ngram
listlengths 0
82k
|
|---|
[
"as _tipi tipi = lambda s: _tipi(s, lang='fr') def test_double_quotes():",
"__future__ import unicode_literals from tipi import tipi as _tipi tipi",
"tipi('''\"brutal\" \"quote's\"''') == ( '''«brutal» «quote's»''' ) def test_single_quotes(): assert",
"import tipi as _tipi tipi = lambda s: _tipi(s, lang='fr')",
"tipi = lambda s: _tipi(s, lang='fr') def test_double_quotes(): assert tipi('''\"brutal\"",
"assert tipi('''\"brutal\" \"quote's\"''') == ( '''«brutal» «quote's»''' ) def test_single_quotes():",
"tipi as _tipi tipi = lambda s: _tipi(s, lang='fr') def",
"<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import unicode_literals",
"\"quote's\"''') == ( '''«brutal» «quote's»''' ) def test_single_quotes(): assert tipi(\"\"\"'brutal'",
"coding: utf-8 -*- from __future__ import unicode_literals from tipi import",
"_tipi tipi = lambda s: _tipi(s, lang='fr') def test_double_quotes(): assert",
"'''«brutal» «quote's»''' ) def test_single_quotes(): assert tipi(\"\"\"'brutal' 'quote's'\"\"\") == (",
"== ( '''«brutal» «quote's»''' ) def test_single_quotes(): assert tipi(\"\"\"'brutal' 'quote's'\"\"\")",
"«quote's»''' ) def test_single_quotes(): assert tipi(\"\"\"'brutal' 'quote's'\"\"\") == ( \"\"\"‹brutal›",
"def test_single_quotes(): assert tipi(\"\"\"'brutal' 'quote's'\"\"\") == ( \"\"\"‹brutal› ‹quote's›\"\"\" )",
"= lambda s: _tipi(s, lang='fr') def test_double_quotes(): assert tipi('''\"brutal\" \"quote's\"''')",
"import unicode_literals from tipi import tipi as _tipi tipi =",
"# -*- coding: utf-8 -*- from __future__ import unicode_literals from",
"s: _tipi(s, lang='fr') def test_double_quotes(): assert tipi('''\"brutal\" \"quote's\"''') == (",
") def test_single_quotes(): assert tipi(\"\"\"'brutal' 'quote's'\"\"\") == ( \"\"\"‹brutal› ‹quote's›\"\"\"",
"unicode_literals from tipi import tipi as _tipi tipi = lambda",
"-*- coding: utf-8 -*- from __future__ import unicode_literals from tipi",
"lang='fr') def test_double_quotes(): assert tipi('''\"brutal\" \"quote's\"''') == ( '''«brutal» «quote's»'''",
"def test_double_quotes(): assert tipi('''\"brutal\" \"quote's\"''') == ( '''«brutal» «quote's»''' )",
"from __future__ import unicode_literals from tipi import tipi as _tipi",
"_tipi(s, lang='fr') def test_double_quotes(): assert tipi('''\"brutal\" \"quote's\"''') == ( '''«brutal»",
"utf-8 -*- from __future__ import unicode_literals from tipi import tipi",
"test_double_quotes(): assert tipi('''\"brutal\" \"quote's\"''') == ( '''«brutal» «quote's»''' ) def",
"( '''«brutal» «quote's»''' ) def test_single_quotes(): assert tipi(\"\"\"'brutal' 'quote's'\"\"\") ==",
"tipi import tipi as _tipi tipi = lambda s: _tipi(s,",
"from tipi import tipi as _tipi tipi = lambda s:",
"-*- from __future__ import unicode_literals from tipi import tipi as",
"lambda s: _tipi(s, lang='fr') def test_double_quotes(): assert tipi('''\"brutal\" \"quote's\"''') =="
] |
[
"Pool(models.Model): id = models.CharField(primary_key=True, max_length=128) name = models.CharField(max_length=128, default='Pool') number",
"= models.CharField(max_length=15, null=True) sam_address = models.CharField(null=True, max_length=128) sam_citystate = models.CharField(null=True,",
"\"Pool {0} - {1}\".format(self.number, self.get_vehicle_display()) class PoolPIID(models.Model): vendor = models.ForeignKey('Vendor')",
"max_length=128) sam_activation_date = models.DateTimeField(null=True) sam_expiration_date = models.DateTimeField(null=True) sam_exclusion = models.NullBooleanField(null=True)",
"sam_address = models.CharField(null=True, max_length=128) sam_citystate = models.CharField(null=True, max_length=128) cm_name =",
"max_length=128) pm_name = models.CharField(null=True, max_length=128) pm_email = models.CharField(null=True, max_length=128) pm_phone",
"Progress'), ('C', 'Completed'), ('F', 'Cancelled') ) class Vendor(models.Model): name =",
"= models.CharField(max_length=128) duns = models.CharField(max_length=9, unique=True) duns_4 = models.CharField(max_length=13, unique=True)",
"pm_email = models.CharField(null=True, max_length=128) pm_phone = models.CharField(null=True, max_length=128) pools =",
"import models VEHICLE_CHOICES = ( ('OASISSB', 'OASIS Small Business'), ('OASIS',",
"max_length=25) def __str__(self): return \"{0} - {1}\".format(self.code, self.description) class SamLoad(models.Model):",
"('C', 'Completed'), ('F', 'Cancelled') ) class Vendor(models.Model): name = models.CharField(max_length=128)",
"= models.CharField(unique=True, max_length=128) short_name = models.CharField(max_length=128) abbreviation = models.CharField(max_length=10, null=True)",
"pm_phone = models.CharField(null=True, max_length=128) pools = models.ManyToManyField('Pool', through='PoolPIID') setasides =",
"= models.CharField(max_length=10, null=True) far_order = models.IntegerField(null=True) def __str__(self): return self.short_name",
"unique=True) duns_4 = models.CharField(max_length=13, unique=True) cage = models.CharField(max_length=15, null=True) sam_address",
"max_length=7) naics = models.ManyToManyField('Naics') threshold = models.CharField(null=True, max_length=128) def __str__(self):",
"models.ForeignKey('Vendor') pool = models.ForeignKey('Pool') piid = models.CharField(max_length=128) def __str__(self): return",
"id = models.CharField(primary_key=True, max_length=128) name = models.CharField(max_length=128, default='Pool') number =",
"class Vendor(models.Model): name = models.CharField(max_length=128) duns = models.CharField(max_length=9, unique=True) duns_4",
"models.CharField(null=True, max_length=128) cm_phone = models.CharField(null=True, max_length=128) pm_name = models.CharField(null=True, max_length=128)",
"__str__(self): return \"{0} - {1} - {2}\".format(self.vendor.name, self.pool.id, self.piid) class",
"= models.IntegerField(null=True) def __str__(self): return self.short_name class Naics(models.Model): code =",
"models.CharField(max_length=128) duns = models.CharField(max_length=9, unique=True) duns_4 = models.CharField(max_length=13, unique=True) cage",
"models.CharField(null=True, max_length=128) pm_email = models.CharField(null=True, max_length=128) pm_phone = models.CharField(null=True, max_length=128)",
"models.CharField(null=True, max_length=128) cm_email = models.CharField(null=True, max_length=128) cm_phone = models.CharField(null=True, max_length=128)",
"= models.CharField(null=True, max_length=128) def __str__(self): return \"Pool {0} - {1}\".format(self.number,",
"__str__(self): return self.short_name class Naics(models.Model): code = models.CharField(max_length=128) description =",
"{2}\".format(self.vendor.name, self.pool.id, self.piid) class SetAside(models.Model): code = models.CharField(unique=True, max_length=128) short_name",
"name = models.CharField(max_length=128) duns = models.CharField(max_length=9, unique=True) duns_4 = models.CharField(max_length=13,",
"Small Business'), ('OASIS', 'OASIS Unrestricted') ) STATUS_CHOICES = ( ('P',",
"null=True) far_order = models.IntegerField(null=True) def __str__(self): return self.short_name class Naics(models.Model):",
"models.CharField(max_length=9, unique=True) duns_4 = models.CharField(max_length=13, unique=True) cage = models.CharField(max_length=15, null=True)",
"= models.CharField(null=True, max_length=128) pm_name = models.CharField(null=True, max_length=128) pm_email = models.CharField(null=True,",
"('OASIS', 'OASIS Unrestricted') ) STATUS_CHOICES = ( ('P', 'In Progress'),",
"{1}\".format(self.number, self.get_vehicle_display()) class PoolPIID(models.Model): vendor = models.ForeignKey('Vendor') pool = models.ForeignKey('Pool')",
"= models.ForeignKey('Pool') piid = models.CharField(max_length=128) def __str__(self): return \"{0} -",
"PoolPIID(models.Model): vendor = models.ForeignKey('Vendor') pool = models.ForeignKey('Pool') piid = models.CharField(max_length=128)",
"max_length=128) short_name = models.CharField(max_length=128) abbreviation = models.CharField(max_length=10, null=True) far_order =",
"max_length=128) sam_citystate = models.CharField(null=True, max_length=128) cm_name = models.CharField(null=True, max_length=128) cm_email",
"description = models.TextField() short_code = models.CharField(unique=True, max_length=25) def __str__(self): return",
"models.NullBooleanField(null=True) sam_url = models.URLField(null=True) annual_revenue = models.BigIntegerField(null=True) number_of_employees = models.IntegerField(null=True)",
"= models.ManyToManyField('Pool', through='PoolPIID') setasides = models.ManyToManyField('SetAside', null=True, blank=True) sam_status =",
"null=True, blank=True) sam_status = models.CharField(null=True, max_length=128) sam_activation_date = models.DateTimeField(null=True) sam_expiration_date",
"models.CharField(max_length=15, null=True) sam_address = models.CharField(null=True, max_length=128) sam_citystate = models.CharField(null=True, max_length=128)",
"return \"{0} - {1} - {2}\".format(self.vendor.name, self.pool.id, self.piid) class SetAside(models.Model):",
"models.ManyToManyField('Naics') threshold = models.CharField(null=True, max_length=128) def __str__(self): return \"Pool {0}",
"= models.CharField(max_length=13, unique=True) cage = models.CharField(max_length=15, null=True) sam_address = models.CharField(null=True,",
"models.CharField(null=True, max_length=128) pm_phone = models.CharField(null=True, max_length=128) pools = models.ManyToManyField('Pool', through='PoolPIID')",
"models.DateTimeField(null=True) sam_exclusion = models.NullBooleanField(null=True) sam_url = models.URLField(null=True) annual_revenue = models.BigIntegerField(null=True)",
"{1} - {2}\".format(self.vendor.name, self.pool.id, self.piid) class SetAside(models.Model): code = models.CharField(unique=True,",
"\"{0} - {1} - {2}\".format(self.vendor.name, self.pool.id, self.piid) class SetAside(models.Model): code",
"= models.CharField(null=True, max_length=128) sam_activation_date = models.DateTimeField(null=True) sam_expiration_date = models.DateTimeField(null=True) sam_exclusion",
"sam_activation_date = models.DateTimeField(null=True) sam_expiration_date = models.DateTimeField(null=True) sam_exclusion = models.NullBooleanField(null=True) sam_url",
"class Pool(models.Model): id = models.CharField(primary_key=True, max_length=128) name = models.CharField(max_length=128, default='Pool')",
"annual_revenue = models.BigIntegerField(null=True) number_of_employees = models.IntegerField(null=True) def __str__(self): return self.name",
"{0} - {1}\".format(self.number, self.get_vehicle_display()) class PoolPIID(models.Model): vendor = models.ForeignKey('Vendor') pool",
"models.CharField(unique=True, max_length=128) short_name = models.CharField(max_length=128) abbreviation = models.CharField(max_length=10, null=True) far_order",
"def __str__(self): return \"Pool {0} - {1}\".format(self.number, self.get_vehicle_display()) class PoolPIID(models.Model):",
"self.pool.id, self.piid) class SetAside(models.Model): code = models.CharField(unique=True, max_length=128) short_name =",
"sam_status = models.CharField(null=True, max_length=128) sam_activation_date = models.DateTimeField(null=True) sam_expiration_date = models.DateTimeField(null=True)",
"'OASIS Small Business'), ('OASIS', 'OASIS Unrestricted') ) STATUS_CHOICES = (",
"def __str__(self): return \"{0} - {1}\".format(self.code, self.description) class SamLoad(models.Model): sam_load",
"pools = models.ManyToManyField('Pool', through='PoolPIID') setasides = models.ManyToManyField('SetAside', null=True, blank=True) sam_status",
"models.CharField(max_length=13, unique=True) cage = models.CharField(max_length=15, null=True) sam_address = models.CharField(null=True, max_length=128)",
"= models.CharField(null=True, max_length=128) pm_email = models.CharField(null=True, max_length=128) pm_phone = models.CharField(null=True,",
"vendor = models.ForeignKey('Vendor') pool = models.ForeignKey('Pool') piid = models.CharField(max_length=128) def",
"'Cancelled') ) class Vendor(models.Model): name = models.CharField(max_length=128) duns = models.CharField(max_length=9,",
"code = models.CharField(unique=True, max_length=128) short_name = models.CharField(max_length=128) abbreviation = models.CharField(max_length=10,",
"Naics(models.Model): code = models.CharField(max_length=128) description = models.TextField() short_code = models.CharField(unique=True,",
"( ('OASISSB', 'OASIS Small Business'), ('OASIS', 'OASIS Unrestricted') ) STATUS_CHOICES",
"self.name class Pool(models.Model): id = models.CharField(primary_key=True, max_length=128) name = models.CharField(max_length=128,",
"cage = models.CharField(max_length=15, null=True) sam_address = models.CharField(null=True, max_length=128) sam_citystate =",
"abbreviation = models.CharField(max_length=10, null=True) far_order = models.IntegerField(null=True) def __str__(self): return",
"= models.CharField(null=True, max_length=128) cm_name = models.CharField(null=True, max_length=128) cm_email = models.CharField(null=True,",
"name = models.CharField(max_length=128, default='Pool') number = models.CharField(max_length=128) vehicle = models.CharField(choices=VEHICLE_CHOICES,",
"sam_exclusion = models.NullBooleanField(null=True) sam_url = models.URLField(null=True) annual_revenue = models.BigIntegerField(null=True) number_of_employees",
"= models.CharField(max_length=128, default='Pool') number = models.CharField(max_length=128) vehicle = models.CharField(choices=VEHICLE_CHOICES, max_length=7)",
"vehicle = models.CharField(choices=VEHICLE_CHOICES, max_length=7) naics = models.ManyToManyField('Naics') threshold = models.CharField(null=True,",
"- {1} - {2}\".format(self.vendor.name, self.pool.id, self.piid) class SetAside(models.Model): code =",
"return \"{0} - {1}\".format(self.code, self.description) class SamLoad(models.Model): sam_load = models.DateField()",
"Vendor(models.Model): name = models.CharField(max_length=128) duns = models.CharField(max_length=9, unique=True) duns_4 =",
"= models.CharField(null=True, max_length=128) cm_phone = models.CharField(null=True, max_length=128) pm_name = models.CharField(null=True,",
"duns = models.CharField(max_length=9, unique=True) duns_4 = models.CharField(max_length=13, unique=True) cage =",
"= models.CharField(max_length=128) abbreviation = models.CharField(max_length=10, null=True) far_order = models.IntegerField(null=True) def",
"max_length=128) name = models.CharField(max_length=128, default='Pool') number = models.CharField(max_length=128) vehicle =",
"= models.URLField(null=True) annual_revenue = models.BigIntegerField(null=True) number_of_employees = models.IntegerField(null=True) def __str__(self):",
"models.CharField(max_length=128) def __str__(self): return \"{0} - {1} - {2}\".format(self.vendor.name, self.pool.id,",
"cm_name = models.CharField(null=True, max_length=128) cm_email = models.CharField(null=True, max_length=128) cm_phone =",
"= models.CharField(max_length=128) def __str__(self): return \"{0} - {1} - {2}\".format(self.vendor.name,",
"= models.CharField(max_length=9, unique=True) duns_4 = models.CharField(max_length=13, unique=True) cage = models.CharField(max_length=15,",
"models.URLField(null=True) annual_revenue = models.BigIntegerField(null=True) number_of_employees = models.IntegerField(null=True) def __str__(self): return",
"VEHICLE_CHOICES = ( ('OASISSB', 'OASIS Small Business'), ('OASIS', 'OASIS Unrestricted')",
"number_of_employees = models.IntegerField(null=True) def __str__(self): return self.name class Pool(models.Model): id",
"SetAside(models.Model): code = models.CharField(unique=True, max_length=128) short_name = models.CharField(max_length=128) abbreviation =",
"models.CharField(null=True, max_length=128) pools = models.ManyToManyField('Pool', through='PoolPIID') setasides = models.ManyToManyField('SetAside', null=True,",
"setasides = models.ManyToManyField('SetAside', null=True, blank=True) sam_status = models.CharField(null=True, max_length=128) sam_activation_date",
"= ( ('P', 'In Progress'), ('C', 'Completed'), ('F', 'Cancelled') )",
"sam_url = models.URLField(null=True) annual_revenue = models.BigIntegerField(null=True) number_of_employees = models.IntegerField(null=True) def",
"duns_4 = models.CharField(max_length=13, unique=True) cage = models.CharField(max_length=15, null=True) sam_address =",
"models.CharField(max_length=10, null=True) far_order = models.IntegerField(null=True) def __str__(self): return self.short_name class",
"<gh_stars>1-10 from django.db import models VEHICLE_CHOICES = ( ('OASISSB', 'OASIS",
"Business'), ('OASIS', 'OASIS Unrestricted') ) STATUS_CHOICES = ( ('P', 'In",
"= models.CharField(unique=True, max_length=25) def __str__(self): return \"{0} - {1}\".format(self.code, self.description)",
"= models.CharField(choices=VEHICLE_CHOICES, max_length=7) naics = models.ManyToManyField('Naics') threshold = models.CharField(null=True, max_length=128)",
"blank=True) sam_status = models.CharField(null=True, max_length=128) sam_activation_date = models.DateTimeField(null=True) sam_expiration_date =",
"= models.CharField(primary_key=True, max_length=128) name = models.CharField(max_length=128, default='Pool') number = models.CharField(max_length=128)",
"models.IntegerField(null=True) def __str__(self): return self.name class Pool(models.Model): id = models.CharField(primary_key=True,",
"class PoolPIID(models.Model): vendor = models.ForeignKey('Vendor') pool = models.ForeignKey('Pool') piid =",
"models.IntegerField(null=True) def __str__(self): return self.short_name class Naics(models.Model): code = models.CharField(max_length=128)",
"models.CharField(unique=True, max_length=25) def __str__(self): return \"{0} - {1}\".format(self.code, self.description) class",
"= models.TextField() short_code = models.CharField(unique=True, max_length=25) def __str__(self): return \"{0}",
"default='Pool') number = models.CharField(max_length=128) vehicle = models.CharField(choices=VEHICLE_CHOICES, max_length=7) naics =",
"'In Progress'), ('C', 'Completed'), ('F', 'Cancelled') ) class Vendor(models.Model): name",
"models.CharField(max_length=128, default='Pool') number = models.CharField(max_length=128) vehicle = models.CharField(choices=VEHICLE_CHOICES, max_length=7) naics",
"= models.ForeignKey('Vendor') pool = models.ForeignKey('Pool') piid = models.CharField(max_length=128) def __str__(self):",
"models.CharField(primary_key=True, max_length=128) name = models.CharField(max_length=128, default='Pool') number = models.CharField(max_length=128) vehicle",
"('P', 'In Progress'), ('C', 'Completed'), ('F', 'Cancelled') ) class Vendor(models.Model):",
"Unrestricted') ) STATUS_CHOICES = ( ('P', 'In Progress'), ('C', 'Completed'),",
"max_length=128) cm_email = models.CharField(null=True, max_length=128) cm_phone = models.CharField(null=True, max_length=128) pm_name",
"models.DateTimeField(null=True) sam_expiration_date = models.DateTimeField(null=True) sam_exclusion = models.NullBooleanField(null=True) sam_url = models.URLField(null=True)",
"max_length=128) pools = models.ManyToManyField('Pool', through='PoolPIID') setasides = models.ManyToManyField('SetAside', null=True, blank=True)",
"models.CharField(null=True, max_length=128) pm_name = models.CharField(null=True, max_length=128) pm_email = models.CharField(null=True, max_length=128)",
"unique=True) cage = models.CharField(max_length=15, null=True) sam_address = models.CharField(null=True, max_length=128) sam_citystate",
"models.CharField(null=True, max_length=128) sam_citystate = models.CharField(null=True, max_length=128) cm_name = models.CharField(null=True, max_length=128)",
"threshold = models.CharField(null=True, max_length=128) def __str__(self): return \"Pool {0} -",
"pool = models.ForeignKey('Pool') piid = models.CharField(max_length=128) def __str__(self): return \"{0}",
"models.CharField(max_length=128) abbreviation = models.CharField(max_length=10, null=True) far_order = models.IntegerField(null=True) def __str__(self):",
") STATUS_CHOICES = ( ('P', 'In Progress'), ('C', 'Completed'), ('F',",
"models.CharField(null=True, max_length=128) sam_activation_date = models.DateTimeField(null=True) sam_expiration_date = models.DateTimeField(null=True) sam_exclusion =",
"- {2}\".format(self.vendor.name, self.pool.id, self.piid) class SetAside(models.Model): code = models.CharField(unique=True, max_length=128)",
"pm_name = models.CharField(null=True, max_length=128) pm_email = models.CharField(null=True, max_length=128) pm_phone =",
"django.db import models VEHICLE_CHOICES = ( ('OASISSB', 'OASIS Small Business'),",
") class Vendor(models.Model): name = models.CharField(max_length=128) duns = models.CharField(max_length=9, unique=True)",
"max_length=128) cm_name = models.CharField(null=True, max_length=128) cm_email = models.CharField(null=True, max_length=128) cm_phone",
"through='PoolPIID') setasides = models.ManyToManyField('SetAside', null=True, blank=True) sam_status = models.CharField(null=True, max_length=128)",
"def __str__(self): return self.name class Pool(models.Model): id = models.CharField(primary_key=True, max_length=128)",
"short_code = models.CharField(unique=True, max_length=25) def __str__(self): return \"{0} - {1}\".format(self.code,",
"= ( ('OASISSB', 'OASIS Small Business'), ('OASIS', 'OASIS Unrestricted') )",
"def __str__(self): return self.short_name class Naics(models.Model): code = models.CharField(max_length=128) description",
"- {1}\".format(self.number, self.get_vehicle_display()) class PoolPIID(models.Model): vendor = models.ForeignKey('Vendor') pool =",
"= models.CharField(max_length=128) description = models.TextField() short_code = models.CharField(unique=True, max_length=25) def",
"models.CharField(max_length=128) description = models.TextField() short_code = models.CharField(unique=True, max_length=25) def __str__(self):",
"models VEHICLE_CHOICES = ( ('OASISSB', 'OASIS Small Business'), ('OASIS', 'OASIS",
"return self.short_name class Naics(models.Model): code = models.CharField(max_length=128) description = models.TextField()",
"null=True) sam_address = models.CharField(null=True, max_length=128) sam_citystate = models.CharField(null=True, max_length=128) cm_name",
"piid = models.CharField(max_length=128) def __str__(self): return \"{0} - {1} -",
"sam_citystate = models.CharField(null=True, max_length=128) cm_name = models.CharField(null=True, max_length=128) cm_email =",
"= models.CharField(null=True, max_length=128) pools = models.ManyToManyField('Pool', through='PoolPIID') setasides = models.ManyToManyField('SetAside',",
"sam_expiration_date = models.DateTimeField(null=True) sam_exclusion = models.NullBooleanField(null=True) sam_url = models.URLField(null=True) annual_revenue",
"cm_email = models.CharField(null=True, max_length=128) cm_phone = models.CharField(null=True, max_length=128) pm_name =",
"max_length=128) def __str__(self): return \"Pool {0} - {1}\".format(self.number, self.get_vehicle_display()) class",
"max_length=128) cm_phone = models.CharField(null=True, max_length=128) pm_name = models.CharField(null=True, max_length=128) pm_email",
"models.CharField(null=True, max_length=128) cm_name = models.CharField(null=True, max_length=128) cm_email = models.CharField(null=True, max_length=128)",
"= models.ManyToManyField('SetAside', null=True, blank=True) sam_status = models.CharField(null=True, max_length=128) sam_activation_date =",
"__str__(self): return \"{0} - {1}\".format(self.code, self.description) class SamLoad(models.Model): sam_load =",
"'Completed'), ('F', 'Cancelled') ) class Vendor(models.Model): name = models.CharField(max_length=128) duns",
"self.piid) class SetAside(models.Model): code = models.CharField(unique=True, max_length=128) short_name = models.CharField(max_length=128)",
"class Naics(models.Model): code = models.CharField(max_length=128) description = models.TextField() short_code =",
"models.CharField(null=True, max_length=128) def __str__(self): return \"Pool {0} - {1}\".format(self.number, self.get_vehicle_display())",
"max_length=128) pm_email = models.CharField(null=True, max_length=128) pm_phone = models.CharField(null=True, max_length=128) pools",
"= models.DateTimeField(null=True) sam_expiration_date = models.DateTimeField(null=True) sam_exclusion = models.NullBooleanField(null=True) sam_url =",
"models.ForeignKey('Pool') piid = models.CharField(max_length=128) def __str__(self): return \"{0} - {1}",
"= models.CharField(null=True, max_length=128) sam_citystate = models.CharField(null=True, max_length=128) cm_name = models.CharField(null=True,",
"max_length=128) pm_phone = models.CharField(null=True, max_length=128) pools = models.ManyToManyField('Pool', through='PoolPIID') setasides",
"models.TextField() short_code = models.CharField(unique=True, max_length=25) def __str__(self): return \"{0} -",
"= models.NullBooleanField(null=True) sam_url = models.URLField(null=True) annual_revenue = models.BigIntegerField(null=True) number_of_employees =",
"'OASIS Unrestricted') ) STATUS_CHOICES = ( ('P', 'In Progress'), ('C',",
"self.get_vehicle_display()) class PoolPIID(models.Model): vendor = models.ForeignKey('Vendor') pool = models.ForeignKey('Pool') piid",
"models.CharField(max_length=128) vehicle = models.CharField(choices=VEHICLE_CHOICES, max_length=7) naics = models.ManyToManyField('Naics') threshold =",
"code = models.CharField(max_length=128) description = models.TextField() short_code = models.CharField(unique=True, max_length=25)",
"STATUS_CHOICES = ( ('P', 'In Progress'), ('C', 'Completed'), ('F', 'Cancelled')",
"= models.ManyToManyField('Naics') threshold = models.CharField(null=True, max_length=128) def __str__(self): return \"Pool",
"models.ManyToManyField('SetAside', null=True, blank=True) sam_status = models.CharField(null=True, max_length=128) sam_activation_date = models.DateTimeField(null=True)",
"self.short_name class Naics(models.Model): code = models.CharField(max_length=128) description = models.TextField() short_code",
"naics = models.ManyToManyField('Naics') threshold = models.CharField(null=True, max_length=128) def __str__(self): return",
"('F', 'Cancelled') ) class Vendor(models.Model): name = models.CharField(max_length=128) duns =",
"cm_phone = models.CharField(null=True, max_length=128) pm_name = models.CharField(null=True, max_length=128) pm_email =",
"models.CharField(choices=VEHICLE_CHOICES, max_length=7) naics = models.ManyToManyField('Naics') threshold = models.CharField(null=True, max_length=128) def",
"= models.CharField(max_length=128) vehicle = models.CharField(choices=VEHICLE_CHOICES, max_length=7) naics = models.ManyToManyField('Naics') threshold",
"short_name = models.CharField(max_length=128) abbreviation = models.CharField(max_length=10, null=True) far_order = models.IntegerField(null=True)",
"( ('P', 'In Progress'), ('C', 'Completed'), ('F', 'Cancelled') ) class",
"= models.BigIntegerField(null=True) number_of_employees = models.IntegerField(null=True) def __str__(self): return self.name class",
"= models.IntegerField(null=True) def __str__(self): return self.name class Pool(models.Model): id =",
"__str__(self): return \"Pool {0} - {1}\".format(self.number, self.get_vehicle_display()) class PoolPIID(models.Model): vendor",
"return self.name class Pool(models.Model): id = models.CharField(primary_key=True, max_length=128) name =",
"= models.CharField(null=True, max_length=128) pm_phone = models.CharField(null=True, max_length=128) pools = models.ManyToManyField('Pool',",
"models.BigIntegerField(null=True) number_of_employees = models.IntegerField(null=True) def __str__(self): return self.name class Pool(models.Model):",
"def __str__(self): return \"{0} - {1} - {2}\".format(self.vendor.name, self.pool.id, self.piid)",
"number = models.CharField(max_length=128) vehicle = models.CharField(choices=VEHICLE_CHOICES, max_length=7) naics = models.ManyToManyField('Naics')",
"class SetAside(models.Model): code = models.CharField(unique=True, max_length=128) short_name = models.CharField(max_length=128) abbreviation",
"return \"Pool {0} - {1}\".format(self.number, self.get_vehicle_display()) class PoolPIID(models.Model): vendor =",
"= models.CharField(null=True, max_length=128) cm_email = models.CharField(null=True, max_length=128) cm_phone = models.CharField(null=True,",
"models.ManyToManyField('Pool', through='PoolPIID') setasides = models.ManyToManyField('SetAside', null=True, blank=True) sam_status = models.CharField(null=True,",
"= models.DateTimeField(null=True) sam_exclusion = models.NullBooleanField(null=True) sam_url = models.URLField(null=True) annual_revenue =",
"__str__(self): return self.name class Pool(models.Model): id = models.CharField(primary_key=True, max_length=128) name",
"('OASISSB', 'OASIS Small Business'), ('OASIS', 'OASIS Unrestricted') ) STATUS_CHOICES =",
"from django.db import models VEHICLE_CHOICES = ( ('OASISSB', 'OASIS Small",
"far_order = models.IntegerField(null=True) def __str__(self): return self.short_name class Naics(models.Model): code"
] |
[
"- - WRITE DOCUMENTATION HERE - - - \"\"\" def",
"DOCUMENTATION HERE - - - \"\"\" def __init__(self): \"\"\" Initialise",
"def __call__(self, register): \"\"\" Run the circuit on a given",
"- \"\"\" def __init__(self): \"\"\" Initialise a QuantumCircuit object \"\"\"",
"\"\"\" Initialise a QuantumCircuit object \"\"\" pass def add_gate(self, gate):",
"\"\"\" Implements a quantum circuit. - - - WRITE DOCUMENTATION",
"QuantumCircuit class boom. \"\"\" class QuantumCircuit(object): # pylint: disable=useless-object-inheritance \"\"\"",
"Implements a quantum circuit. - - - WRITE DOCUMENTATION HERE",
"gate): \"\"\" Add a gate to the circuit \"\"\" pass",
"boom. \"\"\" class QuantumCircuit(object): # pylint: disable=useless-object-inheritance \"\"\" Implements a",
"circuit. - - - WRITE DOCUMENTATION HERE - - -",
"to the circuit \"\"\" pass def run_circuit(self, register): \"\"\" Run",
"on a given quantum register \"\"\" pass def __call__(self, register):",
"register \"\"\" pass def __call__(self, register): \"\"\" Run the circuit",
"circuit on a given quantum register \"\"\" pass def __call__(self,",
"- - \"\"\" def __init__(self): \"\"\" Initialise a QuantumCircuit object",
"quantum circuit. - - - WRITE DOCUMENTATION HERE - -",
"the circuit \"\"\" pass def run_circuit(self, register): \"\"\" Run the",
"Add a gate to the circuit \"\"\" pass def run_circuit(self,",
"a quantum circuit. - - - WRITE DOCUMENTATION HERE -",
"- - - WRITE DOCUMENTATION HERE - - - \"\"\"",
"- WRITE DOCUMENTATION HERE - - - \"\"\" def __init__(self):",
"object \"\"\" pass def add_gate(self, gate): \"\"\" Add a gate",
"pass def add_gate(self, gate): \"\"\" Add a gate to the",
"__init__(self): \"\"\" Initialise a QuantumCircuit object \"\"\" pass def add_gate(self,",
"class boom. \"\"\" class QuantumCircuit(object): # pylint: disable=useless-object-inheritance \"\"\" Implements",
"# pylint: disable=useless-object-inheritance \"\"\" Implements a quantum circuit. - -",
"HERE - - - \"\"\" def __init__(self): \"\"\" Initialise a",
"class QuantumCircuit(object): # pylint: disable=useless-object-inheritance \"\"\" Implements a quantum circuit.",
"register): \"\"\" Run the circuit on a given quantum register",
"the circuit on a given quantum register \"\"\" pass def",
"quantum register \"\"\" pass def __call__(self, register): \"\"\" Run the",
"Contains the QuantumCircuit class boom. \"\"\" class QuantumCircuit(object): # pylint:",
"def run_circuit(self, register): \"\"\" Run the circuit on a given",
"WRITE DOCUMENTATION HERE - - - \"\"\" def __init__(self): \"\"\"",
"gate to the circuit \"\"\" pass def run_circuit(self, register): \"\"\"",
"\"\"\" Contains the QuantumCircuit class boom. \"\"\" class QuantumCircuit(object): #",
"\"\"\" pass def add_gate(self, gate): \"\"\" Add a gate to",
"- - - \"\"\" def __init__(self): \"\"\" Initialise a QuantumCircuit",
"\"\"\" Add a gate to the circuit \"\"\" pass def",
"pass def run_circuit(self, register): \"\"\" Run the circuit on a",
"a QuantumCircuit object \"\"\" pass def add_gate(self, gate): \"\"\" Add",
"the QuantumCircuit class boom. \"\"\" class QuantumCircuit(object): # pylint: disable=useless-object-inheritance",
"a gate to the circuit \"\"\" pass def run_circuit(self, register):",
"\"\"\" Run the circuit on a given quantum register \"\"\"",
"\"\"\" pass def run_circuit(self, register): \"\"\" Run the circuit on",
"def __init__(self): \"\"\" Initialise a QuantumCircuit object \"\"\" pass def",
"Run the circuit on a given quantum register \"\"\" pass",
"\"\"\" class QuantumCircuit(object): # pylint: disable=useless-object-inheritance \"\"\" Implements a quantum",
"add_gate(self, gate): \"\"\" Add a gate to the circuit \"\"\"",
"\"\"\" def __init__(self): \"\"\" Initialise a QuantumCircuit object \"\"\" pass",
"def add_gate(self, gate): \"\"\" Add a gate to the circuit",
"\"\"\" pass def __call__(self, register): \"\"\" Run the circuit on",
"given quantum register \"\"\" pass def __call__(self, register): \"\"\" Run",
"run_circuit(self, register): \"\"\" Run the circuit on a given quantum",
"a given quantum register \"\"\" pass def __call__(self, register): \"\"\"",
"pass def __call__(self, register): \"\"\" Run the circuit on a",
"circuit \"\"\" pass def run_circuit(self, register): \"\"\" Run the circuit",
"disable=useless-object-inheritance \"\"\" Implements a quantum circuit. - - - WRITE",
"Initialise a QuantumCircuit object \"\"\" pass def add_gate(self, gate): \"\"\"",
"QuantumCircuit object \"\"\" pass def add_gate(self, gate): \"\"\" Add a",
"QuantumCircuit(object): # pylint: disable=useless-object-inheritance \"\"\" Implements a quantum circuit. -",
"pylint: disable=useless-object-inheritance \"\"\" Implements a quantum circuit. - - -",
"__call__(self, register): \"\"\" Run the circuit on a given quantum"
] |
[
"class hydrographyWaterbody = r\"\" # path to NHD water body",
"hydrographyWaterbody = r\"\" # path to NHD water body feature",
"= r\"\" # path to NHD area feature class hydrographyFlowline",
"r\"\" # path to geodatabase to use as a workspace",
"path to geodatabase to use as a workspace snapGrid =",
"feature class hydrographyFlowline = r\"\" # path to NHD flowline",
"path to NHD area feature class hydrographyFlowline = r\"\" #",
"r\"\" # path to NHD flowline feature class hydrographyWaterbody =",
"import bathymetricGradient workspace = r\"\" # path to geodatabase to",
"as a workspace snapGrid = r\"\" # path to snapping",
"# path to NHD area feature class hydrographyFlowline = r\"\"",
"workspace = r\"\" # path to geodatabase to use as",
"import sys sys.path.append(\"..\") # change environment to see tools from",
"class cellsize = '' # cell size bathymetricGradient(workspace, snapGrid, hucPoly,",
"polygon hydrographyArea = r\"\" # path to NHD area feature",
"tools from make_hydrodem import bathymetricGradient workspace = r\"\" # path",
"# path to snapping grid hucPoly = r\"\" # path",
"= r\"\" # path to NHD flowline feature class hydrographyWaterbody",
"to NHD flowline feature class hydrographyWaterbody = r\"\" # path",
"use as a workspace snapGrid = r\"\" # path to",
"r\"\" # path to snapping grid hucPoly = r\"\" #",
"hucPoly = r\"\" # path to local folder polygon hydrographyArea",
"# path to NHD water body feature class cellsize =",
"= r\"\" # path to NHD water body feature class",
"from make_hydrodem import bathymetricGradient workspace = r\"\" # path to",
"= '' # cell size bathymetricGradient(workspace, snapGrid, hucPoly, hydrographyArea, hydrographyFlowline,",
"sys sys.path.append(\"..\") # change environment to see tools from make_hydrodem",
"# path to geodatabase to use as a workspace snapGrid",
"path to local folder polygon hydrographyArea = r\"\" # path",
"grid hucPoly = r\"\" # path to local folder polygon",
"to NHD area feature class hydrographyFlowline = r\"\" # path",
"folder polygon hydrographyArea = r\"\" # path to NHD area",
"to NHD water body feature class cellsize = '' #",
"r\"\" # path to NHD water body feature class cellsize",
"to geodatabase to use as a workspace snapGrid = r\"\"",
"= r\"\" # path to snapping grid hucPoly = r\"\"",
"= r\"\" # path to local folder polygon hydrographyArea =",
"# path to local folder polygon hydrographyArea = r\"\" #",
"feature class hydrographyWaterbody = r\"\" # path to NHD water",
"a workspace snapGrid = r\"\" # path to snapping grid",
"path to snapping grid hucPoly = r\"\" # path to",
"r\"\" # path to local folder polygon hydrographyArea = r\"\"",
"area feature class hydrographyFlowline = r\"\" # path to NHD",
"flowline feature class hydrographyWaterbody = r\"\" # path to NHD",
"make_hydrodem import bathymetricGradient workspace = r\"\" # path to geodatabase",
"to use as a workspace snapGrid = r\"\" # path",
"path to NHD water body feature class cellsize = ''",
"local folder polygon hydrographyArea = r\"\" # path to NHD",
"to local folder polygon hydrographyArea = r\"\" # path to",
"'' # cell size bathymetricGradient(workspace, snapGrid, hucPoly, hydrographyArea, hydrographyFlowline, hydrographyWaterbody,cellsize)",
"to see tools from make_hydrodem import bathymetricGradient workspace = r\"\"",
"= r\"\" # path to geodatabase to use as a",
"hydrographyFlowline = r\"\" # path to NHD flowline feature class",
"path to NHD flowline feature class hydrographyWaterbody = r\"\" #",
"water body feature class cellsize = '' # cell size",
"cellsize = '' # cell size bathymetricGradient(workspace, snapGrid, hucPoly, hydrographyArea,",
"workspace snapGrid = r\"\" # path to snapping grid hucPoly",
"bathymetricGradient workspace = r\"\" # path to geodatabase to use",
"see tools from make_hydrodem import bathymetricGradient workspace = r\"\" #",
"snapGrid = r\"\" # path to snapping grid hucPoly =",
"sys.path.append(\"..\") # change environment to see tools from make_hydrodem import",
"to snapping grid hucPoly = r\"\" # path to local",
"NHD area feature class hydrographyFlowline = r\"\" # path to",
"body feature class cellsize = '' # cell size bathymetricGradient(workspace,",
"snapping grid hucPoly = r\"\" # path to local folder",
"class hydrographyFlowline = r\"\" # path to NHD flowline feature",
"# path to NHD flowline feature class hydrographyWaterbody = r\"\"",
"r\"\" # path to NHD area feature class hydrographyFlowline =",
"geodatabase to use as a workspace snapGrid = r\"\" #",
"change environment to see tools from make_hydrodem import bathymetricGradient workspace",
"feature class cellsize = '' # cell size bathymetricGradient(workspace, snapGrid,",
"# change environment to see tools from make_hydrodem import bathymetricGradient",
"NHD water body feature class cellsize = '' # cell",
"environment to see tools from make_hydrodem import bathymetricGradient workspace =",
"NHD flowline feature class hydrographyWaterbody = r\"\" # path to",
"hydrographyArea = r\"\" # path to NHD area feature class"
] |
[
"and cancellation NO_EDIT = 0 EDIT = 1 ADD =",
"class FlowLineContext( BaseContext ): '''Context for drawing, creating and editing",
"OpenGL context for drawing flow calculation lines from Context import",
"edited, the original disappears and the new line is drawn",
"from OpenGL.GL import * from copy import deepcopy class GLFlowSegment(",
"idx ): '''Sets the active line''' self.activeID = idx def",
"from p1 to p2.''' def __init__( self, p1, p2 ):",
"in context.names ] self.lines = deepcopy( context.lines ) def clear(",
"name per line. @param lines A list of Segment instaces.",
"glVertex2f( end.x, end.y ) glEnd() glPopAttrib() class FlowLineContext( BaseContext ):",
"yellow, and when it is being edited, the original disappears",
"): '''Draw the flow segment into a GL context. @param",
"): \"\"\"Detects click, drag, release and creates a line\"\"\" result",
"glVertex2f( self.p2.x, self.p2.y ) mp = self.midPoint() l = self.magnitude()",
"names, lines ): '''Sets the lines in the context with",
"( self.dragging ): x, y = view.screenToWorld( ( eX, eY",
"self.midPoint() l = self.magnitude() n = self.normal() * (0.25 *",
"self.editCB = editCB self.activeLine = None self.canDraw = False self.dragging",
"out all of the lines''' self.lines = [] self.names =",
"context to go into new line mode. Returning the new",
"list of strings. One name per line. @param lines A",
"GLFlowSegment( x.p1, x.p2 ), lines ) self.names = names self.activeID",
"self.notifyEdit( self.activeLine ) return result def notifyEdit( self, line ):",
") def clear( self ): '''Clears out all of the",
"self.EDIT ): assert( self.activeID > -1 ) self.lines[ self.activeID ]",
"= -1 self.editState = self.NO_EDIT def handleMouse ( self, evt,",
"= None self.dragging = False result.set( canceled, canceled, False )",
"of lines. @return A string. The stored name. ''' return",
"): return \"GLFlowSegment (%s, %s)\" % ( self.p1, self.p2 )",
"self.editState = self.EDIT self.notifyEdit( self.activeLine ) elif ( self.editState ==",
"= self.activeLine self.notifyEdit( self.activeLine ) self.activeLine = None self.activeLine =",
"self, p1, p2 ): '''Constructor. @param p1 An instance of",
"''' return self.names[ id ] def getLine( self, id ):",
"e: return result if ( not self.canDraw ): return result",
"p2.''' def __init__( self, p1, p2 ): '''Constructor. @param p1",
"self.lines[ self.activeID ].drawGL( ( 1.0, 1.0, 0.1 ) ) for",
"): '''Sets the name for the line with the given",
"self.activeID > -1 and self.editState != self.ADD ): self.lines[ self.activeID",
"into this''' assert( isinstance( context, FlowLineContext ) ) self.clear() self.names",
"len( self.lines ) def getName( self, id ): '''Returns the",
"self.activeLine ) elif ( self.editState == self.EDIT ): assert( self.activeID",
"result = ContextResult() try: event = self.canonicalEvent( evt ) except",
"self.canDraw = False self.dragging = False self.downPost = None def",
"line ) def drawGL( self ): '''Basic lines are drawn",
"drawn in cyan.''' if ( self.activeLine ): self.activeLine.drawGL( ( 0.1,",
"for drawing flow calculation lines from Context import * from",
"addLine( self ): '''Causes the context to go into new",
"False ) elif ( event.type == MouseEvent.UP ): if (",
"ADD = 2 def __init__( self, cancelCB=None, editCB=None ): '''Constructor.",
"x.p2 ), lines ) self.names = names self.activeID = -1",
"affected by modifications self.editState = self.NO_EDIT self.cancelCB = cancelCB self.editCB",
"GL_LINES ) glColor3fv( color ) glVertex2f( self.p1.x, self.p1.y ) glVertex2f(",
"GL context. @param A 3-tuple of floats. The color of",
"line\"\"\" result = ContextResult() try: event = self.canonicalEvent( evt )",
"eY ) ) p1 = Vector2( x, y ) self.activeLine",
"True, True, False ) self.dragging = True self.notifyEdit( self.activeLine )",
"self.names.pop(-1) if ( not self.cancelCB is None ): self.cancelCB() self.notifyEdit(",
"= -1 self.names.append( 'Line %d' % len( self.names ) )",
"self.names.pop( idx ) self.activeID = -1 def flipLine( self, idx",
"segment. @param p2 An instance of Vector2. The end point",
"has changed''' if ( not self.editCB is None ): self.editCB(",
"the new name.''' self.canDraw = True self.editState = self.ADD self.activeID",
"( self.activeID > -1 and self.editState != self.ADD ): self.lines[",
"getName( self, id ): '''Returns the name associated with the",
") canceled = self.activeLine != None self.activeLine = None self.dragging",
"= self.lines[-1] return self.names[-1] def editLine( self, idx ): '''Edits",
"line from the set''' assert( idx >= 0 and idx",
"is None ): self.cancelCB() self.notifyEdit( None ) canceled = self.activeLine",
"# the minimum drag required to draw a line #",
"''' Segment.__init__( self, p1, p2 ) def __str__( self ):",
"True self.editState = self.ADD self.activeID = -1 self.names.append( 'Line %d'",
"An optional callback object for when flow line drawing is",
"): if ( self.dragging ): x, y = view.screenToWorld( (",
"1], to be interpreted as r, g, b color values.",
"this''' assert( isinstance( context, FlowLineContext ) ) self.clear() self.names =",
"] def addLine( self ): '''Causes the context to go",
"return result def notifyEdit( self, line ): '''Notifies call back",
"( event.type == MouseEvent.DOWN ): #QtCore.QEvent.MouseButtonPress ): if ( btn",
"GLFlowSegment( Vector2(0, 0), Vector2(0, 0) ) ) self.activeLine = self.lines[-1]",
"new line mode. Returning the new name.''' self.canDraw = True",
"= False def getLineCount( self ): \"\"\"Returns the number of",
"id ] def getLine( self, id ): '''Returns the name",
"drag, release and creates a line\"\"\" result = ContextResult() try:",
"eX = event.x eY = event.y if ( event.type ==",
"edit if ( self.editState == self.ADD ): self.editState = self.NO_EDIT",
"( eX, eY ) ) p2 = Vector2( x, y",
"is None ): self.editCB( line ) def drawGL( self ):",
"].drawGL( ( 1.0, 1.0, 0.1 ) ) for i, line",
"line drawing is canceled. @param editCB A callable. An optional",
"self.canDraw = False self.activeID = -1 else: self.editState = self.EDIT",
"): return len( self.lines ) def getName( self, id ):",
"values. ''' glPushAttrib( GL_COLOR_BUFFER_BIT ) glBegin( GL_LINES ) glColor3fv( color",
"self.editState = self.ADD self.activeID = -1 self.names.append( 'Line %d' %",
"lineCount( self ): return len( self.lines ) def getName( self,",
"( not self.editCB is None ): self.editCB( line ) def",
"@return An instance of a FlowLine. ''' return self.lines[ id",
"if ( idx < 0 ): self.editState = self.NO_EDIT self.canDraw",
"'''Causes the context to go into new line mode. Returning",
"drawn in yellow, and when it is being edited, the",
"the set''' assert( idx >= 0 and idx < len(",
"point of the segment. ''' Segment.__init__( self, p1, p2 )",
"= 0 EDIT = 1 ADD = 2 def __init__(",
">= 0 and idx < len( self.lines ) ) self.lines[",
"lines in the context with the given names and lines.",
") - 1 self.lines[self.activeID] = self.activeLine self.editState = self.EDIT self.notifyEdit(",
") self.names = names self.activeID = -1 self.editState = self.NO_EDIT",
") elif ( event.type == MouseEvent.MOVE ): if ( self.dragging",
"in default (green), the active line is drawn in yellow,",
"is drawn in yellow, and when it is being edited,",
") def drawGL( self ): '''Basic lines are drawn in",
"= False self.activeID = -1 else: self.editState = self.EDIT self.canDraw",
"self.cancelCB = cancelCB self.editCB = editCB self.activeLine = None self.canDraw",
"for the line with the given index''' self.names[ idx ]",
"flow line values are edited. ''' BaseContext.__init__( self ) self.lines",
"import deepcopy class GLFlowSegment( Segment ): '''The OpenGL representation of",
"p1 ) result.set( True, True, False ) self.dragging = True",
"self.notifyEdit( self.activeLine ) elif ( btn == MouseEvent.RIGHT and self.dragging",
"( self.editState == self.ADD): return if ( idx < 0",
"is canceled. @param editCB A callable. An optional callback object",
"'''Stops the ability to edit''' self.editState = self.NO_EDIT self.canDraw =",
"False self.downPost = None def copy( self, context ): '''Copy",
"into a GL context. @param A 3-tuple of floats. The",
"idx ].flip() def setActive( self, idx ): '''Sets the active",
"name associated with the line index, id. @param id An",
"= self.activeLine self.editState = self.EDIT self.notifyEdit( self.activeLine ) elif (",
"False result.set( True, True, False ) elif ( event.type ==",
"self.editCB is None ): self.editCB( line ) def drawGL( self",
"lines ): '''Sets the lines in the context with the",
"Returning the new name.''' self.canDraw = True self.editState = self.ADD",
"self.downPost = None def copy( self, context ): '''Copy the",
"x, y = view.screenToWorld( ( eX, eY ) ) p1",
"and self.dragging ): # cancel the edit if ( self.editState",
"when a flow line values are edited. ''' BaseContext.__init__( self",
"+ n glVertex2f( mp.x, mp.y ) glVertex2f( end.x, end.y )",
"cancel the edit if ( self.editState == self.ADD ): self.editState",
"@param id An integer. The index into the stored set",
"self, id ): '''Returns the name associated with the line",
"idx ) self.names.pop( idx ) self.activeID = -1 def flipLine(",
"): '''Constructor. @param p1 An instance of Vector2. The start",
"stopEdit( self ): '''Stops the ability to edit''' self.editState =",
") elif ( btn == MouseEvent.RIGHT and self.dragging ): #",
"): self.lines[ self.activeID ].drawGL( ( 1.0, 1.0, 0.1 ) )",
"a segment with a direciton indicator. The direction indicator shows",
"self.editState == self.ADD): return if ( idx < 0 ):",
"x.p1, x.p2 ), lines ) self.names = names self.activeID =",
"of a line that has changed''' if ( not self.editCB",
"OpenGL representation of a flow line. Basically a segment with",
"of the segment. @param p2 An instance of Vector2. The",
") self.lines.append( GLFlowSegment( Vector2(0, 0), Vector2(0, 0) ) ) self.activeLine",
"line ): '''Notifies call back of a line that has",
"direction is to the RIGHT of the segment. The forward",
"callback object for when a flow line values are edited.",
"eX, eY ) x, y = view.screenToWorld( ( eX, eY",
"drawn in default (green), the active line is drawn in",
"self.ADD ): self.lines[ self.activeID ].drawGL( ( 1.0, 1.0, 0.1 )",
"creating and editing lines''' MIN_LINE_LENGTH = 2 # the minimum",
"def __repr__( self ): return str( self ) def drawGL(",
"per line. @param lines A list of Segment instaces. One",
"evt, view ): \"\"\"Detects click, drag, release and creates a",
"( (endPos - self.downPos).magnitude() >= self.MIN_LINE_LENGTH ): if ( self.editState",
"= self.NO_EDIT self.canDraw = False self.activeID = -1 else: self.editState",
") def drawGL( self, color=(0.1, 1.0, 0.1) ): '''Draw the",
"the lines''' self.lines = [] self.names = [] self.activeID =",
"the minimum drag required to draw a line # edit",
"self.names = names self.activeID = -1 self.editState = self.NO_EDIT def",
"idx ): '''Flips the direction of the line in the",
"color=(0.1, 1.0, 0.1) ): '''Draw the flow segment into a",
"indicated line''' if ( self.editState == self.ADD): return if (",
"%d' % len( self.names ) ) self.lines.append( GLFlowSegment( Vector2(0, 0),",
") self.lines[ idx ].flip() def setActive( self, idx ): '''Sets",
"idx >= 0 and idx < len( self.lines ) )",
"evt ) except ValueError as e: return result if (",
"''' self.lines = map( lambda x: GLFlowSegment( x.p1, x.p2 ),",
") ) p1 = Vector2( x, y ) self.activeLine =",
"of lines. @return An instance of a FlowLine. ''' return",
"BaseContext.__init__( self ) self.lines = [] self.names = [] self.activeID",
"Vector2( x, y ) self.activeLine = GLFlowSegment( p1, p1 )",
"event.type == MouseEvent.UP ): if ( btn == MouseEvent.LEFT and",
"A list of strings. One name per line. @param lines",
"eX, eY ) if ( (endPos - self.downPos).magnitude() >= self.MIN_LINE_LENGTH",
"self.editState == self.ADD ): self.activeID = len( self.lines ) -",
"= cancelCB self.editCB = editCB self.activeLine = None self.canDraw =",
"event.button eX = event.x eY = event.y if ( event.type",
"== self.ADD ): self.activeID = len( self.lines ) - 1",
"is drawn in cyan.''' if ( self.activeLine ): self.activeLine.drawGL( (",
"self.canDraw = True self.editState = self.ADD self.activeID = -1 self.names.append(",
"idx def stopEdit( self ): '''Stops the ability to edit'''",
"[0, 1], to be interpreted as r, g, b color",
"0 and idx < len( self.lines ) ) self.lines[ idx",
"the ability to edit''' self.editState = self.NO_EDIT self.canDraw = False",
"shows which way flow is expected to cross the line.",
"line index, id. @param id An integer. The index into",
"result if ( not self.canDraw ): return result if (",
"self, line ): '''Notifies call back of a line that",
"= False result.set( canceled, canceled, False ) elif ( event.type",
"in enumerate( self.lines ): if ( i == self.activeID ):",
"def __init__( self, cancelCB=None, editCB=None ): '''Constructor. @param cancelCB A",
"= editCB self.activeLine = None self.canDraw = False self.dragging =",
"canceled = self.activeLine != None self.activeLine = None self.dragging =",
"): self.activeID = len( self.lines ) - 1 self.lines[self.activeID] =",
"self.ADD): return if ( idx < 0 ): self.editState =",
"isinstance( context, FlowLineContext ) ) self.clear() self.names = [ a",
"mode. Returning the new name.''' self.canDraw = True self.editState =",
"context. @param A 3-tuple of floats. The color of the",
"to the RIGHT of the segment. The forward direction is",
"self.normal() * (0.25 * l ) end = mp +",
"self.notifyEdit( self.activeLine ) elif ( self.editState == self.EDIT ): assert(",
"event.type == MouseEvent.MOVE ): if ( self.dragging ): x, y",
"self.activeID > -1 ) self.lines[ self.activeID ] = self.activeLine self.notifyEdit(",
"the flow segment into a GL context. @param A 3-tuple",
"names and lines. It is asserted that len( names )",
"self.activeLine = None self.activeLine = None self.dragging = False result.set(",
"( btn == MouseEvent.LEFT and self.dragging ): endPos = Vector2(",
"self.magnitude() n = self.normal() * (0.25 * l ) end",
"False self.downPost = None def lineCount( self ): return len(",
"into the stored set of lines. @return A string. The",
"'''Sets the active line''' self.activeID = idx def stopEdit( self",
"): return result if ( event.noModifiers() ): btn = event.button",
"for knowing what to do with the active line and",
"None self.canDraw = False self.dragging = False self.downPost = None",
"'''Returns the name associated with the line index, id. @param",
"self ): '''Basic lines are drawn in default (green), the",
"assert( idx >= 0 and idx < len( self.lines )",
"knowing what to do with the active line and cancellation",
"A 3-tuple of floats. The color of the line. All",
"mp.y ) glVertex2f( end.x, end.y ) glEnd() glPopAttrib() class FlowLineContext(",
"= self.NO_EDIT self.activeLine = None self.canDraw = False self.dragging =",
") self.activeLine = self.lines[-1] return self.names[-1] def editLine( self, idx",
"= self.midPoint() l = self.magnitude() n = self.normal() * (0.25",
"self.editState = self.NO_EDIT self.canDraw = False def getLineCount( self ):",
"asserted that len( names ) == len( lines ). @param",
"] def getLine( self, id ): '''Returns the name associated",
"p2 ) def __str__( self ): return \"GLFlowSegment (%s, %s)\"",
"direciton indicator. The direction indicator shows which way flow is",
"and editing lines''' MIN_LINE_LENGTH = 2 # the minimum drag",
"self.canDraw = True self.activeID = idx def setLineName( self, idx,",
"def deleteLine( self, idx ): '''Removes a line from the",
"are drawn in default (green), the active line is drawn",
"= self.magnitude() n = self.normal() * (0.25 * l )",
"= False self.dragging = False self.downPost = None def lineCount(",
"self.p1.x, self.p1.y ) glVertex2f( self.p2.x, self.p2.y ) mp = self.midPoint()",
"len( self.lines ) ) self.lines.pop( idx ) self.names.pop( idx )",
"self.activeID = -1 def flipLine( self, idx ): '''Flips the",
"@param lines A list of Segment instaces. One line per",
"( event.type == MouseEvent.MOVE ): if ( self.dragging ): x,",
"= view.screenToWorld( ( eX, eY ) ) p2 = Vector2(",
"names self.activeID = -1 self.editState = self.NO_EDIT def handleMouse (",
"= True self.activeID = idx def setLineName( self, idx, name",
"(endPos - self.downPos).magnitude() >= self.MIN_LINE_LENGTH ): if ( self.editState ==",
"= len( self.lines ) - 1 self.lines[self.activeID] = self.activeLine self.editState",
"'''Basic lines are drawn in default (green), the active line",
"= map( lambda x: GLFlowSegment( x.p1, x.p2 ), lines )",
"= self.canonicalEvent( evt ) except ValueError as e: return result",
"segment. The forward direction is the direction from p1 to",
"len( self.names ) ) self.lines.append( GLFlowSegment( Vector2(0, 0), Vector2(0, 0)",
"< len( self.lines ) ) self.lines[ idx ].flip() def setActive(",
"l = self.magnitude() n = self.normal() * (0.25 * l",
"lambda x: GLFlowSegment( x.p1, x.p2 ), lines ) self.names =",
"self.downPost = None def lineCount( self ): return len( self.lines",
"): btn = event.button eX = event.x eY = event.y",
"def setMultiLines( self, names, lines ): '''Sets the lines in",
"Vector2( x, y ) self.activeLine.p2 = p2 result.set( True, True,",
"A callable. An optional callback object for when flow line",
"= [] self.names = [] self.activeID = -1 # the",
"names ) == len( lines ). @param names A list",
"and self.editState != self.ADD ): self.lines[ self.activeID ].drawGL( ( 1.0,",
"of the segment. ''' Segment.__init__( self, p1, p2 ) def",
"(0.25 * l ) end = mp + n glVertex2f(",
"set of lines. @return An instance of a FlowLine. '''",
"name.''' self.canDraw = True self.editState = self.ADD self.activeID = -1",
"self, idx ): '''Edits the indicated line''' if ( self.editState",
"@param cancelCB A callable. An optional callback object for when",
"index''' self.names[ idx ] = name def deleteLine( self, idx",
"mp.x, mp.y ) glVertex2f( end.x, end.y ) glEnd() glPopAttrib() class",
"ability to edit''' self.editState = self.NO_EDIT self.canDraw = False def",
"result.set( True, True, False ) self.dragging = True self.notifyEdit( self.activeLine",
") result.set( True, True, False ) self.dragging = True self.notifyEdit(",
"y ) self.activeLine.p2 = p2 result.set( True, True, False )",
"should lie in the range [0, 1], to be interpreted",
"r, g, b color values. ''' glPushAttrib( GL_COLOR_BUFFER_BIT ) glBegin(",
"editCB self.activeLine = None self.canDraw = False self.dragging = False",
"Basically a segment with a direciton indicator. The direction indicator",
"): self.editState = self.NO_EDIT self.canDraw = False self.activeID = -1",
"'''The OpenGL representation of a flow line. Basically a segment",
"= Vector2( eX, eY ) x, y = view.screenToWorld( (",
"OpenGL.GL import * from copy import deepcopy class GLFlowSegment( Segment",
"< 0 ): self.editState = self.NO_EDIT self.canDraw = False self.activeID",
"editing lines''' MIN_LINE_LENGTH = 2 # the minimum drag required",
"self.lines[ idx ].flip() def setActive( self, idx ): '''Sets the",
"direction indicator shows which way flow is expected to cross",
"ContextResult() try: event = self.canonicalEvent( evt ) except ValueError as",
"> -1 ) self.lines[ self.activeID ] = self.activeLine self.notifyEdit( self.activeLine",
"direction of the line in the set''' assert( idx >=",
"the stored set of lines. @return An instance of a",
"idx < len( self.lines ) ) self.lines[ idx ].flip() def",
"p1, p2 ) def __str__( self ): return \"GLFlowSegment (%s,",
">= 0 and idx < len( self.lines ) ) self.lines.pop(",
"2 # the minimum drag required to draw a line",
"line values are edited. ''' BaseContext.__init__( self ) self.lines =",
"clear( self ): '''Clears out all of the lines''' self.lines",
"lines''' self.lines = [] self.names = [] self.activeID = -1",
"self.lines = [] self.names = [] self.activeID = -1 self.editState",
"to do with the active line and cancellation NO_EDIT =",
"self.activeLine = None self.dragging = False result.set( True, True, False",
"set of lines. @return A string. The stored name. '''",
"when it is being edited, the original disappears and the",
"associated with the line index, id. @param id An integer.",
") except ValueError as e: return result if ( not",
"lines\"\"\" return len( self.lines ) def setMultiLines( self, names, lines",
"= event.y if ( event.type == MouseEvent.DOWN ): #QtCore.QEvent.MouseButtonPress ):",
"glVertex2f( mp.x, mp.y ) glVertex2f( end.x, end.y ) glEnd() glPopAttrib()",
"event.type == MouseEvent.DOWN ): #QtCore.QEvent.MouseButtonPress ): if ( btn ==",
"lines from Context import * from primitives import Vector2, Segment",
"of the segment. The forward direction is the direction from",
"= [] self.activeID = -1 # the line currently affected",
"): # cancel the edit if ( self.editState == self.ADD",
"btn == MouseEvent.LEFT and self.dragging ): endPos = Vector2( eX,",
"self.dragging ): x, y = view.screenToWorld( ( eX, eY )",
"self.lines = map( lambda x: GLFlowSegment( x.p1, x.p2 ), lines",
"flow line. Basically a segment with a direciton indicator. The",
"( self, evt, view ): \"\"\"Detects click, drag, release and",
"self.lines[ self.activeID ] = self.activeLine self.notifyEdit( self.activeLine ) self.activeLine =",
"1.0, 1.0 ) ) elif ( self.activeID > -1 and",
"edit''' self.editState = self.NO_EDIT self.canDraw = False def getLineCount( self",
"lines are drawn in default (green), the active line is",
"the RIGHT of the segment. The forward direction is the",
"), lines ) self.names = names self.activeID = -1 self.editState",
"is to the RIGHT of the segment. The forward direction",
"None ): self.cancelCB() self.notifyEdit( None ) canceled = self.activeLine !=",
"in cyan.''' if ( self.activeLine ): self.activeLine.drawGL( ( 0.1, 1.0,",
"callable. An optional callback object for when flow line drawing",
"for drawing, creating and editing lines''' MIN_LINE_LENGTH = 2 #",
"required to draw a line # edit state - used",
"line. All values should lie in the range [0, 1],",
"MouseEvent.LEFT ): self.downPos = Vector2( eX, eY ) x, y",
"== MouseEvent.UP ): if ( btn == MouseEvent.LEFT and self.dragging",
"the line currently affected by modifications self.editState = self.NO_EDIT self.cancelCB",
"name ): '''Sets the name for the line with the",
") self.activeID = -1 def flipLine( self, idx ): '''Flips",
"cancellation NO_EDIT = 0 EDIT = 1 ADD = 2",
"result.set( canceled, canceled, False ) elif ( event.type == MouseEvent.UP",
"p1, p2 ): '''Constructor. @param p1 An instance of Vector2.",
"self.dragging = False self.downPost = None def lineCount( self ):",
"self.cancelCB() self.notifyEdit( None ) canceled = self.activeLine != None self.activeLine",
"'''Constructor. @param p1 An instance of Vector2. The start point",
"def handleMouse ( self, evt, view ): \"\"\"Detects click, drag,",
"for when flow line drawing is canceled. @param editCB A",
"GLFlowSegment( Segment ): '''The OpenGL representation of a flow line.",
"): self.editState = self.NO_EDIT self.lines.pop(-1) self.names.pop(-1) if ( not self.cancelCB",
"( not self.cancelCB is None ): self.cancelCB() self.notifyEdit( None )",
"self.dragging = False result.set( canceled, canceled, False ) elif (",
"the given FlowLineContext into this''' assert( isinstance( context, FlowLineContext )",
"* from primitives import Vector2, Segment from OpenGL.GL import *",
"The start point of the segment. @param p2 An instance",
"3-tuple of floats. The color of the line. All values",
"self.activeID = -1 else: self.editState = self.EDIT self.canDraw = True",
"the line with the given index''' self.names[ idx ] =",
"MouseEvent.RIGHT and self.dragging ): # cancel the edit if (",
"call back of a line that has changed''' if (",
"'''Sets the name for the line with the given index'''",
") p2 = Vector2( x, y ) self.activeLine.p2 = p2",
"n = self.normal() * (0.25 * l ) end =",
") end = mp + n glVertex2f( mp.x, mp.y )",
"mp = self.midPoint() l = self.magnitude() n = self.normal() *",
"glEnd() glPopAttrib() class FlowLineContext( BaseContext ): '''Context for drawing, creating",
"self.names = [] self.activeID = -1 self.editState = self.NO_EDIT self.activeLine",
"self.activeLine ) self.activeLine = None self.activeLine = None self.dragging =",
"the range [0, 1], to be interpreted as r, g,",
"changed''' if ( not self.editCB is None ): self.editCB( line",
"default (green), the active line is drawn in yellow, and",
"( self.editState == self.ADD ): self.editState = self.NO_EDIT self.lines.pop(-1) self.names.pop(-1)",
"'''Notifies call back of a line that has changed''' if",
"p2 An instance of Vector2. The end point of the",
"glColor3fv( color ) glVertex2f( self.p1.x, self.p1.y ) glVertex2f( self.p2.x, self.p2.y",
"self.p1.y ) glVertex2f( self.p2.x, self.p2.y ) mp = self.midPoint() l",
"view.screenToWorld( ( eX, eY ) ) p2 = Vector2( x,",
"== MouseEvent.DOWN ): #QtCore.QEvent.MouseButtonPress ): if ( btn == MouseEvent.LEFT",
"elif ( self.activeID > -1 and self.editState != self.ADD ):",
"def setActive( self, idx ): '''Sets the active line''' self.activeID",
"self.MIN_LINE_LENGTH ): if ( self.editState == self.ADD ): self.activeID =",
"def editLine( self, idx ): '''Edits the indicated line''' if",
"== MouseEvent.LEFT and self.dragging ): endPos = Vector2( eX, eY",
"!= self.ADD ): self.lines[ self.activeID ].drawGL( ( 1.0, 1.0, 0.1",
"RIGHT of the segment. The forward direction is the direction",
"a GL context. @param A 3-tuple of floats. The color",
"= Vector2( x, y ) self.activeLine = GLFlowSegment( p1, p1",
"of Vector2. The start point of the segment. @param p2",
"self.editState = self.NO_EDIT self.lines.pop(-1) self.names.pop(-1) if ( not self.cancelCB is",
"False ) self.dragging = True self.notifyEdit( self.activeLine ) elif (",
"): '''Clears out all of the lines''' self.lines = []",
"it is being edited, the original disappears and the new",
") for i, line in enumerate( self.lines ): if (",
"( 0.1, 1.0, 1.0 ) ) elif ( self.activeID >",
"% len( self.names ) ) self.lines.append( GLFlowSegment( Vector2(0, 0), Vector2(0,",
"if ( self.editState == self.ADD ): self.editState = self.NO_EDIT self.lines.pop(-1)",
"self.NO_EDIT self.activeLine = None self.canDraw = False self.dragging = False",
"btn == MouseEvent.RIGHT and self.dragging ): # cancel the edit",
"with the line index, id. @param id An integer. The",
") elif ( event.type == MouseEvent.UP ): if ( btn",
"drawing, creating and editing lines''' MIN_LINE_LENGTH = 2 # the",
"the lines in the context with the given names and",
"self.lines.pop(-1) self.names.pop(-1) if ( not self.cancelCB is None ): self.cancelCB()",
"a line from the set''' assert( idx >= 0 and",
"All values should lie in the range [0, 1], to",
"is the direction from p1 to p2.''' def __init__( self,",
"index into the stored set of lines. @return A string.",
"= name def deleteLine( self, idx ): '''Removes a line",
"= event.x eY = event.y if ( event.type == MouseEvent.DOWN",
"1.0, 1.0, 0.1 ) ) for i, line in enumerate(",
"0.1 ) ) for i, line in enumerate( self.lines ):",
"True, False ) self.notifyEdit( self.activeLine ) return result def notifyEdit(",
"self ) def drawGL( self, color=(0.1, 1.0, 0.1) ): '''Draw",
"stored set of lines. @return An instance of a FlowLine.",
"in the context with the given names and lines. It",
"1 self.lines[self.activeID] = self.activeLine self.editState = self.EDIT self.notifyEdit( self.activeLine )",
"to go into new line mode. Returning the new name.'''",
"1.0 ) ) elif ( self.activeID > -1 and self.editState",
"> -1 and self.editState != self.ADD ): self.lines[ self.activeID ].drawGL(",
"self.notifyEdit( None ) canceled = self.activeLine != None self.activeLine =",
"return if ( idx < 0 ): self.editState = self.NO_EDIT",
"set''' assert( idx >= 0 and idx < len( self.lines",
"given names and lines. It is asserted that len( names",
"to draw a line # edit state - used for",
"idx < 0 ): self.editState = self.NO_EDIT self.canDraw = False",
"for i, line in enumerate( self.lines ): if ( i",
"setActive( self, idx ): '''Sets the active line''' self.activeID =",
">= self.MIN_LINE_LENGTH ): if ( self.editState == self.ADD ): self.activeID",
"edit state - used for knowing what to do with",
"= self.NO_EDIT self.cancelCB = cancelCB self.editCB = editCB self.activeLine =",
"= None def copy( self, context ): '''Copy the state",
"return self.names[-1] def editLine( self, idx ): '''Edits the indicated",
"canceled, canceled, False ) elif ( event.type == MouseEvent.UP ):",
"do with the active line and cancellation NO_EDIT = 0",
"== self.ADD): return if ( idx < 0 ): self.editState",
") ) elif ( self.activeID > -1 and self.editState !=",
"state - used for knowing what to do with the",
"if ( btn == MouseEvent.LEFT ): self.downPos = Vector2( eX,",
"if ( self.dragging ): x, y = view.screenToWorld( ( eX,",
"= mp + n glVertex2f( mp.x, mp.y ) glVertex2f( end.x,",
"floats. The color of the line. All values should lie",
"__init__( self, p1, p2 ): '''Constructor. @param p1 An instance",
") x, y = view.screenToWorld( ( eX, eY ) )",
"False def getLineCount( self ): \"\"\"Returns the number of defined",
"self.editState = self.NO_EDIT def handleMouse ( self, evt, view ):",
"= self.EDIT self.notifyEdit( self.activeLine ) elif ( self.editState == self.EDIT",
"p1 = Vector2( x, y ) self.activeLine = GLFlowSegment( p1,",
"self.ADD ): self.activeID = len( self.lines ) - 1 self.lines[self.activeID]",
"x, y ) self.activeLine = GLFlowSegment( p1, p1 ) result.set(",
"with the given index''' self.names[ idx ] = name def",
"and idx < len( self.lines ) ) self.lines[ idx ].flip()",
"Segment ): '''The OpenGL representation of a flow line. Basically",
"end point of the segment. ''' Segment.__init__( self, p1, p2",
"color ) glVertex2f( self.p1.x, self.p1.y ) glVertex2f( self.p2.x, self.p2.y )",
"Vector2(0, 0), Vector2(0, 0) ) ) self.activeLine = self.lines[-1] return",
"lines''' MIN_LINE_LENGTH = 2 # the minimum drag required to",
"self.lines = deepcopy( context.lines ) def clear( self ): '''Clears",
"self.lines.pop( idx ) self.names.pop( idx ) self.activeID = -1 def",
") ) self.lines[ idx ].flip() def setActive( self, idx ):",
"( self.activeLine ): self.activeLine.drawGL( ( 0.1, 1.0, 1.0 ) )",
"forward direction is the direction from p1 to p2.''' def",
"True, False ) self.dragging = True self.notifyEdit( self.activeLine ) elif",
"return result if ( event.noModifiers() ): btn = event.button eX",
"line''' if ( self.editState == self.ADD): return if ( idx",
"the name for the line with the given index''' self.names[",
"Segment.__init__( self, p1, p2 ) def __str__( self ): return",
"if ( btn == MouseEvent.LEFT and self.dragging ): endPos =",
"self.lines ) def setMultiLines( self, names, lines ): '''Sets the",
"self, context ): '''Copy the state of the given FlowLineContext",
") def __repr__( self ): return str( self ) def",
"- 1 self.lines[self.activeID] = self.activeLine self.editState = self.EDIT self.notifyEdit( self.activeLine",
"'''Sets the lines in the context with the given names",
"0.1, 1.0, 1.0 ) ) elif ( self.activeID > -1",
"instance of a FlowLine. ''' return self.lines[ id ] def",
"(green), the active line is drawn in yellow, and when",
"= False self.downPost = None def lineCount( self ): return",
"event.y if ( event.type == MouseEvent.DOWN ): #QtCore.QEvent.MouseButtonPress ): if",
"if ( (endPos - self.downPos).magnitude() >= self.MIN_LINE_LENGTH ): if (",
"self ): '''Stops the ability to edit''' self.editState = self.NO_EDIT",
"self.p2.y ) mp = self.midPoint() l = self.magnitude() n =",
"line # edit state - used for knowing what to",
"self ): '''Causes the context to go into new line",
"return self.lines[ id ] def addLine( self ): '''Causes the",
"from the set''' assert( idx >= 0 and idx <",
") return result def notifyEdit( self, line ): '''Notifies call",
"flow line drawing is canceled. @param editCB A callable. An",
"the context with the given names and lines. It is",
"currently affected by modifications self.editState = self.NO_EDIT self.cancelCB = cancelCB",
"): self.activeLine.drawGL( ( 0.1, 1.0, 1.0 ) ) elif (",
"the state of the given FlowLineContext into this''' assert( isinstance(",
"minimum drag required to draw a line # edit state",
"all of the lines''' self.lines = [] self.names = []",
"self.lines.append( GLFlowSegment( Vector2(0, 0), Vector2(0, 0) ) ) self.activeLine =",
"( btn == MouseEvent.LEFT ): self.downPos = Vector2( eX, eY",
"with the active line and cancellation NO_EDIT = 0 EDIT",
"self.activeLine = None self.dragging = False result.set( canceled, canceled, False",
"return result if ( not self.canDraw ): return result if",
"modifications self.editState = self.NO_EDIT self.cancelCB = cancelCB self.editCB = editCB",
"self.names[-1] def editLine( self, idx ): '''Edits the indicated line'''",
"assert( self.activeID > -1 ) self.lines[ self.activeID ] = self.activeLine",
"elif ( event.type == MouseEvent.MOVE ): if ( self.dragging ):",
"click, drag, release and creates a line\"\"\" result = ContextResult()",
"self.activeID = idx def stopEdit( self ): '''Stops the ability",
"self.activeLine.p2 = p2 result.set( True, True, False ) self.notifyEdit( self.activeLine",
"The stored name. ''' return self.names[ id ] def getLine(",
"result.set( True, True, False ) self.notifyEdit( self.activeLine ) return result",
"lines. @return A string. The stored name. ''' return self.names[",
") ) for i, line in enumerate( self.lines ): if",
"the segment. ''' Segment.__init__( self, p1, p2 ) def __str__(",
"import * from copy import deepcopy class GLFlowSegment( Segment ):",
"cross the line. The flow direction is to the RIGHT",
"% ( self.p1, self.p2 ) def __repr__( self ): return",
"line and cancellation NO_EDIT = 0 EDIT = 1 ADD",
"indicator. The direction indicator shows which way flow is expected",
"idx ): '''Edits the indicated line''' if ( self.editState ==",
"eY = event.y if ( event.type == MouseEvent.DOWN ): #QtCore.QEvent.MouseButtonPress",
"= view.screenToWorld( ( eX, eY ) ) p1 = Vector2(",
") p1 = Vector2( x, y ) self.activeLine = GLFlowSegment(",
"GLFlowSegment( p1, p1 ) result.set( True, True, False ) self.dragging",
"= self.NO_EDIT self.lines.pop(-1) self.names.pop(-1) if ( not self.cancelCB is None",
"names A list of strings. One name per line. @param",
"representation of a flow line. Basically a segment with a",
"self.lines ) def getName( self, id ): '''Returns the name",
"( self.p1, self.p2 ) def __repr__( self ): return str(",
"-1 else: self.editState = self.EDIT self.canDraw = True self.activeID =",
"self, idx ): '''Sets the active line''' self.activeID = idx",
"): '''Basic lines are drawn in default (green), the active",
"] self.lines = deepcopy( context.lines ) def clear( self ):",
"# cancel the edit if ( self.editState == self.ADD ):",
"end.y ) glEnd() glPopAttrib() class FlowLineContext( BaseContext ): '''Context for",
"self.notifyEdit( self.activeLine ) self.activeLine = None self.activeLine = None self.dragging",
"idx < len( self.lines ) ) self.lines.pop( idx ) self.names.pop(",
"self.NO_EDIT self.lines.pop(-1) self.names.pop(-1) if ( not self.cancelCB is None ):",
") ) p2 = Vector2( x, y ) self.activeLine.p2 =",
"p1 to p2.''' def __init__( self, p1, p2 ): '''Constructor.",
"def clear( self ): '''Clears out all of the lines'''",
"= self.ADD self.activeID = -1 self.names.append( 'Line %d' % len(",
") self.lines.pop( idx ) self.names.pop( idx ) self.activeID = -1",
"self.activeLine = self.lines[-1] return self.names[-1] def editLine( self, idx ):",
"event.noModifiers() ): btn = event.button eX = event.x eY =",
"in the set''' assert( idx >= 0 and idx <",
"color values. ''' glPushAttrib( GL_COLOR_BUFFER_BIT ) glBegin( GL_LINES ) glColor3fv(",
"drawing flow calculation lines from Context import * from primitives",
"index, id. @param id An integer. The index into the",
"state of the given FlowLineContext into this''' assert( isinstance( context,",
"self.dragging = True self.notifyEdit( self.activeLine ) elif ( btn ==",
"\"GLFlowSegment (%s, %s)\" % ( self.p1, self.p2 ) def __repr__(",
"Vector2, Segment from OpenGL.GL import * from copy import deepcopy",
"if ( self.editState == self.ADD): return if ( idx <",
"the new line is drawn in cyan.''' if ( self.activeLine",
"end.x, end.y ) glEnd() glPopAttrib() class FlowLineContext( BaseContext ): '''Context",
"id ] def addLine( self ): '''Causes the context to",
"segment with a direciton indicator. The direction indicator shows which",
"Vector2. The start point of the segment. @param p2 An",
"used for knowing what to do with the active line",
"[] self.activeID = -1 # the line currently affected by",
"the active line is drawn in yellow, and when it",
"self.activeLine ): self.activeLine.drawGL( ( 0.1, 1.0, 1.0 ) ) elif",
"color of the line. All values should lie in the",
"assert( isinstance( context, FlowLineContext ) ) self.clear() self.names = [",
"self.activeLine = GLFlowSegment( p1, p1 ) result.set( True, True, False",
"2 def __init__( self, cancelCB=None, editCB=None ): '''Constructor. @param cancelCB",
"def lineCount( self ): return len( self.lines ) def getName(",
"0 and idx < len( self.lines ) ) self.lines.pop( idx",
"what to do with the active line and cancellation NO_EDIT",
"True, False ) elif ( event.type == MouseEvent.MOVE ): if",
"eX, eY ) ) p1 = Vector2( x, y )",
"( self.editState == self.ADD ): self.activeID = len( self.lines )",
"else: self.editState = self.EDIT self.canDraw = True self.activeID = idx",
"import * from primitives import Vector2, Segment from OpenGL.GL import",
"with the given names and lines. It is asserted that",
"are edited. ''' BaseContext.__init__( self ) self.lines = [] self.names",
"self.canonicalEvent( evt ) except ValueError as e: return result if",
"This is the OpenGL context for drawing flow calculation lines",
"): return str( self ) def drawGL( self, color=(0.1, 1.0,",
"= True self.editState = self.ADD self.activeID = -1 self.names.append( 'Line",
"It is asserted that len( names ) == len( lines",
"def drawGL( self ): '''Basic lines are drawn in default",
"and idx < len( self.lines ) ) self.lines.pop( idx )",
"self.NO_EDIT self.canDraw = False def getLineCount( self ): \"\"\"Returns the",
"): if ( btn == MouseEvent.LEFT and self.dragging ): endPos",
"self.NO_EDIT def handleMouse ( self, evt, view ): \"\"\"Detects click,",
"): '''The OpenGL representation of a flow line. Basically a",
"a line # edit state - used for knowing what",
"cancelCB self.editCB = editCB self.activeLine = None self.canDraw = False",
"1.0, 0.1 ) ) for i, line in enumerate( self.lines",
"of the given FlowLineContext into this''' assert( isinstance( context, FlowLineContext",
"drawGL( self ): '''Basic lines are drawn in default (green),",
"p1 An instance of Vector2. The start point of the",
"to p2.''' def __init__( self, p1, p2 ): '''Constructor. @param",
"b color values. ''' glPushAttrib( GL_COLOR_BUFFER_BIT ) glBegin( GL_LINES )",
"@param p1 An instance of Vector2. The start point of",
"elif ( event.type == MouseEvent.UP ): if ( btn ==",
"the line index, id. @param id An integer. The index",
"creates a line\"\"\" result = ContextResult() try: event = self.canonicalEvent(",
"= ContextResult() try: event = self.canonicalEvent( evt ) except ValueError",
") ) self.activeLine = self.lines[-1] return self.names[-1] def editLine( self,",
"Vector2( eX, eY ) x, y = view.screenToWorld( ( eX,",
"that has changed''' if ( not self.editCB is None ):",
"== MouseEvent.MOVE ): if ( self.dragging ): x, y =",
"'''Context for drawing, creating and editing lines''' MIN_LINE_LENGTH = 2",
"stored set of lines. @return A string. The stored name.",
"FlowLineContext ) ) self.clear() self.names = [ a for a",
"= None self.dragging = False result.set( True, True, False )",
"flow calculation lines from Context import * from primitives import",
") elif ( self.activeID > -1 and self.editState != self.ADD",
"the direction of the line in the set''' assert( idx",
"indicator shows which way flow is expected to cross the",
"self.activeID = idx def setLineName( self, idx, name ): '''Sets",
"event = self.canonicalEvent( evt ) except ValueError as e: return",
"None ): self.editCB( line ) def drawGL( self ): '''Basic",
"name for the line with the given index''' self.names[ idx",
"False result.set( canceled, canceled, False ) elif ( event.type ==",
"] = self.activeLine self.notifyEdit( self.activeLine ) self.activeLine = None self.activeLine",
"self.p1, self.p2 ) def __repr__( self ): return str( self",
"self.lines[ id ] def addLine( self ): '''Causes the context",
"None self.activeLine = None self.dragging = False result.set( True, True,",
"self.names[ idx ] = name def deleteLine( self, idx ):",
"= Vector2( x, y ) self.activeLine.p2 = p2 result.set( True,",
"is asserted that len( names ) == len( lines ).",
"from primitives import Vector2, Segment from OpenGL.GL import * from",
"of Vector2. The end point of the segment. ''' Segment.__init__(",
"The direction indicator shows which way flow is expected to",
"for when a flow line values are edited. ''' BaseContext.__init__(",
"< len( self.lines ) ) self.lines.pop( idx ) self.names.pop( idx",
"cancelCB A callable. An optional callback object for when flow",
"): '''Removes a line from the set''' assert( idx >=",
"0) ) ) self.activeLine = self.lines[-1] return self.names[-1] def editLine(",
"): '''Edits the indicated line''' if ( self.editState == self.ADD):",
"elif ( btn == MouseEvent.RIGHT and self.dragging ): # cancel",
"= [] self.activeID = -1 self.editState = self.NO_EDIT self.activeLine =",
"lines. @return An instance of a FlowLine. ''' return self.lines[",
"1.0, 0.1) ): '''Draw the flow segment into a GL",
"= False self.downPost = None def copy( self, context ):",
"self.canDraw = False def getLineCount( self ): \"\"\"Returns the number",
"copy import deepcopy class GLFlowSegment( Segment ): '''The OpenGL representation",
"result def notifyEdit( self, line ): '''Notifies call back of",
"flow direction is to the RIGHT of the segment. The",
"is being edited, the original disappears and the new line",
"-1 self.names.append( 'Line %d' % len( self.names ) ) self.lines.append(",
"self.EDIT self.canDraw = True self.activeID = idx def setLineName( self,",
"callback object for when flow line drawing is canceled. @param",
"the given names and lines. It is asserted that len(",
"= None self.activeLine = None self.dragging = False result.set( True,",
"self.downPos).magnitude() >= self.MIN_LINE_LENGTH ): if ( self.editState == self.ADD ):",
"def __init__( self, p1, p2 ): '''Constructor. @param p1 An",
"self.activeID = -1 self.editState = self.NO_EDIT def handleMouse ( self,",
"= -1 # the line currently affected by modifications self.editState",
"from Context import * from primitives import Vector2, Segment from",
"def stopEdit( self ): '''Stops the ability to edit''' self.editState",
"self.cancelCB is None ): self.cancelCB() self.notifyEdit( None ) canceled =",
"self.activeLine self.notifyEdit( self.activeLine ) self.activeLine = None self.activeLine = None",
"False ) self.notifyEdit( self.activeLine ) return result def notifyEdit( self,",
"( not self.canDraw ): return result if ( event.noModifiers() ):",
"p2 ): '''Constructor. @param p1 An instance of Vector2. The",
"self.dragging ): # cancel the edit if ( self.editState ==",
") ) self.lines.pop( idx ) self.names.pop( idx ) self.activeID =",
"deepcopy( context.lines ) def clear( self ): '''Clears out all",
"values are edited. ''' BaseContext.__init__( self ) self.lines = []",
"expected to cross the line. The flow direction is to",
") ) self.clear() self.names = [ a for a in",
"# edit state - used for knowing what to do",
"instaces. One line per name. ''' self.lines = map( lambda",
"self.editState = self.EDIT self.canDraw = True self.activeID = idx def",
"draw a line # edit state - used for knowing",
"a flow line values are edited. ''' BaseContext.__init__( self )",
"'''Draw the flow segment into a GL context. @param A",
") self.names.pop( idx ) self.activeID = -1 def flipLine( self,",
"of Segment instaces. One line per name. ''' self.lines =",
"self, evt, view ): \"\"\"Detects click, drag, release and creates",
"-1 self.editState = self.NO_EDIT self.activeLine = None self.canDraw = False",
"to cross the line. The flow direction is to the",
"the line. The flow direction is to the RIGHT of",
"0.1) ): '''Draw the flow segment into a GL context.",
"None ) canceled = self.activeLine != None self.activeLine = None",
"): if ( self.editState == self.ADD ): self.activeID = len(",
") self.notifyEdit( self.activeLine ) return result def notifyEdit( self, line",
"which way flow is expected to cross the line. The",
"notifyEdit( self, line ): '''Notifies call back of a line",
"MouseEvent.UP ): if ( btn == MouseEvent.LEFT and self.dragging ):",
"instance of Vector2. The end point of the segment. '''",
"): self.editCB( line ) def drawGL( self ): '''Basic lines",
"self, p1, p2 ) def __str__( self ): return \"GLFlowSegment",
"of the line in the set''' assert( idx >= 0",
"drawing is canceled. @param editCB A callable. An optional callback",
"of the line. All values should lie in the range",
"self ) self.lines = [] self.names = [] self.activeID =",
"== len( lines ). @param names A list of strings.",
"result if ( event.noModifiers() ): btn = event.button eX =",
"defined lines\"\"\" return len( self.lines ) def setMultiLines( self, names,",
"False self.dragging = False self.downPost = None def lineCount( self",
"self.dragging ): endPos = Vector2( eX, eY ) if (",
"self.downPos = Vector2( eX, eY ) x, y = view.screenToWorld(",
"drawGL( self, color=(0.1, 1.0, 0.1) ): '''Draw the flow segment",
"[] self.names = [] self.activeID = -1 # the line",
"self.p2.x, self.p2.y ) mp = self.midPoint() l = self.magnitude() n",
"p1, p1 ) result.set( True, True, False ) self.dragging =",
"p2 = Vector2( x, y ) self.activeLine.p2 = p2 result.set(",
"the context to go into new line mode. Returning the",
"): '''Context for drawing, creating and editing lines''' MIN_LINE_LENGTH =",
"deepcopy class GLFlowSegment( Segment ): '''The OpenGL representation of a",
"editCB A callable. An optional callback object for when a",
"A callable. An optional callback object for when a flow",
"y = view.screenToWorld( ( eX, eY ) ) p1 =",
"self.clear() self.names = [ a for a in context.names ]",
"the line. All values should lie in the range [0,",
"= self.normal() * (0.25 * l ) end = mp",
"] = name def deleteLine( self, idx ): '''Removes a",
"eX, eY ) ) p2 = Vector2( x, y )",
"= p2 result.set( True, True, False ) self.notifyEdit( self.activeLine )",
"line mode. Returning the new name.''' self.canDraw = True self.editState",
"line with the given index''' self.names[ idx ] = name",
"the given index''' self.names[ idx ] = name def deleteLine(",
"def flipLine( self, idx ): '''Flips the direction of the",
"== self.ADD ): self.editState = self.NO_EDIT self.lines.pop(-1) self.names.pop(-1) if (",
"self.activeID ] = self.activeLine self.notifyEdit( self.activeLine ) self.activeLine = None",
"disappears and the new line is drawn in cyan.''' if",
"stored name. ''' return self.names[ id ] def getLine( self,",
"eY ) if ( (endPos - self.downPos).magnitude() >= self.MIN_LINE_LENGTH ):",
"self.EDIT self.notifyEdit( self.activeLine ) elif ( self.editState == self.EDIT ):",
"setMultiLines( self, names, lines ): '''Sets the lines in the",
"'Line %d' % len( self.names ) ) self.lines.append( GLFlowSegment( Vector2(0,",
"of defined lines\"\"\" return len( self.lines ) def setMultiLines( self,",
"self, names, lines ): '''Sets the lines in the context",
"An instance of Vector2. The end point of the segment.",
"''' glPushAttrib( GL_COLOR_BUFFER_BIT ) glBegin( GL_LINES ) glColor3fv( color )",
"context ): '''Copy the state of the given FlowLineContext into",
"[] self.names = [] self.activeID = -1 self.editState = self.NO_EDIT",
"None self.dragging = False result.set( True, True, False ) elif",
"optional callback object for when a flow line values are",
"False ) elif ( event.type == MouseEvent.MOVE ): if (",
"handleMouse ( self, evt, view ): \"\"\"Detects click, drag, release",
"the name associated with the line index, id. @param id",
"): '''Notifies call back of a line that has changed'''",
"the stored set of lines. @return A string. The stored",
"Segment instaces. One line per name. ''' self.lines = map(",
") self.activeLine = GLFlowSegment( p1, p1 ) result.set( True, True,",
"# the line currently affected by modifications self.editState = self.NO_EDIT",
"def getName( self, id ): '''Returns the name associated with",
"= idx def setLineName( self, idx, name ): '''Sets the",
"if ( not self.canDraw ): return result if ( event.noModifiers()",
"a flow line. Basically a segment with a direciton indicator.",
"= -1 self.editState = self.NO_EDIT self.activeLine = None self.canDraw =",
"__repr__( self ): return str( self ) def drawGL( self,",
"line in enumerate( self.lines ): if ( i == self.activeID",
"self.activeLine self.editState = self.EDIT self.notifyEdit( self.activeLine ) elif ( self.editState",
"the direction from p1 to p2.''' def __init__( self, p1,",
"): '''Copy the state of the given FlowLineContext into this'''",
"setLineName( self, idx, name ): '''Sets the name for the",
"A list of Segment instaces. One line per name. '''",
"( btn == MouseEvent.RIGHT and self.dragging ): # cancel the",
"= -1 else: self.editState = self.EDIT self.canDraw = True self.activeID",
"active line is drawn in yellow, and when it is",
") ) self.lines.append( GLFlowSegment( Vector2(0, 0), Vector2(0, 0) ) )",
"self.editState != self.ADD ): self.lines[ self.activeID ].drawGL( ( 1.0, 1.0,",
"( eX, eY ) ) p1 = Vector2( x, y",
"self.editState == self.EDIT ): assert( self.activeID > -1 ) self.lines[",
"getLineCount( self ): \"\"\"Returns the number of defined lines\"\"\" return",
"is the OpenGL context for drawing flow calculation lines from",
"-1 def flipLine( self, idx ): '''Flips the direction of",
"== MouseEvent.LEFT ): self.downPos = Vector2( eX, eY ) x,",
"self, idx, name ): '''Sets the name for the line",
") glVertex2f( end.x, end.y ) glEnd() glPopAttrib() class FlowLineContext( BaseContext",
"). @param names A list of strings. One name per",
"MouseEvent.LEFT and self.dragging ): endPos = Vector2( eX, eY )",
"def getLine( self, id ): '''Returns the name associated with",
"a for a in context.names ] self.lines = deepcopy( context.lines",
"import Vector2, Segment from OpenGL.GL import * from copy import",
"False self.activeID = -1 else: self.editState = self.EDIT self.canDraw =",
"self ): \"\"\"Returns the number of defined lines\"\"\" return len(",
"MouseEvent.DOWN ): #QtCore.QEvent.MouseButtonPress ): if ( btn == MouseEvent.LEFT ):",
"self.lines ): if ( i == self.activeID ): continue line.drawGL()",
"''' BaseContext.__init__( self ) self.lines = [] self.names = []",
"deleteLine( self, idx ): '''Removes a line from the set'''",
"y ) self.activeLine = GLFlowSegment( p1, p1 ) result.set( True,",
"direction from p1 to p2.''' def __init__( self, p1, p2",
"def getLineCount( self ): \"\"\"Returns the number of defined lines\"\"\"",
"self.lines ) ) self.lines.pop( idx ) self.names.pop( idx ) self.activeID",
"= Vector2( eX, eY ) if ( (endPos - self.downPos).magnitude()",
"go into new line mode. Returning the new name.''' self.canDraw",
"None self.dragging = False result.set( canceled, canceled, False ) elif",
"self.activeLine ) elif ( btn == MouseEvent.RIGHT and self.dragging ):",
"self.activeID ].drawGL( ( 1.0, 1.0, 0.1 ) ) for i,",
"self, idx ): '''Removes a line from the set''' assert(",
"lines A list of Segment instaces. One line per name.",
"l ) end = mp + n glVertex2f( mp.x, mp.y",
"str( self ) def drawGL( self, color=(0.1, 1.0, 0.1) ):",
"id An integer. The index into the stored set of",
"The index into the stored set of lines. @return An",
"): \"\"\"Returns the number of defined lines\"\"\" return len( self.lines",
"The end point of the segment. ''' Segment.__init__( self, p1,",
"flow is expected to cross the line. The flow direction",
"): endPos = Vector2( eX, eY ) if ( (endPos",
"self.lines ) - 1 self.lines[self.activeID] = self.activeLine self.editState = self.EDIT",
") glBegin( GL_LINES ) glColor3fv( color ) glVertex2f( self.p1.x, self.p1.y",
") glVertex2f( self.p2.x, self.p2.y ) mp = self.midPoint() l =",
"name. ''' self.lines = map( lambda x: GLFlowSegment( x.p1, x.p2",
"line is drawn in yellow, and when it is being",
"glVertex2f( self.p1.x, self.p1.y ) glVertex2f( self.p2.x, self.p2.y ) mp =",
"canceled, False ) elif ( event.type == MouseEvent.UP ): if",
") self.lines[ self.activeID ] = self.activeLine self.notifyEdit( self.activeLine ) self.activeLine",
"y = view.screenToWorld( ( eX, eY ) ) p2 =",
") self.activeLine.p2 = p2 result.set( True, True, False ) self.notifyEdit(",
"segment. ''' Segment.__init__( self, p1, p2 ) def __str__( self",
"(%s, %s)\" % ( self.p1, self.p2 ) def __repr__( self",
"idx, name ): '''Sets the name for the line with",
"self.editState = self.NO_EDIT self.canDraw = False self.activeID = -1 else:",
"context for drawing flow calculation lines from Context import *",
"given FlowLineContext into this''' assert( isinstance( context, FlowLineContext ) )",
"def setLineName( self, idx, name ): '''Sets the name for",
"): self.downPos = Vector2( eX, eY ) x, y =",
") self.clear() self.names = [ a for a in context.names",
"the line in the set''' assert( idx >= 0 and",
"if ( event.noModifiers() ): btn = event.button eX = event.x",
"integer. The index into the stored set of lines. @return",
"canceled. @param editCB A callable. An optional callback object for",
"self.activeID = -1 self.editState = self.NO_EDIT self.activeLine = None self.canDraw",
"range [0, 1], to be interpreted as r, g, b",
"and lines. It is asserted that len( names ) ==",
"-1 self.editState = self.NO_EDIT def handleMouse ( self, evt, view",
"1 ADD = 2 def __init__( self, cancelCB=None, editCB=None ):",
"ValueError as e: return result if ( not self.canDraw ):",
"into new line mode. Returning the new name.''' self.canDraw =",
"= False result.set( True, True, False ) elif ( event.type",
"%s)\" % ( self.p1, self.p2 ) def __repr__( self ):",
"<filename>out/flowContext.py # This is the OpenGL context for drawing flow",
") def __str__( self ): return \"GLFlowSegment (%s, %s)\" %",
"line''' self.activeID = idx def stopEdit( self ): '''Stops the",
"self.activeLine = None self.canDraw = False self.dragging = False self.downPost",
"'''Constructor. @param cancelCB A callable. An optional callback object for",
"name. ''' return self.names[ id ] def getLine( self, id",
"getLine( self, id ): '''Returns the name associated with the",
"== MouseEvent.RIGHT and self.dragging ): # cancel the edit if",
"and the new line is drawn in cyan.''' if (",
"in the range [0, 1], to be interpreted as r,",
"= -1 def flipLine( self, idx ): '''Flips the direction",
"return self.names[ id ] def getLine( self, id ): '''Returns",
"the segment. The forward direction is the direction from p1",
"a FlowLine. ''' return self.lines[ id ] def addLine( self",
"lines. It is asserted that len( names ) == len(",
"cancelCB=None, editCB=None ): '''Constructor. @param cancelCB A callable. An optional",
"when flow line drawing is canceled. @param editCB A callable.",
"= [ a for a in context.names ] self.lines =",
"self.editState = self.NO_EDIT self.activeLine = None self.canDraw = False self.dragging",
"): self.cancelCB() self.notifyEdit( None ) canceled = self.activeLine != None",
"by modifications self.editState = self.NO_EDIT self.cancelCB = cancelCB self.editCB =",
"i, line in enumerate( self.lines ): if ( i ==",
"self.activeID = -1 self.names.append( 'Line %d' % len( self.names )",
"\"\"\"Returns the number of defined lines\"\"\" return len( self.lines )",
"new line is drawn in cyan.''' if ( self.activeLine ):",
"): if ( btn == MouseEvent.LEFT ): self.downPos = Vector2(",
"= self.activeLine != None self.activeLine = None self.dragging = False",
"flow segment into a GL context. @param A 3-tuple of",
"not self.canDraw ): return result if ( event.noModifiers() ): btn",
"if ( event.type == MouseEvent.DOWN ): #QtCore.QEvent.MouseButtonPress ): if (",
"'''Edits the indicated line''' if ( self.editState == self.ADD): return",
"self.dragging = False self.downPost = None def copy( self, context",
") glEnd() glPopAttrib() class FlowLineContext( BaseContext ): '''Context for drawing,",
"that len( names ) == len( lines ). @param names",
"- used for knowing what to do with the active",
"self.names = [ a for a in context.names ] self.lines",
"\"\"\"Detects click, drag, release and creates a line\"\"\" result =",
"into the stored set of lines. @return An instance of",
"= None self.canDraw = False self.dragging = False self.downPost =",
"): '''Causes the context to go into new line mode.",
"not self.cancelCB is None ): self.cancelCB() self.notifyEdit( None ) canceled",
"view ): \"\"\"Detects click, drag, release and creates a line\"\"\"",
"values should lie in the range [0, 1], to be",
"@param A 3-tuple of floats. The color of the line.",
"callable. An optional callback object for when a flow line",
"The color of the line. All values should lie in",
"True, True, False ) elif ( event.type == MouseEvent.MOVE ):",
"Segment from OpenGL.GL import * from copy import deepcopy class",
"= names self.activeID = -1 self.editState = self.NO_EDIT def handleMouse",
"( event.type == MouseEvent.UP ): if ( btn == MouseEvent.LEFT",
"optional callback object for when flow line drawing is canceled.",
"a line that has changed''' if ( not self.editCB is",
"idx ] = name def deleteLine( self, idx ): '''Removes",
"return len( self.lines ) def setMultiLines( self, names, lines ):",
"btn = event.button eX = event.x eY = event.y if",
"@param editCB A callable. An optional callback object for when",
"original disappears and the new line is drawn in cyan.'''",
"eY ) ) p2 = Vector2( x, y ) self.activeLine.p2",
"id ): '''Returns the name associated with the line index,",
"__str__( self ): return \"GLFlowSegment (%s, %s)\" % ( self.p1,",
"* from copy import deepcopy class GLFlowSegment( Segment ): '''The",
"def drawGL( self, color=(0.1, 1.0, 0.1) ): '''Draw the flow",
"idx def setLineName( self, idx, name ): '''Sets the name",
"idx ) self.activeID = -1 def flipLine( self, idx ):",
"view.screenToWorld( ( eX, eY ) ) p1 = Vector2( x,",
"( 1.0, 1.0, 0.1 ) ) for i, line in",
"segment into a GL context. @param A 3-tuple of floats.",
"== self.EDIT ): assert( self.activeID > -1 ) self.lines[ self.activeID",
"BaseContext ): '''Context for drawing, creating and editing lines''' MIN_LINE_LENGTH",
"primitives import Vector2, Segment from OpenGL.GL import * from copy",
"return len( self.lines ) def getName( self, id ): '''Returns",
"'''Flips the direction of the line in the set''' assert(",
"def __str__( self ): return \"GLFlowSegment (%s, %s)\" % (",
"-1 # the line currently affected by modifications self.editState =",
"of the lines''' self.lines = [] self.names = [] self.activeID",
"flipLine( self, idx ): '''Flips the direction of the line",
"line is drawn in cyan.''' if ( self.activeLine ): self.activeLine.drawGL(",
"self.activeID = -1 # the line currently affected by modifications",
"self, cancelCB=None, editCB=None ): '''Constructor. @param cancelCB A callable. An",
"the indicated line''' if ( self.editState == self.ADD): return if",
"be interpreted as r, g, b color values. ''' glPushAttrib(",
"active line''' self.activeID = idx def stopEdit( self ): '''Stops",
"EDIT = 1 ADD = 2 def __init__( self, cancelCB=None,",
"The flow direction is to the RIGHT of the segment.",
"( idx < 0 ): self.editState = self.NO_EDIT self.canDraw =",
"self.activeLine != None self.activeLine = None self.dragging = False result.set(",
"the edit if ( self.editState == self.ADD ): self.editState =",
"if ( self.editState == self.ADD ): self.activeID = len( self.lines",
"direction is the direction from p1 to p2.''' def __init__(",
"self, color=(0.1, 1.0, 0.1) ): '''Draw the flow segment into",
"list of Segment instaces. One line per name. ''' self.lines",
"True, True, False ) self.notifyEdit( self.activeLine ) return result def",
"class GLFlowSegment( Segment ): '''The OpenGL representation of a flow",
"a line\"\"\" result = ContextResult() try: event = self.canonicalEvent( evt",
"and when it is being edited, the original disappears and",
"a direciton indicator. The direction indicator shows which way flow",
"= GLFlowSegment( p1, p1 ) result.set( True, True, False )",
") if ( (endPos - self.downPos).magnitude() >= self.MIN_LINE_LENGTH ): if",
"line. @param lines A list of Segment instaces. One line",
"len( self.lines ) ) self.lines[ idx ].flip() def setActive( self,",
"n glVertex2f( mp.x, mp.y ) glVertex2f( end.x, end.y ) glEnd()",
"): x, y = view.screenToWorld( ( eX, eY ) )",
"self ): return \"GLFlowSegment (%s, %s)\" % ( self.p1, self.p2",
"instance of Vector2. The start point of the segment. @param",
"to be interpreted as r, g, b color values. '''",
") elif ( self.editState == self.EDIT ): assert( self.activeID >",
"being edited, the original disappears and the new line is",
"enumerate( self.lines ): if ( i == self.activeID ): continue",
"self.names.append( 'Line %d' % len( self.names ) ) self.lines.append( GLFlowSegment(",
"object for when flow line drawing is canceled. @param editCB",
"self.editState = self.NO_EDIT self.cancelCB = cancelCB self.editCB = editCB self.activeLine",
"self ): return len( self.lines ) def getName( self, id",
"): '''Sets the active line''' self.activeID = idx def stopEdit(",
"elif ( self.editState == self.EDIT ): assert( self.activeID > -1",
"the segment. @param p2 An instance of Vector2. The end",
"): '''Returns the name associated with the line index, id.",
"None def lineCount( self ): return len( self.lines ) def",
"is expected to cross the line. The flow direction is",
"map( lambda x: GLFlowSegment( x.p1, x.p2 ), lines ) self.names",
") def setMultiLines( self, names, lines ): '''Sets the lines",
"as e: return result if ( not self.canDraw ): return",
"if ( not self.cancelCB is None ): self.cancelCB() self.notifyEdit( None",
"g, b color values. ''' glPushAttrib( GL_COLOR_BUFFER_BIT ) glBegin( GL_LINES",
"= idx def stopEdit( self ): '''Stops the ability to",
"= None def lineCount( self ): return len( self.lines )",
"-1 and self.editState != self.ADD ): self.lines[ self.activeID ].drawGL( (",
"= self.EDIT self.canDraw = True self.activeID = idx def setLineName(",
"editLine( self, idx ): '''Edits the indicated line''' if (",
") == len( lines ). @param names A list of",
"cyan.''' if ( self.activeLine ): self.activeLine.drawGL( ( 0.1, 1.0, 1.0",
"the OpenGL context for drawing flow calculation lines from Context",
"self.names = [] self.activeID = -1 # the line currently",
"None def copy( self, context ): '''Copy the state of",
"interpreted as r, g, b color values. ''' glPushAttrib( GL_COLOR_BUFFER_BIT",
"editCB=None ): '''Constructor. @param cancelCB A callable. An optional callback",
"): '''Stops the ability to edit''' self.editState = self.NO_EDIT self.canDraw",
"if ( self.activeLine ): self.activeLine.drawGL( ( 0.1, 1.0, 1.0 )",
"object for when a flow line values are edited. '''",
"lines ). @param names A list of strings. One name",
"string. The stored name. ''' return self.names[ id ] def",
") self.activeLine = None self.activeLine = None self.dragging = False",
"self.activeID = len( self.lines ) - 1 self.lines[self.activeID] = self.activeLine",
"): assert( self.activeID > -1 ) self.lines[ self.activeID ] =",
"len( names ) == len( lines ). @param names A",
"if ( not self.editCB is None ): self.editCB( line )",
"id. @param id An integer. The index into the stored",
"self.activeLine.drawGL( ( 0.1, 1.0, 1.0 ) ) elif ( self.activeID",
"GL_COLOR_BUFFER_BIT ) glBegin( GL_LINES ) glColor3fv( color ) glVertex2f( self.p1.x,",
"copy( self, context ): '''Copy the state of the given",
"to edit''' self.editState = self.NO_EDIT self.canDraw = False def getLineCount(",
"event.x eY = event.y if ( event.type == MouseEvent.DOWN ):",
"x, y = view.screenToWorld( ( eX, eY ) ) p2",
"An instance of a FlowLine. ''' return self.lines[ id ]",
"of a flow line. Basically a segment with a direciton",
"@param p2 An instance of Vector2. The end point of",
"= True self.notifyEdit( self.activeLine ) elif ( btn == MouseEvent.RIGHT",
"= 2 def __init__( self, cancelCB=None, editCB=None ): '''Constructor. @param",
"self.editCB( line ) def drawGL( self ): '''Basic lines are",
"An instance of Vector2. The start point of the segment.",
"self.NO_EDIT self.cancelCB = cancelCB self.editCB = editCB self.activeLine = None",
"def copy( self, context ): '''Copy the state of the",
"0 EDIT = 1 ADD = 2 def __init__( self,",
"for a in context.names ] self.lines = deepcopy( context.lines )",
"= self.NO_EDIT self.canDraw = False def getLineCount( self ): \"\"\"Returns",
"glPushAttrib( GL_COLOR_BUFFER_BIT ) glBegin( GL_LINES ) glColor3fv( color ) glVertex2f(",
"edited. ''' BaseContext.__init__( self ) self.lines = [] self.names =",
"of strings. One name per line. @param lines A list",
"- self.downPos).magnitude() >= self.MIN_LINE_LENGTH ): if ( self.editState == self.ADD",
") self.dragging = True self.notifyEdit( self.activeLine ) elif ( btn",
"): '''Flips the direction of the line in the set'''",
"].flip() def setActive( self, idx ): '''Sets the active line'''",
"Context import * from primitives import Vector2, Segment from OpenGL.GL",
"the original disappears and the new line is drawn in",
"self, idx ): '''Flips the direction of the line in",
"try: event = self.canonicalEvent( evt ) except ValueError as e:",
"#QtCore.QEvent.MouseButtonPress ): if ( btn == MouseEvent.LEFT ): self.downPos =",
"release and creates a line\"\"\" result = ContextResult() try: event",
"Vector2. The end point of the segment. ''' Segment.__init__( self,",
"active line and cancellation NO_EDIT = 0 EDIT = 1",
"= 1 ADD = 2 def __init__( self, cancelCB=None, editCB=None",
"= False self.dragging = False self.downPost = None def copy(",
"A string. The stored name. ''' return self.names[ id ]",
") glColor3fv( color ) glVertex2f( self.p1.x, self.p1.y ) glVertex2f( self.p2.x,",
"'''Removes a line from the set''' assert( idx >= 0",
"self.lines ) ) self.lines[ idx ].flip() def setActive( self, idx",
"strings. One name per line. @param lines A list of",
"* (0.25 * l ) end = mp + n",
"context with the given names and lines. It is asserted",
"p2 result.set( True, True, False ) self.notifyEdit( self.activeLine ) return",
"NO_EDIT = 0 EDIT = 1 ADD = 2 def",
"return str( self ) def drawGL( self, color=(0.1, 1.0, 0.1)",
"'''Clears out all of the lines''' self.lines = [] self.names",
"end = mp + n glVertex2f( mp.x, mp.y ) glVertex2f(",
"self.editState == self.ADD ): self.editState = self.NO_EDIT self.lines.pop(-1) self.names.pop(-1) if",
"with a direciton indicator. The direction indicator shows which way",
"self.canDraw ): return result if ( event.noModifiers() ): btn =",
"mp + n glVertex2f( mp.x, mp.y ) glVertex2f( end.x, end.y",
"of floats. The color of the line. All values should",
"[] self.activeID = -1 self.editState = self.NO_EDIT self.activeLine = None",
") glVertex2f( self.p1.x, self.p1.y ) glVertex2f( self.p2.x, self.p2.y ) mp",
"lines ) self.names = names self.activeID = -1 self.editState =",
"except ValueError as e: return result if ( not self.canDraw",
"line in the set''' assert( idx >= 0 and idx",
"'''Copy the state of the given FlowLineContext into this''' assert(",
"@return A string. The stored name. ''' return self.names[ id",
"One line per name. ''' self.lines = map( lambda x:",
"= 2 # the minimum drag required to draw a",
"glPopAttrib() class FlowLineContext( BaseContext ): '''Context for drawing, creating and",
"True self.activeID = idx def setLineName( self, idx, name ):",
"line currently affected by modifications self.editState = self.NO_EDIT self.cancelCB =",
"per name. ''' self.lines = map( lambda x: GLFlowSegment( x.p1,",
"self.names[ id ] def getLine( self, id ): '''Returns the",
"line per name. ''' self.lines = map( lambda x: GLFlowSegment(",
"and creates a line\"\"\" result = ContextResult() try: event =",
"): '''Constructor. @param cancelCB A callable. An optional callback object",
"number of defined lines\"\"\" return len( self.lines ) def setMultiLines(",
"and self.dragging ): endPos = Vector2( eX, eY ) if",
"endPos = Vector2( eX, eY ) if ( (endPos -",
"MouseEvent.MOVE ): if ( self.dragging ): x, y = view.screenToWorld(",
"self.activeLine ) return result def notifyEdit( self, line ): '''Notifies",
"__init__( self, cancelCB=None, editCB=None ): '''Constructor. @param cancelCB A callable.",
"= self.NO_EDIT def handleMouse ( self, evt, view ): \"\"\"Detects",
"lie in the range [0, 1], to be interpreted as",
"def notifyEdit( self, line ): '''Notifies call back of a",
"x: GLFlowSegment( x.p1, x.p2 ), lines ) self.names = names",
"line that has changed''' if ( not self.editCB is None",
"0), Vector2(0, 0) ) ) self.activeLine = self.lines[-1] return self.names[-1]",
"len( self.lines ) def setMultiLines( self, names, lines ): '''Sets",
"a in context.names ] self.lines = deepcopy( context.lines ) def",
"from copy import deepcopy class GLFlowSegment( Segment ): '''The OpenGL",
"btn == MouseEvent.LEFT ): self.downPos = Vector2( eX, eY )",
"# This is the OpenGL context for drawing flow calculation",
"point of the segment. @param p2 An instance of Vector2.",
"given index''' self.names[ idx ] = name def deleteLine( self,",
"): #QtCore.QEvent.MouseButtonPress ): if ( btn == MouseEvent.LEFT ): self.downPos",
"self.NO_EDIT self.canDraw = False self.activeID = -1 else: self.editState =",
"context.lines ) def clear( self ): '''Clears out all of",
"not self.editCB is None ): self.editCB( line ) def drawGL(",
"= event.button eX = event.x eY = event.y if (",
"of a FlowLine. ''' return self.lines[ id ] def addLine(",
"FlowLineContext into this''' assert( isinstance( context, FlowLineContext ) ) self.clear()",
"The forward direction is the direction from p1 to p2.'''",
"= [] self.names = [] self.activeID = -1 self.editState =",
"line. Basically a segment with a direciton indicator. The direction",
"* l ) end = mp + n glVertex2f( mp.x,",
"self.ADD self.activeID = -1 self.names.append( 'Line %d' % len( self.names",
"index into the stored set of lines. @return An instance",
"len( self.lines ) - 1 self.lines[self.activeID] = self.activeLine self.editState =",
"new name.''' self.canDraw = True self.editState = self.ADD self.activeID =",
"self ): return str( self ) def drawGL( self, color=(0.1,",
"context, FlowLineContext ) ) self.clear() self.names = [ a for",
"self.names ) ) self.lines.append( GLFlowSegment( Vector2(0, 0), Vector2(0, 0) )",
"the active line and cancellation NO_EDIT = 0 EDIT =",
"calculation lines from Context import * from primitives import Vector2,",
"self.lines = [] self.names = [] self.activeID = -1 #",
"FlowLineContext( BaseContext ): '''Context for drawing, creating and editing lines'''",
"self ): '''Clears out all of the lines''' self.lines =",
"context.names ] self.lines = deepcopy( context.lines ) def clear( self",
"''' return self.lines[ id ] def addLine( self ): '''Causes",
"the active line''' self.activeID = idx def stopEdit( self ):",
"line. The flow direction is to the RIGHT of the",
"eY ) x, y = view.screenToWorld( ( eX, eY )",
"True self.notifyEdit( self.activeLine ) elif ( btn == MouseEvent.RIGHT and",
"result.set( True, True, False ) elif ( event.type == MouseEvent.MOVE",
"( self.editState == self.EDIT ): assert( self.activeID > -1 )",
"back of a line that has changed''' if ( not",
"glBegin( GL_LINES ) glColor3fv( color ) glVertex2f( self.p1.x, self.p1.y )",
"= deepcopy( context.lines ) def clear( self ): '''Clears out",
"): '''Sets the lines in the context with the given",
"start point of the segment. @param p2 An instance of",
"@param names A list of strings. One name per line.",
"self.lines[self.activeID] = self.activeLine self.editState = self.EDIT self.notifyEdit( self.activeLine ) elif",
"MIN_LINE_LENGTH = 2 # the minimum drag required to draw",
"!= None self.activeLine = None self.dragging = False result.set( canceled,",
"The index into the stored set of lines. @return A",
"as r, g, b color values. ''' glPushAttrib( GL_COLOR_BUFFER_BIT )",
"False self.dragging = False self.downPost = None def copy( self,",
"self.ADD ): self.editState = self.NO_EDIT self.lines.pop(-1) self.names.pop(-1) if ( not",
") self.lines = [] self.names = [] self.activeID = -1",
"len( lines ). @param names A list of strings. One",
"An integer. The index into the stored set of lines.",
"drag required to draw a line # edit state -",
"return \"GLFlowSegment (%s, %s)\" % ( self.p1, self.p2 ) def",
"way flow is expected to cross the line. The flow",
"the number of defined lines\"\"\" return len( self.lines ) def",
"Vector2(0, 0) ) ) self.activeLine = self.lines[-1] return self.names[-1] def",
"FlowLine. ''' return self.lines[ id ] def addLine( self ):",
") def getName( self, id ): '''Returns the name associated",
"0 ): self.editState = self.NO_EDIT self.canDraw = False self.activeID =",
"name def deleteLine( self, idx ): '''Removes a line from",
"None self.activeLine = None self.dragging = False result.set( canceled, canceled,",
"def addLine( self ): '''Causes the context to go into",
"One name per line. @param lines A list of Segment",
"self.dragging = False result.set( True, True, False ) elif (",
"in yellow, and when it is being edited, the original",
"idx ): '''Removes a line from the set''' assert( idx",
"( event.noModifiers() ): btn = event.button eX = event.x eY",
"x, y ) self.activeLine.p2 = p2 result.set( True, True, False",
"An optional callback object for when a flow line values",
"-1 ) self.lines[ self.activeID ] = self.activeLine self.notifyEdit( self.activeLine )",
"self.p2 ) def __repr__( self ): return str( self )",
"[ a for a in context.names ] self.lines = deepcopy(",
"Vector2( eX, eY ) if ( (endPos - self.downPos).magnitude() >=",
") mp = self.midPoint() l = self.magnitude() n = self.normal()",
"self.lines[-1] return self.names[-1] def editLine( self, idx ): '''Edits the"
] |
[] |
[
"print_numbers(): time.sleep(0.2) print(\"子线程结束\") if __name__ == \"__main__\": t1 = Thread(target=print_numbers)",
"@File: test.py # @Desc: from threading import Thread import time",
"def print_numbers(): time.sleep(0.2) print(\"子线程结束\") if __name__ == \"__main__\": t1 =",
"# @File: test.py # @Desc: from threading import Thread import",
"# @Author: GraceKoo # @File: test.py # @Desc: from threading",
"# -*- coding: utf-8 -*- # @Time: 2020/11/8 23:47 #",
"__name__ == \"__main__\": t1 = Thread(target=print_numbers) t1.setDaemon(True) t1.start() # print(\"主线程结束\")",
"coding: utf-8 -*- # @Time: 2020/11/8 23:47 # @Author: GraceKoo",
"@Desc: from threading import Thread import time def print_numbers(): time.sleep(0.2)",
"utf-8 -*- # @Time: 2020/11/8 23:47 # @Author: GraceKoo #",
"@Time: 2020/11/8 23:47 # @Author: GraceKoo # @File: test.py #",
"import Thread import time def print_numbers(): time.sleep(0.2) print(\"子线程结束\") if __name__",
"import time def print_numbers(): time.sleep(0.2) print(\"子线程结束\") if __name__ == \"__main__\":",
"print(\"子线程结束\") if __name__ == \"__main__\": t1 = Thread(target=print_numbers) t1.setDaemon(True) t1.start()",
"from threading import Thread import time def print_numbers(): time.sleep(0.2) print(\"子线程结束\")",
"time.sleep(0.2) print(\"子线程结束\") if __name__ == \"__main__\": t1 = Thread(target=print_numbers) t1.setDaemon(True)",
"GraceKoo # @File: test.py # @Desc: from threading import Thread",
"# @Desc: from threading import Thread import time def print_numbers():",
"# @Time: 2020/11/8 23:47 # @Author: GraceKoo # @File: test.py",
"time def print_numbers(): time.sleep(0.2) print(\"子线程结束\") if __name__ == \"__main__\": t1",
"2020/11/8 23:47 # @Author: GraceKoo # @File: test.py # @Desc:",
"@Author: GraceKoo # @File: test.py # @Desc: from threading import",
"Thread import time def print_numbers(): time.sleep(0.2) print(\"子线程结束\") if __name__ ==",
"test.py # @Desc: from threading import Thread import time def",
"-*- coding: utf-8 -*- # @Time: 2020/11/8 23:47 # @Author:",
"threading import Thread import time def print_numbers(): time.sleep(0.2) print(\"子线程结束\") if",
"if __name__ == \"__main__\": t1 = Thread(target=print_numbers) t1.setDaemon(True) t1.start() #",
"-*- # @Time: 2020/11/8 23:47 # @Author: GraceKoo # @File:",
"23:47 # @Author: GraceKoo # @File: test.py # @Desc: from"
] |
[
"***********# SECRET_KEY = CONFIG_DATA[\"SECRET_KEY\"] # SECURITY WARNING: don't run with",
"USE_I18N = True USE_L10N = True USE_TZ = True EMAIL_BACKEND",
"'127.0.0.1', 'api.massenergize.org', 'apis.massenergize.org', 'api.massenergize.com', 'apis.massenergize.com', 'api-prod.massenergize.org', 'api.prod.massenergize.org', 'api-dev.massenergize.org', 'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com'",
"# https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' # Simplified",
"paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR =",
"validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', },",
"}, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {",
"{ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE",
"inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))",
"'remote-default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : os.environ.get('DATABASE_NAME'), 'USER' :",
"project. Generated by 'django-admin startproject' using Django 2.1.4. For more",
": os.environ.get('DATABASE_HOST'), 'PORT' : os.environ.get('DATABASE_PORT') }, 'default': { 'ENGINE' :",
"False SESSION_COOKIE_SECURE = False # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES =",
"'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware' ]",
"}, } firebase_service_account_path = '/_main_/config/massenergizeProdFirebaseServiceAccount.json' if IS_PROD else '/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS",
"AWS CONFIGURATION ---------------------# CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True DATA_UPLOAD_MAX_MEMORY_SIZE",
"EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT",
"'api.massenergize.com', 'apis.massenergize.com', 'api-prod.massenergize.org', 'api.prod.massenergize.org', 'api-dev.massenergize.org', 'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ] INSTALLED_APPS =",
"], }, }, ] WSGI_APPLICATION = '_main_.wsgi.application' CSRF_COOKIE_SECURE = False",
"more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full",
"# Build paths inside the project like this: os.path.join(BASE_DIR, ...)",
"'/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA = load_json(BASE_DIR + path_to_config) os.environ.update(CONFIG_DATA) # ******** END",
"True USE_L10N = True USE_TZ = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'",
"'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',",
"= os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = None #--------END AWS",
"= 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL') DEFAULT_FROM_EMAIL =",
"{ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':",
"os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ******** LOAD CONFIG DATA",
"if IS_PROD else '/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA = load_json(BASE_DIR + path_to_config) os.environ.update(CONFIG_DATA)",
"False # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'remote-default': {",
"{ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] #",
"# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {",
"in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', '127.0.0.1',",
"'storages.backends.s3boto3.S3Boto3Storage' #-------- FILE STORAGE CONFIGURATION ---------------------# #-------- AWS CONFIGURATION ---------------------#",
"'PASSWORD' : '', 'HOST' : 'localhost', 'PORT' : '5555' },",
"'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware' ] #-------- FILE STORAGE CONFIGURATION",
"'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware',",
"True ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'api.massenergize.org', 'apis.massenergize.org', 'api.massenergize.com', 'apis.massenergize.com',",
"'HOST' : os.environ.get('DATABASE_HOST'), 'PORT' : os.environ.get('DATABASE_PORT') }, 'default': { 'ENGINE'",
"path_to_config) os.environ.update(CONFIG_DATA) # ******** END LOAD CONFIG DATA ***********# SECRET_KEY",
"}, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/",
"# Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME':",
"DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440*3 ROOT_URLCONF = '_main_.urls' TEMPLATES = [ {",
"os.environ.get('DATABASE_PORT') }, 'default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : 'gchekler21',",
"'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware' ] #-------- FILE",
"'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : os.environ.get('DATABASE_NAME'), 'USER' : os.environ.get('DATABASE_USER'), 'PASSWORD'",
"DATABASES = { 'remote-default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' :",
"] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE =",
"SECURITY WARNING: don't run with debug turned on in production!",
"AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION = os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME",
"'_main_.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS':",
": os.environ.get('DATABASE_NAME'), 'USER' : os.environ.get('DATABASE_USER'), 'PASSWORD' : os.environ.get('DATABASE_PASSWORD'), 'HOST' :",
"'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '_main_.wsgi.application' CSRF_COOKIE_SECURE",
"= { 'remote-default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : os.environ.get('DATABASE_NAME'),",
"path_to_config = '/_main_/config/massenergizeProdConfig.json' if IS_PROD else '/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA = load_json(BASE_DIR",
"full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\"",
"TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ",
"= '/_main_/config/massenergizeProdConfig.json' if IS_PROD else '/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA = load_json(BASE_DIR +",
"# 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware' ] #--------",
"'HOST' : 'localhost', 'PORT' : '5555' }, } firebase_service_account_path =",
"AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = None #--------END AWS CONFIGURATION ---------------------#",
"'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #-------- FILE STORAGE CONFIGURATION ---------------------# #--------",
"for massenergize_portal_backend project. Generated by 'django-admin startproject' using Django 2.1.4.",
"CORS_ALLOW_CREDENTIALS = True DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440*3 ROOT_URLCONF = '_main_.urls' TEMPLATES",
"STATIC_URL = '/static/' MEDIA_URL = '/media/' # Simplified static file",
"'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '_main_.wsgi.application'",
"******** END LOAD CONFIG DATA ***********# SECRET_KEY = CONFIG_DATA[\"SECRET_KEY\"] #",
"'api-dev.massenergize.org', 'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ] INSTALLED_APPS = [ 'authentication', 'carbon_calculator', 'database',",
"'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },",
"and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" import os import firebase_admin",
"= True ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'api.massenergize.org', 'apis.massenergize.org', 'api.massenergize.com',",
"] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware',",
"Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'",
"'carbon_calculator', 'database', 'api', 'website', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',",
": os.environ.get('DATABASE_ENGINE'), 'NAME' : 'gchekler21', 'USER' : '', 'PASSWORD' :",
"'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',",
"'/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS = credentials.Certificate(BASE_DIR + firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS) # Password validation",
"debug turned on in production! DEBUG = True ALLOWED_HOSTS =",
"on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of",
"#-------- FILE STORAGE CONFIGURATION ---------------------# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE =",
"# Simplified static file serving. STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION =",
"# https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N =",
"= os.environ.get('EMAIL_PASSWORD') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/",
"# ******** LOAD CONFIG DATA ***********# IS_PROD = False path_to_config",
"EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') # Static files (CSS, JavaScript, Images) #",
"Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N",
"BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ******** LOAD CONFIG DATA ***********# IS_PROD",
"#--------END AWS CONFIGURATION ---------------------# CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True",
"CONFIG_DATA[\"SECRET_KEY\"] # SECURITY WARNING: don't run with debug turned on",
"FILE STORAGE CONFIGURATION ---------------------# #-------- AWS CONFIGURATION ---------------------# AWS_ACCESS_KEY_ID =",
"'/_main_/config/massenergizeProdFirebaseServiceAccount.json' if IS_PROD else '/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS = credentials.Certificate(BASE_DIR + firebase_service_account_path)",
"'NAME' : os.environ.get('DATABASE_NAME'), 'USER' : os.environ.get('DATABASE_USER'), 'PASSWORD' : os.environ.get('DATABASE_PASSWORD'), 'HOST'",
"CONFIGURATION ---------------------# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #-------- FILE",
"True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com'",
"'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization #",
"587 EMAIL_HOST_USER = os.environ.get('EMAIL') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD')",
"'_main_.wsgi.application' CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False # Database #",
"'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware',",
"the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #",
"'PORT' : '5555' }, } firebase_service_account_path = '/_main_/config/massenergizeProdFirebaseServiceAccount.json' if IS_PROD",
"Django settings for massenergize_portal_backend project. Generated by 'django-admin startproject' using",
"os.environ.get('DATABASE_ENGINE'), 'NAME' : 'gchekler21', 'USER' : '', 'PASSWORD' : '',",
"Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/",
"'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom middlewares",
"'authentication', 'carbon_calculator', 'database', 'api', 'website', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',",
"IS_PROD = False path_to_config = '/_main_/config/massenergizeProdConfig.json' if IS_PROD else '/_main_/config/massenergizeProjectConfig.json'",
"= True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER =",
"MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',",
": 'localhost', 'PORT' : '5555' }, } firebase_service_account_path = '/_main_/config/massenergizeProdFirebaseServiceAccount.json'",
"= os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ******** LOAD CONFIG DATA ***********# IS_PROD =",
"'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : 'gchekler21', 'USER' : '', 'PASSWORD'",
"STORAGE CONFIGURATION ---------------------# #-------- AWS CONFIGURATION ---------------------# AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')",
"os.environ.get('DATABASE_HOST'), 'PORT' : os.environ.get('DATABASE_PORT') }, 'default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'),",
"credentials from .utils.utils import load_json # Build paths inside the",
"***********# IS_PROD = False path_to_config = '/_main_/config/massenergizeProdConfig.json' if IS_PROD else",
"= None #--------END AWS CONFIGURATION ---------------------# CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS",
"'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',",
"}, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ]",
"'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', },",
"STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #-------- FILE STORAGE CONFIGURATION ---------------------# #-------- AWS",
"USE_L10N = True USE_TZ = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS",
"# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL =",
"'django-admin startproject' using Django 2.1.4. For more information on this",
"}, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE",
"this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings",
"= '/static/' MEDIA_URL = '/media/' # Simplified static file serving.",
"startproject' using Django 2.1.4. For more information on this file,",
"Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',",
": os.environ.get('DATABASE_ENGINE'), 'NAME' : os.environ.get('DATABASE_NAME'), 'USER' : os.environ.get('DATABASE_USER'), 'PASSWORD' :",
"'api.massenergize.org', 'apis.massenergize.org', 'api.massenergize.com', 'apis.massenergize.com', 'api-prod.massenergize.org', 'api.prod.massenergize.org', 'api-dev.massenergize.org', 'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ]",
"os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = None #--------END AWS CONFIGURATION ---------------------# CORS_ORIGIN_ALLOW_ALL =",
"SESSION_COOKIE_SECURE = False # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = {",
"'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '_main_.wsgi.application' CSRF_COOKIE_SECURE =",
"ROOT_URLCONF = '_main_.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':",
"#custom middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware' ] #-------- FILE STORAGE CONFIGURATION ---------------------# DEFAULT_FILE_STORAGE",
"] INSTALLED_APPS = [ 'authentication', 'carbon_calculator', 'database', 'api', 'website', 'corsheaders',",
"AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',",
"INSTALLED_APPS = [ 'authentication', 'carbon_calculator', 'database', 'api', 'website', 'corsheaders', 'django.contrib.admin',",
"'apis.massenergize.org', 'api.massenergize.com', 'apis.massenergize.com', 'api-prod.massenergize.org', 'api.prod.massenergize.org', 'api-dev.massenergize.org', 'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ] INSTALLED_APPS",
"'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization",
"}, ] WSGI_APPLICATION = '_main_.wsgi.application' CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE =",
"= '_main_.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [],",
"# SECURITY WARNING: don't run with debug turned on in",
"MEDIA_URL = '/media/' # Simplified static file serving. STATICFILES_LOCATION =",
"= 2621440*3 ROOT_URLCONF = '_main_.urls' TEMPLATES = [ { 'BACKEND':",
"'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',",
"'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',",
"os.environ.get('DATABASE_USER'), 'PASSWORD' : os.environ.get('DATABASE_PASSWORD'), 'HOST' : os.environ.get('DATABASE_HOST'), 'PORT' : os.environ.get('DATABASE_PORT')",
": '5555' }, } firebase_service_account_path = '/_main_/config/massenergizeProdFirebaseServiceAccount.json' if IS_PROD else",
"= True CORS_ALLOW_CREDENTIALS = True DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440*3 ROOT_URLCONF =",
"with debug turned on in production! DEBUG = True ALLOWED_HOSTS",
"https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME':",
"os.environ.get('EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') # Static files (CSS, JavaScript, Images)",
"os.environ.get('EMAIL_PASSWORD') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL",
"---------------------# #-------- AWS CONFIGURATION ---------------------# AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY =",
"JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/'",
"'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom",
"[ 'authentication', 'carbon_calculator', 'database', 'api', 'website', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',",
"None #--------END AWS CONFIGURATION ---------------------# CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS =",
"---------------------# CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440*3",
"USE_TZ = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST",
"DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #-------- FILE STORAGE CONFIGURATION",
"DATA ***********# IS_PROD = False path_to_config = '/_main_/config/massenergizeProdConfig.json' if IS_PROD",
"'PORT' : os.environ.get('DATABASE_PORT') }, 'default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME'",
"= '/_main_/config/massenergizeProdFirebaseServiceAccount.json' if IS_PROD else '/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS = credentials.Certificate(BASE_DIR +",
"WSGI_APPLICATION = '_main_.wsgi.application' CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False #",
"from .utils.utils import load_json # Build paths inside the project",
"import credentials from .utils.utils import load_json # Build paths inside",
"production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'api.massenergize.org',",
"'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ] INSTALLED_APPS = [ 'authentication', 'carbon_calculator', 'database', 'api', 'website',",
"EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL') EMAIL_HOST_PASSWORD",
"# ******** END LOAD CONFIG DATA ***********# SECRET_KEY = CONFIG_DATA[\"SECRET_KEY\"]",
"this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ******** LOAD CONFIG",
": os.environ.get('DATABASE_PORT') }, 'default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' :",
"if IS_PROD else '/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS = credentials.Certificate(BASE_DIR + firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS)",
"[ 'localhost', '127.0.0.1', 'api.massenergize.org', 'apis.massenergize.org', 'api.massenergize.com', 'apis.massenergize.com', 'api-prod.massenergize.org', 'api.prod.massenergize.org', 'api-dev.massenergize.org',",
"files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL",
"os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION = os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = None",
"For the full list of settings and their values, see",
"'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware' ] #-------- FILE STORAGE CONFIGURATION ---------------------#",
"like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ******** LOAD",
"END LOAD CONFIG DATA ***********# SECRET_KEY = CONFIG_DATA[\"SECRET_KEY\"] # SECURITY",
"= os.environ.get('EMAIL') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') # Static",
"= True USE_TZ = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS =",
"'gchekler21', 'USER' : '', 'PASSWORD' : '', 'HOST' : 'localhost',",
"Simplified static file serving. STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media'",
"'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [",
"DEFAULT_FROM_EMAIL = os.environ.get('EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') # Static files (CSS,",
"Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' #",
"CONFIGURATION ---------------------# CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True DATA_UPLOAD_MAX_MEMORY_SIZE =",
"AWS CONFIGURATION ---------------------# AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME",
"credentials.Certificate(BASE_DIR + firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS) # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS",
"file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and",
"'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware',",
"True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ],",
"'/_main_/config/massenergizeProdConfig.json' if IS_PROD else '/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA = load_json(BASE_DIR + path_to_config)",
"'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware' ] #-------- FILE STORAGE",
"turned on in production! DEBUG = True ALLOWED_HOSTS = [",
"'api.prod.massenergize.org', 'api-dev.massenergize.org', 'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ] INSTALLED_APPS = [ 'authentication', 'carbon_calculator',",
"\"\"\" import os import firebase_admin from firebase_admin import credentials from",
"their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" import os import firebase_admin from",
"= 'storages.backends.s3boto3.S3Boto3Storage' #-------- FILE STORAGE CONFIGURATION ---------------------# #-------- AWS CONFIGURATION",
"---------------------# AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')",
"CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases",
"'authentication.middleware.MassenergizeJWTAuthMiddleware' ] #-------- FILE STORAGE CONFIGURATION ---------------------# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'",
"by 'django-admin startproject' using Django 2.1.4. For more information on",
"settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" import os import",
"] #-------- FILE STORAGE CONFIGURATION ---------------------# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE",
"= CONFIG_DATA[\"SECRET_KEY\"] # SECURITY WARNING: don't run with debug turned",
"} firebase_service_account_path = '/_main_/config/massenergizeProdFirebaseServiceAccount.json' if IS_PROD else '/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS =",
"CONFIGURATION ---------------------# AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME =",
"= 'UTC' USE_I18N = True USE_L10N = True USE_TZ =",
"True USE_TZ = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True",
"CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440*3 ROOT_URLCONF",
"'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE =",
": os.environ.get('DATABASE_USER'), 'PASSWORD' : os.environ.get('DATABASE_PASSWORD'), 'HOST' : os.environ.get('DATABASE_HOST'), 'PORT' :",
"https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'remote-default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME'",
"import os import firebase_admin from firebase_admin import credentials from .utils.utils",
"[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {",
"}, }, ] WSGI_APPLICATION = '_main_.wsgi.application' CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE",
"= '/media/' # Simplified static file serving. STATICFILES_LOCATION = 'static'",
"True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL')",
"'USER' : '', 'PASSWORD' : '', 'HOST' : 'localhost', 'PORT'",
"'5555' }, } firebase_service_account_path = '/_main_/config/massenergizeProdFirebaseServiceAccount.json' if IS_PROD else '/_main_/config/massenergizeFirebaseServiceAccount.json'",
"+ path_to_config) os.environ.update(CONFIG_DATA) # ******** END LOAD CONFIG DATA ***********#",
"= os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION = os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL =",
"https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values,",
"list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" import",
"[], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',",
"'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us'",
"values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" import os import firebase_admin from firebase_admin",
"settings for massenergize_portal_backend project. Generated by 'django-admin startproject' using Django",
"os.environ.update(CONFIG_DATA) # ******** END LOAD CONFIG DATA ***********# SECRET_KEY =",
"'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',",
"os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION = os.environ.get('AWS_S3_SIGNATURE_VERSION')",
"'/media/' # Simplified static file serving. STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION",
"= False SESSION_COOKIE_SECURE = False # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES",
"= 587 EMAIL_HOST_USER = os.environ.get('EMAIL') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL') EMAIL_HOST_PASSWORD =",
"= credentials.Certificate(BASE_DIR + firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS) # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators",
"AWS_S3_SIGNATURE_VERSION = os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = None #--------END",
"[ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {",
"= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS':",
"FILE STORAGE CONFIGURATION ---------------------# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'",
"os.environ.get('DATABASE_ENGINE'), 'NAME' : os.environ.get('DATABASE_NAME'), 'USER' : os.environ.get('DATABASE_USER'), 'PASSWORD' : os.environ.get('DATABASE_PASSWORD'),",
"...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ******** LOAD CONFIG DATA ***********#",
"https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" import os import firebase_admin from firebase_admin import credentials",
"don't run with debug turned on in production! DEBUG =",
"= 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT =",
"= True DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440*3 ROOT_URLCONF = '_main_.urls' TEMPLATES =",
"[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',",
"'localhost', 'PORT' : '5555' }, } firebase_service_account_path = '/_main_/config/massenergizeProdFirebaseServiceAccount.json' if",
"FIREBASE_CREDENTIALS = credentials.Certificate(BASE_DIR + firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS) # Password validation #",
"# Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC'",
"False path_to_config = '/_main_/config/massenergizeProdConfig.json' if IS_PROD else '/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA =",
"IS_PROD else '/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS = credentials.Certificate(BASE_DIR + firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS) #",
"project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ********",
"'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', #",
"'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], },",
"{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors':",
"see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" import os import firebase_admin from firebase_admin import",
"'USER' : os.environ.get('DATABASE_USER'), 'PASSWORD' : os.environ.get('DATABASE_PASSWORD'), 'HOST' : os.environ.get('DATABASE_HOST'), 'PORT'",
"'NAME' : 'gchekler21', 'USER' : '', 'PASSWORD' : '', 'HOST'",
"'', 'PASSWORD' : '', 'HOST' : 'localhost', 'PORT' : '5555'",
"import firebase_admin from firebase_admin import credentials from .utils.utils import load_json",
"load_json # Build paths inside the project like this: os.path.join(BASE_DIR,",
"---------------------# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #-------- FILE STORAGE",
"CONFIGURATION ---------------------# #-------- AWS CONFIGURATION ---------------------# AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY",
"(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL =",
"CONFIG_DATA = load_json(BASE_DIR + path_to_config) os.environ.update(CONFIG_DATA) # ******** END LOAD",
"= [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',",
"\"\"\" Django settings for massenergize_portal_backend project. Generated by 'django-admin startproject'",
"CONFIG DATA ***********# IS_PROD = False path_to_config = '/_main_/config/massenergizeProdConfig.json' if",
"'default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : 'gchekler21', 'USER' :",
"os import firebase_admin from firebase_admin import credentials from .utils.utils import",
"firebase_service_account_path = '/_main_/config/massenergizeProdFirebaseServiceAccount.json' if IS_PROD else '/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS = credentials.Certificate(BASE_DIR",
"'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587",
"https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True",
"load_json(BASE_DIR + path_to_config) os.environ.update(CONFIG_DATA) # ******** END LOAD CONFIG DATA",
"True CORS_ALLOW_CREDENTIALS = True DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440*3 ROOT_URLCONF = '_main_.urls'",
"{ 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : os.environ.get('DATABASE_NAME'), 'USER' : os.environ.get('DATABASE_USER'),",
"= True USE_L10N = True USE_TZ = True EMAIL_BACKEND =",
".utils.utils import load_json # Build paths inside the project like",
"'api-prod.massenergize.org', 'api.prod.massenergize.org', 'api-dev.massenergize.org', 'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ] INSTALLED_APPS = [ 'authentication',",
"'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]",
"= os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = None #--------END AWS CONFIGURATION ---------------------# CORS_ORIGIN_ALLOW_ALL",
"import load_json # Build paths inside the project like this:",
"os.environ.get('DATABASE_NAME'), 'USER' : os.environ.get('DATABASE_USER'), 'PASSWORD' : os.environ.get('DATABASE_PASSWORD'), 'HOST' : os.environ.get('DATABASE_HOST'),",
"AWS_DEFAULT_ACL = None #--------END AWS CONFIGURATION ---------------------# CORS_ORIGIN_ALLOW_ALL = True",
"] WSGI_APPLICATION = '_main_.wsgi.application' CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False",
"{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },",
"{ 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : 'gchekler21', 'USER' : '',",
"= [ 'authentication', 'carbon_calculator', 'database', 'api', 'website', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth',",
"For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the",
"os.environ.get('DATABASE_PASSWORD'), 'HOST' : os.environ.get('DATABASE_HOST'), 'PORT' : os.environ.get('DATABASE_PORT') }, 'default': {",
"= [ 'localhost', '127.0.0.1', 'api.massenergize.org', 'apis.massenergize.org', 'api.massenergize.com', 'apis.massenergize.com', 'api-prod.massenergize.org', 'api.prod.massenergize.org',",
"2621440*3 ROOT_URLCONF = '_main_.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',",
"ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'api.massenergize.org', 'apis.massenergize.org', 'api.massenergize.com', 'apis.massenergize.com', 'api-prod.massenergize.org',",
"'UTC' USE_I18N = True USE_L10N = True USE_TZ = True",
"#-------- AWS CONFIGURATION ---------------------# AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')",
"on in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost',",
"'', 'HOST' : 'localhost', 'PORT' : '5555' }, } firebase_service_account_path",
"[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION",
"LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N",
"'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ] INSTALLED_APPS = [ 'authentication', 'carbon_calculator', 'database', 'api',",
"'apis.massenergize.com', 'api-prod.massenergize.org', 'api.prod.massenergize.org', 'api-dev.massenergize.org', 'api.dev.massenergize.org', 'massenergize-api.wpdvzstek2.us-east-2.elasticbeanstalk.com' ] INSTALLED_APPS = [",
"#-------- FILE STORAGE CONFIGURATION ---------------------# #-------- AWS CONFIGURATION ---------------------# AWS_ACCESS_KEY_ID",
": '', 'HOST' : 'localhost', 'PORT' : '5555' }, }",
"= [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', },",
"# Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'remote-default': { 'ENGINE'",
"LOAD CONFIG DATA ***********# IS_PROD = False path_to_config = '/_main_/config/massenergizeProdConfig.json'",
"'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #custom middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware'",
"see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their",
"else '/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA = load_json(BASE_DIR + path_to_config) os.environ.update(CONFIG_DATA) # ********",
"STORAGE CONFIGURATION ---------------------# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #--------",
"= False path_to_config = '/_main_/config/massenergizeProdConfig.json' if IS_PROD else '/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA",
"'api', 'website', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]",
"{ 'remote-default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : os.environ.get('DATABASE_NAME'), 'USER'",
"massenergize_portal_backend project. Generated by 'django-admin startproject' using Django 2.1.4. For",
"AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION = os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL",
"'localhost', '127.0.0.1', 'api.massenergize.org', 'apis.massenergize.org', 'api.massenergize.com', 'apis.massenergize.com', 'api-prod.massenergize.org', 'api.prod.massenergize.org', 'api-dev.massenergize.org', 'api.dev.massenergize.org',",
"EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER",
"SECRET_KEY = CONFIG_DATA[\"SECRET_KEY\"] # SECURITY WARNING: don't run with debug",
"WARNING: don't run with debug turned on in production! DEBUG",
"Generated by 'django-admin startproject' using Django 2.1.4. For more information",
"firebase_admin from firebase_admin import credentials from .utils.utils import load_json #",
"= '_main_.wsgi.application' CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False # Database",
"2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For",
"using Django 2.1.4. For more information on this file, see",
": 'gchekler21', 'USER' : '', 'PASSWORD' : '', 'HOST' :",
"Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'remote-default': { 'ENGINE' :",
"from firebase_admin import credentials from .utils.utils import load_json # Build",
"= 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #-------- FILE STORAGE CONFIGURATION ---------------------#",
"'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION =",
": '', 'PASSWORD' : '', 'HOST' : 'localhost', 'PORT' :",
"= load_json(BASE_DIR + path_to_config) os.environ.update(CONFIG_DATA) # ******** END LOAD CONFIG",
"middlewares 'authentication.middleware.MassenergizeJWTAuthMiddleware' ] #-------- FILE STORAGE CONFIGURATION ---------------------# DEFAULT_FILE_STORAGE =",
"information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list",
"# https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'remote-default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'),",
"DEBUG = True ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'api.massenergize.org', 'apis.massenergize.org',",
"the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/",
"run with debug turned on in production! DEBUG = True",
"= 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N =",
"LOAD CONFIG DATA ***********# SECRET_KEY = CONFIG_DATA[\"SECRET_KEY\"] # SECURITY WARNING:",
"= os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION =",
"}, 'default': { 'ENGINE' : os.environ.get('DATABASE_ENGINE'), 'NAME' : 'gchekler21', 'USER'",
"of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ \"\"\" import os",
"'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True",
"CONFIG DATA ***********# SECRET_KEY = CONFIG_DATA[\"SECRET_KEY\"] # SECURITY WARNING: don't",
"'PASSWORD' : os.environ.get('DATABASE_PASSWORD'), 'HOST' : os.environ.get('DATABASE_HOST'), 'PORT' : os.environ.get('DATABASE_PORT') },",
": os.environ.get('DATABASE_PASSWORD'), 'HOST' : os.environ.get('DATABASE_HOST'), 'PORT' : os.environ.get('DATABASE_PORT') }, 'default':",
"'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL')",
"'/static/' MEDIA_URL = '/media/' # Simplified static file serving. STATICFILES_LOCATION",
"'website', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE",
"os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = None #--------END AWS CONFIGURATION",
"= os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION = os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME =",
"firebase_admin.initialize_app(FIREBASE_CREDENTIALS) # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {",
"EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL') DEFAULT_FROM_EMAIL",
"firebase_admin import credentials from .utils.utils import load_json # Build paths",
"'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [",
"https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' # Simplified static",
"Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR",
"******** LOAD CONFIG DATA ***********# IS_PROD = False path_to_config =",
"os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION = os.environ.get('AWS_S3_SIGNATURE_VERSION') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME')",
"IS_PROD else '/_main_/config/massenergizeProjectConfig.json' CONFIG_DATA = load_json(BASE_DIR + path_to_config) os.environ.update(CONFIG_DATA) #",
"AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_SIGNATURE_VERSION",
"= False # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'remote-default':",
"EMAIL_HOST_USER = os.environ.get('EMAIL') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') #",
"{ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME':",
"else '/_main_/config/massenergizeFirebaseServiceAccount.json' FIREBASE_CREDENTIALS = credentials.Certificate(BASE_DIR + firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS) # Password",
"'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE =",
"firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS) # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [",
"TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True,",
"os.environ.get('EMAIL') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') # Static files",
"DATA ***********# SECRET_KEY = CONFIG_DATA[\"SECRET_KEY\"] # SECURITY WARNING: don't run",
"os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ******** LOAD CONFIG DATA ***********# IS_PROD = False",
"= True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST =",
"'database', 'api', 'website', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',",
"True DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440*3 ROOT_URLCONF = '_main_.urls' TEMPLATES = [",
"= os.environ.get('EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') # Static files (CSS, JavaScript,",
"+ firebase_service_account_path) firebase_admin.initialize_app(FIREBASE_CREDENTIALS) # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS ="
] |
[
"= None _method = None _requests: dict = {} _running",
"dict = {} _running = True _request_queue: asyncio.Queue = asyncio.Queue()",
"loop async def open(self): await self._provider.open() asyncio.ensure_future(self.request_loop(), loop=self._loop) asyncio.ensure_future(self.run(), loop=self._loop)",
"if not self.provider.is_connected(): raise ConnectionError(f'Connection lost. {self._provider}') task = AsyncTask().create(self._method,",
"ConnectionError(f'Connection lost. {self._provider}') task = AsyncTask().create(self._method, *args, **kwargs) if 'parallel'",
"= asyncio.get_event_loop() self._loop = loop async def open(self): await self._provider.open()",
"_provider = None _method = None _requests: dict = {}",
"task.error is None: self._requests[ response.id ].status = State.COMPLETED else: self._requests[response.id].status",
"self._requests[response.id] task.result = response.result task.error = response.error if task.error is",
"= provider if loop is None: loop = asyncio.get_event_loop() self._loop",
"self.provider.call_method(task) task.status = State.RUNNING if self._request_queue.empty(): self._request_queue.task_done() async def run(self):",
"AsyncClient: _provider = None _method = None _requests: dict =",
"if responses is not None: for response in responses: if",
"task.callback(task), loop=self._loop ) def __call__(self, *args, **kwargs): if not self.provider.is_connected():",
"self._request_queue.put(None) async def request_loop(self): while self._running: task = await self._request_queue.get()",
"not self.provider.is_connected(): raise ConnectionError(f'Connection lost. {self._provider}') task = AsyncTask().create(self._method, *args,",
"asyncio.Queue = asyncio.Queue() _loop = None def __init__(self, provider, loop=None):",
"self._provider = provider if loop is None: loop = asyncio.get_event_loop()",
"loop is None: loop = asyncio.get_event_loop() self._loop = loop async",
"class AsyncClient: _provider = None _method = None _requests: dict",
"{} _running = True _request_queue: asyncio.Queue = asyncio.Queue() _loop =",
"self._requests[ response.id ].status = State.COMPLETED else: self._requests[response.id].status = State.FAILED task.event.set()",
"not None: for response in responses: if response.id in self._requests:",
"task.event.set() del self._requests[response.id] if task._callback is not None: asyncio.ensure_future( task.callback(task),",
"Client from aiorpcgrid.task import AsyncTask, State class AsyncClient: _provider =",
"await self._provider.close() await self._request_queue.put(None) async def request_loop(self): while self._running: task",
"loop=self._loop) asyncio.ensure_future(self.run(), loop=self._loop) return self async def close(self): self._running =",
"def request_loop(self): while self._running: task = await self._request_queue.get() if task",
"self._requests[response.id] if task._callback is not None: asyncio.ensure_future( task.callback(task), loop=self._loop )",
"await self._request_queue.put(None) async def request_loop(self): while self._running: task = await",
"provider, loop=None): self._provider = provider if loop is None: loop",
"if response.id in self._requests: task = self._requests[response.id] task.result = response.result",
"close(self): self._running = False await self._provider.close() await self._request_queue.put(None) async def",
"task.result = response.result task.error = response.error if task.error is None:",
"State.RUNNING if self._request_queue.empty(): self._request_queue.task_done() async def run(self): while self._running: responses",
"task._callback is not None: asyncio.ensure_future( task.callback(task), loop=self._loop ) def __call__(self,",
"State.FAILED task.event.set() del self._requests[response.id] if task._callback is not None: asyncio.ensure_future(",
"from aiorpcgrid.task import AsyncTask, State class AsyncClient: _provider = None",
"self._request_queue.task_done() async def run(self): while self._running: responses = await self._provider.recv()",
"in self._requests: task = self._requests[response.id] task.result = response.result task.error =",
"aiorpcgrid.task import AsyncTask, State class AsyncClient: _provider = None _method",
"not None: asyncio.ensure_future( task.callback(task), loop=self._loop ) def __call__(self, *args, **kwargs):",
"# from aiorpcgrid.client import Client from aiorpcgrid.task import AsyncTask, State",
"None: loop = asyncio.get_event_loop() self._loop = loop async def open(self):",
"def __call__(self, *args, **kwargs): if not self.provider.is_connected(): raise ConnectionError(f'Connection lost.",
"if 'parallel' in kwargs: task._parallel = kwargs['parallel'] self._method = None",
"open(self): await self._provider.open() asyncio.ensure_future(self.request_loop(), loop=self._loop) asyncio.ensure_future(self.run(), loop=self._loop) return self async",
"def __init__(self, provider, loop=None): self._provider = provider if loop is",
"self._method = None task.status = State.PENDING self._requests[task.id] = task self._request_queue.put_nowait(self._requests[task.id])",
"if task.error is None: self._requests[ response.id ].status = State.COMPLETED else:",
"None task.status = State.PENDING self._requests[task.id] = task self._request_queue.put_nowait(self._requests[task.id]) return self._requests[task.id]",
"task = await self._request_queue.get() if task is not None: await",
"__call__(self, *args, **kwargs): if not self.provider.is_connected(): raise ConnectionError(f'Connection lost. {self._provider}')",
"asyncio.ensure_future(self.request_loop(), loop=self._loop) asyncio.ensure_future(self.run(), loop=self._loop) return self async def close(self): self._running",
"is not None: await self.provider.call_method(task) task.status = State.RUNNING if self._request_queue.empty():",
"in kwargs: task._parallel = kwargs['parallel'] self._method = None task.status =",
"is not None: asyncio.ensure_future( task.callback(task), loop=self._loop ) def __call__(self, *args,",
"self._running: responses = await self._provider.recv() if responses is not None:",
"responses: if response.id in self._requests: task = self._requests[response.id] task.result =",
"= State.COMPLETED else: self._requests[response.id].status = State.FAILED task.event.set() del self._requests[response.id] if",
"= await self._provider.recv() if responses is not None: for response",
"self._request_queue.get() if task is not None: await self.provider.call_method(task) task.status =",
"self._running = False await self._provider.close() await self._request_queue.put(None) async def request_loop(self):",
"self.provider.is_connected(): raise ConnectionError(f'Connection lost. {self._provider}') task = AsyncTask().create(self._method, *args, **kwargs)",
"aiorpcgrid.client import Client from aiorpcgrid.task import AsyncTask, State class AsyncClient:",
"responses is not None: for response in responses: if response.id",
"*args, **kwargs): if not self.provider.is_connected(): raise ConnectionError(f'Connection lost. {self._provider}') task",
"self._requests: task = self._requests[response.id] task.result = response.result task.error = response.error",
"response.id in self._requests: task = self._requests[response.id] task.result = response.result task.error",
"{self._provider}') task = AsyncTask().create(self._method, *args, **kwargs) if 'parallel' in kwargs:",
"= State.RUNNING if self._request_queue.empty(): self._request_queue.task_done() async def run(self): while self._running:",
"= {} _running = True _request_queue: asyncio.Queue = asyncio.Queue() _loop",
"is None: loop = asyncio.get_event_loop() self._loop = loop async def",
"not None: await self.provider.call_method(task) task.status = State.RUNNING if self._request_queue.empty(): self._request_queue.task_done()",
"= await self._request_queue.get() if task is not None: await self.provider.call_method(task)",
"= loop async def open(self): await self._provider.open() asyncio.ensure_future(self.request_loop(), loop=self._loop) asyncio.ensure_future(self.run(),",
"asyncio.ensure_future( task.callback(task), loop=self._loop ) def __call__(self, *args, **kwargs): if not",
"async def request_loop(self): while self._running: task = await self._request_queue.get() if",
"None: for response in responses: if response.id in self._requests: task",
"_method = None _requests: dict = {} _running = True",
"import asyncio # from aiorpcgrid.client import Client from aiorpcgrid.task import",
"None _method = None _requests: dict = {} _running =",
"None: self._requests[ response.id ].status = State.COMPLETED else: self._requests[response.id].status = State.FAILED",
"self._running: task = await self._request_queue.get() if task is not None:",
"if task._callback is not None: asyncio.ensure_future( task.callback(task), loop=self._loop ) def",
"= self._requests[response.id] task.result = response.result task.error = response.error if task.error",
"def run(self): while self._running: responses = await self._provider.recv() if responses",
"is None: self._requests[ response.id ].status = State.COMPLETED else: self._requests[response.id].status =",
"_requests: dict = {} _running = True _request_queue: asyncio.Queue =",
"None _requests: dict = {} _running = True _request_queue: asyncio.Queue",
"request_loop(self): while self._running: task = await self._request_queue.get() if task is",
"task._parallel = kwargs['parallel'] self._method = None task.status = State.PENDING self._requests[task.id]",
"loop = asyncio.get_event_loop() self._loop = loop async def open(self): await",
"await self.provider.call_method(task) task.status = State.RUNNING if self._request_queue.empty(): self._request_queue.task_done() async def",
"async def open(self): await self._provider.open() asyncio.ensure_future(self.request_loop(), loop=self._loop) asyncio.ensure_future(self.run(), loop=self._loop) return",
"None def __init__(self, provider, loop=None): self._provider = provider if loop",
"State.COMPLETED else: self._requests[response.id].status = State.FAILED task.event.set() del self._requests[response.id] if task._callback",
"else: self._requests[response.id].status = State.FAILED task.event.set() del self._requests[response.id] if task._callback is",
"None: await self.provider.call_method(task) task.status = State.RUNNING if self._request_queue.empty(): self._request_queue.task_done() async",
"self._provider.close() await self._request_queue.put(None) async def request_loop(self): while self._running: task =",
"while self._running: task = await self._request_queue.get() if task is not",
"self._request_queue.empty(): self._request_queue.task_done() async def run(self): while self._running: responses = await",
") def __call__(self, *args, **kwargs): if not self.provider.is_connected(): raise ConnectionError(f'Connection",
"raise ConnectionError(f'Connection lost. {self._provider}') task = AsyncTask().create(self._method, *args, **kwargs) if",
"run(self): while self._running: responses = await self._provider.recv() if responses is",
"= kwargs['parallel'] self._method = None task.status = State.PENDING self._requests[task.id] =",
"asyncio.get_event_loop() self._loop = loop async def open(self): await self._provider.open() asyncio.ensure_future(self.request_loop(),",
"lost. {self._provider}') task = AsyncTask().create(self._method, *args, **kwargs) if 'parallel' in",
"loop=self._loop ) def __call__(self, *args, **kwargs): if not self.provider.is_connected(): raise",
"asyncio # from aiorpcgrid.client import Client from aiorpcgrid.task import AsyncTask,",
"if loop is None: loop = asyncio.get_event_loop() self._loop = loop",
"'parallel' in kwargs: task._parallel = kwargs['parallel'] self._method = None task.status",
"is not None: for response in responses: if response.id in",
"response.id ].status = State.COMPLETED else: self._requests[response.id].status = State.FAILED task.event.set() del",
"await self._provider.open() asyncio.ensure_future(self.request_loop(), loop=self._loop) asyncio.ensure_future(self.run(), loop=self._loop) return self async def",
"response.error if task.error is None: self._requests[ response.id ].status = State.COMPLETED",
"*args, **kwargs) if 'parallel' in kwargs: task._parallel = kwargs['parallel'] self._method",
"AsyncTask().create(self._method, *args, **kwargs) if 'parallel' in kwargs: task._parallel = kwargs['parallel']",
"__init__(self, provider, loop=None): self._provider = provider if loop is None:",
"AsyncTask, State class AsyncClient: _provider = None _method = None",
"_running = True _request_queue: asyncio.Queue = asyncio.Queue() _loop = None",
"= None _requests: dict = {} _running = True _request_queue:",
"if task is not None: await self.provider.call_method(task) task.status = State.RUNNING",
"= State.FAILED task.event.set() del self._requests[response.id] if task._callback is not None:",
"del self._requests[response.id] if task._callback is not None: asyncio.ensure_future( task.callback(task), loop=self._loop",
"= AsyncTask().create(self._method, *args, **kwargs) if 'parallel' in kwargs: task._parallel =",
"await self._provider.recv() if responses is not None: for response in",
"await self._request_queue.get() if task is not None: await self.provider.call_method(task) task.status",
"kwargs['parallel'] self._method = None task.status = State.PENDING self._requests[task.id] = task",
"task is not None: await self.provider.call_method(task) task.status = State.RUNNING if",
"**kwargs) if 'parallel' in kwargs: task._parallel = kwargs['parallel'] self._method =",
"return self async def close(self): self._running = False await self._provider.close()",
"task.status = State.RUNNING if self._request_queue.empty(): self._request_queue.task_done() async def run(self): while",
"_loop = None def __init__(self, provider, loop=None): self._provider = provider",
"= None def __init__(self, provider, loop=None): self._provider = provider if",
"= response.error if task.error is None: self._requests[ response.id ].status =",
"asyncio.Queue() _loop = None def __init__(self, provider, loop=None): self._provider =",
"def close(self): self._running = False await self._provider.close() await self._request_queue.put(None) async",
"def open(self): await self._provider.open() asyncio.ensure_future(self.request_loop(), loop=self._loop) asyncio.ensure_future(self.run(), loop=self._loop) return self",
"**kwargs): if not self.provider.is_connected(): raise ConnectionError(f'Connection lost. {self._provider}') task =",
"task.error = response.error if task.error is None: self._requests[ response.id ].status",
"self._provider.recv() if responses is not None: for response in responses:",
"import AsyncTask, State class AsyncClient: _provider = None _method =",
"for response in responses: if response.id in self._requests: task =",
"while self._running: responses = await self._provider.recv() if responses is not",
"async def run(self): while self._running: responses = await self._provider.recv() if",
"async def close(self): self._running = False await self._provider.close() await self._request_queue.put(None)",
"= True _request_queue: asyncio.Queue = asyncio.Queue() _loop = None def",
"asyncio.ensure_future(self.run(), loop=self._loop) return self async def close(self): self._running = False",
"response in responses: if response.id in self._requests: task = self._requests[response.id]",
"self._provider.open() asyncio.ensure_future(self.request_loop(), loop=self._loop) asyncio.ensure_future(self.run(), loop=self._loop) return self async def close(self):",
"self._requests[response.id].status = State.FAILED task.event.set() del self._requests[response.id] if task._callback is not",
"task = AsyncTask().create(self._method, *args, **kwargs) if 'parallel' in kwargs: task._parallel",
"loop=self._loop) return self async def close(self): self._running = False await",
"= asyncio.Queue() _loop = None def __init__(self, provider, loop=None): self._provider",
"= False await self._provider.close() await self._request_queue.put(None) async def request_loop(self): while",
"response.result task.error = response.error if task.error is None: self._requests[ response.id",
"None: asyncio.ensure_future( task.callback(task), loop=self._loop ) def __call__(self, *args, **kwargs): if",
"True _request_queue: asyncio.Queue = asyncio.Queue() _loop = None def __init__(self,",
"State class AsyncClient: _provider = None _method = None _requests:",
"task = self._requests[response.id] task.result = response.result task.error = response.error if",
"self async def close(self): self._running = False await self._provider.close() await",
"= response.result task.error = response.error if task.error is None: self._requests[",
"_request_queue: asyncio.Queue = asyncio.Queue() _loop = None def __init__(self, provider,",
"kwargs: task._parallel = kwargs['parallel'] self._method = None task.status = State.PENDING",
"responses = await self._provider.recv() if responses is not None: for",
"import Client from aiorpcgrid.task import AsyncTask, State class AsyncClient: _provider",
"if self._request_queue.empty(): self._request_queue.task_done() async def run(self): while self._running: responses =",
"= None task.status = State.PENDING self._requests[task.id] = task self._request_queue.put_nowait(self._requests[task.id]) return",
"in responses: if response.id in self._requests: task = self._requests[response.id] task.result",
"provider if loop is None: loop = asyncio.get_event_loop() self._loop =",
"].status = State.COMPLETED else: self._requests[response.id].status = State.FAILED task.event.set() del self._requests[response.id]",
"loop=None): self._provider = provider if loop is None: loop =",
"False await self._provider.close() await self._request_queue.put(None) async def request_loop(self): while self._running:",
"self._loop = loop async def open(self): await self._provider.open() asyncio.ensure_future(self.request_loop(), loop=self._loop)",
"from aiorpcgrid.client import Client from aiorpcgrid.task import AsyncTask, State class"
] |
[
"2.0 (the \"License\"); # you may not use this file",
"https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import boto3 from opentelemetry.instrumentation.aws_lambda import ( AwsLambdaInstrumentor ) #",
"wrap_function_wrapper( self._wrapped_module_name, self._wrapped_function_name, self._functionPatch, ) def _uninstrument(self, **kwargs): unwrap( import_module(self._wrapped_module_name),",
"import os from importlib import import_module from wrapt import wrap_function_wrapper",
"args[1] ctx_aws_request_id = lambda_context.aws_request_id ctx_invoked_function_arn = lambda_context.invoked_function_arn orig_handler = os.environ.get(\"ORIG_HANDLER\",",
"aws propagator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( AwsXRayFormat, ) from opentelemetry.instrumentation.aws_lambda.version",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"# Copy this snippet into AWS Lambda function # Ref",
"original_func(*args, **kwargs) # force_flush before function quit in case of",
"function_version = os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\") propagator = AwsXRayFormat() parent_context = propagator.extract({\"X-Amzn-Trace-Id\": xray_trace_id})",
"kwargs): lambda_context = args[1] ctx_aws_request_id = lambda_context.aws_request_id ctx_invoked_function_arn = lambda_context.invoked_function_arn",
"unwrap from opentelemetry.trace import SpanKind, get_tracer, get_tracer_provider logger = logging.getLogger(__name__)",
"AwsLambdaInstrumentor ) # Enable instrumentation AwsLambdaInstrumentor().instrument() # Lambda function def",
"__version__, kwargs.get(\"tracer_provider\")) self._tracer_provider = get_tracer_provider() lambda_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) wrapped_names",
"span.set_attribute(\"faas.execution\", ctx_aws_request_id) span.set_attribute(\"faas.id\", ctx_invoked_function_arn) # TODO: fix in Collector because",
") as span: # Refer: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example span.set_attribute(\"faas.execution\", ctx_aws_request_id) span.set_attribute(\"faas.id\", ctx_invoked_function_arn)",
") # Enable instrumentation AwsLambdaInstrumentor().instrument() # Lambda function def lambda_handler(event,",
"use this file except in compliance with the License. #",
"AwsXRayFormat() parent_context = propagator.extract({\"X-Amzn-Trace-Id\": xray_trace_id}) with self._tracer.start_as_current_span( name=orig_handler, context=parent_context, kind=SpanKind.SERVER",
"API --- \"\"\" import logging import os from importlib import",
"from wrapt import wrap_function_wrapper # TODO: aws propagator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"License. # You may obtain a copy of the License",
"import unwrap from opentelemetry.trace import SpanKind, get_tracer, get_tracer_provider logger =",
"self._tracer.start_as_current_span( name=orig_handler, context=parent_context, kind=SpanKind.SERVER ) as span: # Refer: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example",
"BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from opentelemetry.trace import SpanKind, get_tracer,",
"limitations under the License. # TODO: usage \"\"\" The opentelemetry-instrumentation-aws-lambda",
"Usage ----- .. code:: python # Copy this snippet into",
"under the License is distributed on an \"AS IS\" BASIS,",
"License for the specific language governing permissions and # limitations",
"print(bucket.name) return \"200 OK\" API --- \"\"\" import logging import",
"resource attrubutes span.set_attribute(\"faas.name\", lambda_name) span.set_attribute(\"faas.version\", function_version) result = original_func(*args, **kwargs)",
"boto3 from opentelemetry.instrumentation.aws_lambda import ( AwsLambdaInstrumentor ) # Enable instrumentation",
"\"\"\" The opentelemetry-instrumentation-aws-lambda package allows tracing AWS Lambda function. Usage",
"before function quit in case of Lambda freeze. self._tracer_provider.force_flush() return",
"import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap",
"propagator.extract({\"X-Amzn-Trace-Id\": xray_trace_id}) with self._tracer.start_as_current_span( name=orig_handler, context=parent_context, kind=SpanKind.SERVER ) as span:",
"from importlib import import_module from wrapt import wrap_function_wrapper # TODO:",
"orig_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) # TODO: enable propagate from AWS",
"def _instrument(self, **kwargs): self._tracer = get_tracer(__name__, __version__, kwargs.get(\"tracer_provider\")) self._tracer_provider =",
"in compliance with the License. # You may obtain a",
"TODO: fix in Collector because they belong resource attrubutes span.set_attribute(\"faas.name\",",
"software # distributed under the License is distributed on an",
"self._wrapped_function_name, ) def _functionPatch(self, original_func, instance, args, kwargs): lambda_context =",
"__version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from",
"\"200 OK\" API --- \"\"\" import logging import os from",
"= get_tracer_provider() lambda_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) wrapped_names = lambda_handler.rsplit(\".\", 1)",
"# TODO: fix in Collector because they belong resource attrubutes",
"TODO: aws propagator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( AwsXRayFormat, ) from",
"Ref Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import boto3 from opentelemetry.instrumentation.aws_lambda import ( AwsLambdaInstrumentor",
"class AwsLambdaInstrumentor(BaseInstrumentor): def _instrument(self, **kwargs): self._tracer = get_tracer(__name__, __version__, kwargs.get(\"tracer_provider\"))",
"propagate from AWS by env variable xray_trace_id = os.environ.get(\"_X_AMZN_TRACE_ID\", \"\")",
"License. # TODO: usage \"\"\" The opentelemetry-instrumentation-aws-lambda package allows tracing",
"name=orig_handler, context=parent_context, kind=SpanKind.SERVER ) as span: # Refer: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example span.set_attribute(\"faas.execution\",",
"context=parent_context, kind=SpanKind.SERVER ) as span: # Refer: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example span.set_attribute(\"faas.execution\", ctx_aws_request_id)",
"kind=SpanKind.SERVER ) as span: # Refer: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example span.set_attribute(\"faas.execution\", ctx_aws_request_id) span.set_attribute(\"faas.id\",",
"ctx_invoked_function_arn = lambda_context.invoked_function_arn orig_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) # TODO: enable",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"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",
"function # Ref Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import boto3 from opentelemetry.instrumentation.aws_lambda import",
"to in writing, software # distributed under the License is",
"wrapt import wrap_function_wrapper # TODO: aws propagator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import",
".. code:: python # Copy this snippet into AWS Lambda",
"# See the License for the specific language governing permissions",
"self._wrapped_module_name = wrapped_names[0] self._wrapped_function_name = wrapped_names[1] wrap_function_wrapper( self._wrapped_module_name, self._wrapped_function_name, self._functionPatch,",
"instance, args, kwargs): lambda_context = args[1] ctx_aws_request_id = lambda_context.aws_request_id ctx_invoked_function_arn",
"lambda_context.invoked_function_arn orig_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) # TODO: enable propagate from",
"language governing permissions and # limitations under the License. #",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"= wrapped_names[0] self._wrapped_function_name = wrapped_names[1] wrap_function_wrapper( self._wrapped_module_name, self._wrapped_function_name, self._functionPatch, )",
"_uninstrument(self, **kwargs): unwrap( import_module(self._wrapped_module_name), self._wrapped_function_name, ) def _functionPatch(self, original_func, instance,",
"with the License. # You may obtain a copy of",
"**kwargs): self._tracer = get_tracer(__name__, __version__, kwargs.get(\"tracer_provider\")) self._tracer_provider = get_tracer_provider() lambda_handler",
"OK\" API --- \"\"\" import logging import os from importlib",
"unwrap( import_module(self._wrapped_module_name), self._wrapped_function_name, ) def _functionPatch(self, original_func, instance, args, kwargs):",
"= args[1] ctx_aws_request_id = lambda_context.aws_request_id ctx_invoked_function_arn = lambda_context.invoked_function_arn orig_handler =",
"compliance with the License. # You may obtain a copy",
"agreed to in writing, software # distributed under the License",
"in s3.buckets.all(): print(bucket.name) return \"200 OK\" API --- \"\"\" import",
"logging.getLogger(__name__) class AwsLambdaInstrumentor(BaseInstrumentor): def _instrument(self, **kwargs): self._tracer = get_tracer(__name__, __version__,",
"belong resource attrubutes span.set_attribute(\"faas.name\", lambda_name) span.set_attribute(\"faas.version\", function_version) result = original_func(*args,",
"distributed under the License is distributed on an \"AS IS\"",
"import_module(self._wrapped_module_name), self._wrapped_function_name, ) def _functionPatch(self, original_func, instance, args, kwargs): lambda_context",
"Lambda function. Usage ----- .. code:: python # Copy this",
"express or implied. # See the License for the specific",
"tracing AWS Lambda function. Usage ----- .. code:: python #",
"except in compliance with the License. # You may obtain",
"enable propagate from AWS by env variable xray_trace_id = os.environ.get(\"_X_AMZN_TRACE_ID\",",
"AwsLambdaInstrumentor(BaseInstrumentor): def _instrument(self, **kwargs): self._tracer = get_tracer(__name__, __version__, kwargs.get(\"tracer_provider\")) self._tracer_provider",
"get_tracer_provider() lambda_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) wrapped_names = lambda_handler.rsplit(\".\", 1) self._wrapped_module_name",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"= lambda_context.invoked_function_arn orig_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) # TODO: enable propagate",
"Authors # # Licensed under the Apache License, Version 2.0",
"not use this file except in compliance with the License.",
"ctx_invoked_function_arn) # TODO: fix in Collector because they belong resource",
"writing, software # distributed under the License is distributed on",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"# Refer: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example span.set_attribute(\"faas.execution\", ctx_aws_request_id) span.set_attribute(\"faas.id\", ctx_invoked_function_arn) # TODO: fix",
"TODO: usage \"\"\" The opentelemetry-instrumentation-aws-lambda package allows tracing AWS Lambda",
"# Enable instrumentation AwsLambdaInstrumentor().instrument() # Lambda function def lambda_handler(event, context):",
"lambda_context = args[1] ctx_aws_request_id = lambda_context.aws_request_id ctx_invoked_function_arn = lambda_context.invoked_function_arn orig_handler",
"opentelemetry-instrumentation-aws-lambda package allows tracing AWS Lambda function. Usage ----- ..",
"_functionPatch(self, original_func, instance, args, kwargs): lambda_context = args[1] ctx_aws_request_id =",
"lambda_handler(event, context): s3 = boto3.resource('s3') for bucket in s3.buckets.all(): print(bucket.name)",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"propagator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( AwsXRayFormat, ) from opentelemetry.instrumentation.aws_lambda.version import",
"opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from opentelemetry.trace import",
"the License. # TODO: usage \"\"\" The opentelemetry-instrumentation-aws-lambda package allows",
"lambda_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) wrapped_names = lambda_handler.rsplit(\".\", 1) self._wrapped_module_name =",
"function_version) result = original_func(*args, **kwargs) # force_flush before function quit",
"opentelemetry.trace import SpanKind, get_tracer, get_tracer_provider logger = logging.getLogger(__name__) class AwsLambdaInstrumentor(BaseInstrumentor):",
"os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) # TODO: enable propagate from AWS by env",
"because they belong resource attrubutes span.set_attribute(\"faas.name\", lambda_name) span.set_attribute(\"faas.version\", function_version) result",
"# Ref Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import boto3 from opentelemetry.instrumentation.aws_lambda import (",
"in Collector because they belong resource attrubutes span.set_attribute(\"faas.name\", lambda_name) span.set_attribute(\"faas.version\",",
"def _functionPatch(self, original_func, instance, args, kwargs): lambda_context = args[1] ctx_aws_request_id",
"--- \"\"\" import logging import os from importlib import import_module",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"boto3.resource('s3') for bucket in s3.buckets.all(): print(bucket.name) return \"200 OK\" API",
"os.environ.get(\"_HANDLER\")) wrapped_names = lambda_handler.rsplit(\".\", 1) self._wrapped_module_name = wrapped_names[0] self._wrapped_function_name =",
"import wrap_function_wrapper # TODO: aws propagator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import (",
"the License is distributed on an \"AS IS\" BASIS, #",
"= logging.getLogger(__name__) class AwsLambdaInstrumentor(BaseInstrumentor): def _instrument(self, **kwargs): self._tracer = get_tracer(__name__,",
"from opentelemetry.instrumentation.aws_lambda import ( AwsLambdaInstrumentor ) # Enable instrumentation AwsLambdaInstrumentor().instrument()",
"= os.environ.get(\"_X_AMZN_TRACE_ID\", \"\") lambda_name = os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\") function_version = os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\") propagator",
"self._wrapped_function_name = wrapped_names[1] wrap_function_wrapper( self._wrapped_module_name, self._wrapped_function_name, self._functionPatch, ) def _uninstrument(self,",
"they belong resource attrubutes span.set_attribute(\"faas.name\", lambda_name) span.set_attribute(\"faas.version\", function_version) result =",
"def lambda_handler(event, context): s3 = boto3.resource('s3') for bucket in s3.buckets.all():",
"law or agreed to in writing, software # distributed under",
"os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) wrapped_names = lambda_handler.rsplit(\".\", 1) self._wrapped_module_name = wrapped_names[0] self._wrapped_function_name",
"= lambda_context.aws_request_id ctx_invoked_function_arn = lambda_context.invoked_function_arn orig_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) #",
"get_tracer_provider logger = logging.getLogger(__name__) class AwsLambdaInstrumentor(BaseInstrumentor): def _instrument(self, **kwargs): self._tracer",
"attrubutes span.set_attribute(\"faas.name\", lambda_name) span.set_attribute(\"faas.version\", function_version) result = original_func(*args, **kwargs) #",
"snippet into AWS Lambda function # Ref Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import",
"import SpanKind, get_tracer, get_tracer_provider logger = logging.getLogger(__name__) class AwsLambdaInstrumentor(BaseInstrumentor): def",
"get_tracer, get_tracer_provider logger = logging.getLogger(__name__) class AwsLambdaInstrumentor(BaseInstrumentor): def _instrument(self, **kwargs):",
"xray_trace_id}) with self._tracer.start_as_current_span( name=orig_handler, context=parent_context, kind=SpanKind.SERVER ) as span: #",
"for bucket in s3.buckets.all(): print(bucket.name) return \"200 OK\" API ---",
"may obtain a copy of the License at # #",
"and # limitations under the License. # TODO: usage \"\"\"",
"= os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\") propagator = AwsXRayFormat() parent_context = propagator.extract({\"X-Amzn-Trace-Id\": xray_trace_id}) with",
"The opentelemetry-instrumentation-aws-lambda package allows tracing AWS Lambda function. Usage -----",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( AwsXRayFormat, ) from opentelemetry.instrumentation.aws_lambda.version import __version__ from",
"xray_trace_id = os.environ.get(\"_X_AMZN_TRACE_ID\", \"\") lambda_name = os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\") function_version = os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\")",
"may not use this file except in compliance with the",
"os.environ.get(\"_HANDLER\")) # TODO: enable propagate from AWS by env variable",
"= get_tracer(__name__, __version__, kwargs.get(\"tracer_provider\")) self._tracer_provider = get_tracer_provider() lambda_handler = os.environ.get(\"ORIG_HANDLER\",",
"import ( AwsXRayFormat, ) from opentelemetry.instrumentation.aws_lambda.version import __version__ from opentelemetry.instrumentation.instrumentor",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"wrapped_names[0] self._wrapped_function_name = wrapped_names[1] wrap_function_wrapper( self._wrapped_module_name, self._wrapped_function_name, self._functionPatch, ) def",
"# TODO: aws propagator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( AwsXRayFormat, )",
"this file except in compliance with the License. # You",
"# limitations under the License. # TODO: usage \"\"\" The",
"AwsLambdaInstrumentor().instrument() # Lambda function def lambda_handler(event, context): s3 = boto3.resource('s3')",
"Copyright 2020, OpenTelemetry Authors # # Licensed under the Apache",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"context): s3 = boto3.resource('s3') for bucket in s3.buckets.all(): print(bucket.name) return",
"# # Licensed under the Apache License, Version 2.0 (the",
"AWS by env variable xray_trace_id = os.environ.get(\"_X_AMZN_TRACE_ID\", \"\") lambda_name =",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"wrapped_names[1] wrap_function_wrapper( self._wrapped_module_name, self._wrapped_function_name, self._functionPatch, ) def _uninstrument(self, **kwargs): unwrap(",
"importlib import import_module from wrapt import wrap_function_wrapper # TODO: aws",
"get_tracer(__name__, __version__, kwargs.get(\"tracer_provider\")) self._tracer_provider = get_tracer_provider() lambda_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\"))",
"force_flush before function quit in case of Lambda freeze. self._tracer_provider.force_flush()",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"# TODO: usage \"\"\" The opentelemetry-instrumentation-aws-lambda package allows tracing AWS",
"args, kwargs): lambda_context = args[1] ctx_aws_request_id = lambda_context.aws_request_id ctx_invoked_function_arn =",
"= os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) wrapped_names = lambda_handler.rsplit(\".\", 1) self._wrapped_module_name = wrapped_names[0]",
"# TODO: enable propagate from AWS by env variable xray_trace_id",
"package allows tracing AWS Lambda function. Usage ----- .. code::",
"opentelemetry.instrumentation.aws_lambda.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import",
"self._functionPatch, ) def _uninstrument(self, **kwargs): unwrap( import_module(self._wrapped_module_name), self._wrapped_function_name, ) def",
"----- .. code:: python # Copy this snippet into AWS",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example span.set_attribute(\"faas.execution\", ctx_aws_request_id) span.set_attribute(\"faas.id\", ctx_invoked_function_arn) # TODO: fix in Collector",
") def _uninstrument(self, **kwargs): unwrap( import_module(self._wrapped_module_name), self._wrapped_function_name, ) def _functionPatch(self,",
"ctx_aws_request_id = lambda_context.aws_request_id ctx_invoked_function_arn = lambda_context.invoked_function_arn orig_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\"))",
"or implied. # See the License for the specific language",
"TODO: enable propagate from AWS by env variable xray_trace_id =",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"function. Usage ----- .. code:: python # Copy this snippet",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"os.environ.get(\"_X_AMZN_TRACE_ID\", \"\") lambda_name = os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\") function_version = os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\") propagator =",
"( AwsXRayFormat, ) from opentelemetry.instrumentation.aws_lambda.version import __version__ from opentelemetry.instrumentation.instrumentor import",
"= wrapped_names[1] wrap_function_wrapper( self._wrapped_module_name, self._wrapped_function_name, self._functionPatch, ) def _uninstrument(self, **kwargs):",
"AwsXRayFormat, ) from opentelemetry.instrumentation.aws_lambda.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor",
"os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\") function_version = os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\") propagator = AwsXRayFormat() parent_context = propagator.extract({\"X-Amzn-Trace-Id\":",
"propagator = AwsXRayFormat() parent_context = propagator.extract({\"X-Amzn-Trace-Id\": xray_trace_id}) with self._tracer.start_as_current_span( name=orig_handler,",
"self._wrapped_module_name, self._wrapped_function_name, self._functionPatch, ) def _uninstrument(self, **kwargs): unwrap( import_module(self._wrapped_module_name), self._wrapped_function_name,",
"Lambda function def lambda_handler(event, context): s3 = boto3.resource('s3') for bucket",
"(the \"License\"); # you may not use this file except",
"# you may not use this file except in compliance",
"return \"200 OK\" API --- \"\"\" import logging import os",
"# Copyright 2020, OpenTelemetry Authors # # Licensed under the",
"logging import os from importlib import import_module from wrapt import",
"Collector because they belong resource attrubutes span.set_attribute(\"faas.name\", lambda_name) span.set_attribute(\"faas.version\", function_version)",
"wrapped_names = lambda_handler.rsplit(\".\", 1) self._wrapped_module_name = wrapped_names[0] self._wrapped_function_name = wrapped_names[1]",
"Lambda function # Ref Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import boto3 from opentelemetry.instrumentation.aws_lambda",
"\"\"\" import logging import os from importlib import import_module from",
"under the License. # TODO: usage \"\"\" The opentelemetry-instrumentation-aws-lambda package",
"instrumentation AwsLambdaInstrumentor().instrument() # Lambda function def lambda_handler(event, context): s3 =",
"= lambda_handler.rsplit(\".\", 1) self._wrapped_module_name = wrapped_names[0] self._wrapped_function_name = wrapped_names[1] wrap_function_wrapper(",
"# # Unless required by applicable law or agreed to",
"allows tracing AWS Lambda function. Usage ----- .. code:: python",
"Refer: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example span.set_attribute(\"faas.execution\", ctx_aws_request_id) span.set_attribute(\"faas.id\", ctx_invoked_function_arn) # TODO: fix in",
"function quit in case of Lambda freeze. self._tracer_provider.force_flush() return result",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"**kwargs) # force_flush before function quit in case of Lambda",
"import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from opentelemetry.trace import SpanKind,",
"Version 2.0 (the \"License\"); # you may not use this",
"code:: python # Copy this snippet into AWS Lambda function",
"from opentelemetry.trace import SpanKind, get_tracer, get_tracer_provider logger = logging.getLogger(__name__) class",
"_instrument(self, **kwargs): self._tracer = get_tracer(__name__, __version__, kwargs.get(\"tracer_provider\")) self._tracer_provider = get_tracer_provider()",
"opentelemetry.instrumentation.utils import unwrap from opentelemetry.trace import SpanKind, get_tracer, get_tracer_provider logger",
"implied. # See the License for the specific language governing",
"AWS Lambda function. Usage ----- .. code:: python # Copy",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"by applicable law or agreed to in writing, software #",
"Enable instrumentation AwsLambdaInstrumentor().instrument() # Lambda function def lambda_handler(event, context): s3",
"from opentelemetry.instrumentation.aws_lambda.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils",
"self._tracer = get_tracer(__name__, __version__, kwargs.get(\"tracer_provider\")) self._tracer_provider = get_tracer_provider() lambda_handler =",
"opentelemetry.instrumentation.aws_lambda import ( AwsLambdaInstrumentor ) # Enable instrumentation AwsLambdaInstrumentor().instrument() #",
"s3.buckets.all(): print(bucket.name) return \"200 OK\" API --- \"\"\" import logging",
"lambda_name) span.set_attribute(\"faas.version\", function_version) result = original_func(*args, **kwargs) # force_flush before",
"# Lambda function def lambda_handler(event, context): s3 = boto3.resource('s3') for",
"Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import boto3 from opentelemetry.instrumentation.aws_lambda import ( AwsLambdaInstrumentor )",
"lambda_name = os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\") function_version = os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\") propagator = AwsXRayFormat() parent_context",
"python # Copy this snippet into AWS Lambda function #",
"( AwsLambdaInstrumentor ) # Enable instrumentation AwsLambdaInstrumentor().instrument() # Lambda function",
"= os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\") function_version = os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\") propagator = AwsXRayFormat() parent_context =",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"s3 = boto3.resource('s3') for bucket in s3.buckets.all(): print(bucket.name) return \"200",
"# force_flush before function quit in case of Lambda freeze.",
"Unless required by applicable law or agreed to in writing,",
") def _functionPatch(self, original_func, instance, args, kwargs): lambda_context = args[1]",
"AWS Lambda function # Ref Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import boto3 from",
"the specific language governing permissions and # limitations under the",
"function def lambda_handler(event, context): s3 = boto3.resource('s3') for bucket in",
"fix in Collector because they belong resource attrubutes span.set_attribute(\"faas.name\", lambda_name)",
"2020, OpenTelemetry Authors # # Licensed under the Apache License,",
"applicable law or agreed to in writing, software # distributed",
"in writing, software # distributed under the License is distributed",
"as span: # Refer: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example span.set_attribute(\"faas.execution\", ctx_aws_request_id) span.set_attribute(\"faas.id\", ctx_invoked_function_arn) #",
"= original_func(*args, **kwargs) # force_flush before function quit in case",
"**kwargs): unwrap( import_module(self._wrapped_module_name), self._wrapped_function_name, ) def _functionPatch(self, original_func, instance, args,",
"env variable xray_trace_id = os.environ.get(\"_X_AMZN_TRACE_ID\", \"\") lambda_name = os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\") function_version",
"1) self._wrapped_module_name = wrapped_names[0] self._wrapped_function_name = wrapped_names[1] wrap_function_wrapper( self._wrapped_module_name, self._wrapped_function_name,",
"wrap_function_wrapper # TODO: aws propagator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( AwsXRayFormat,",
"import logging import os from importlib import import_module from wrapt",
"def _uninstrument(self, **kwargs): unwrap( import_module(self._wrapped_module_name), self._wrapped_function_name, ) def _functionPatch(self, original_func,",
"from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from opentelemetry.trace",
"parent_context = propagator.extract({\"X-Amzn-Trace-Id\": xray_trace_id}) with self._tracer.start_as_current_span( name=orig_handler, context=parent_context, kind=SpanKind.SERVER )",
"ctx_aws_request_id) span.set_attribute(\"faas.id\", ctx_invoked_function_arn) # TODO: fix in Collector because they",
"bucket in s3.buckets.all(): print(bucket.name) return \"200 OK\" API --- \"\"\"",
"span.set_attribute(\"faas.name\", lambda_name) span.set_attribute(\"faas.version\", function_version) result = original_func(*args, **kwargs) # force_flush",
"import ( AwsLambdaInstrumentor ) # Enable instrumentation AwsLambdaInstrumentor().instrument() # Lambda",
"os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\") propagator = AwsXRayFormat() parent_context = propagator.extract({\"X-Amzn-Trace-Id\": xray_trace_id}) with self._tracer.start_as_current_span(",
"os from importlib import import_module from wrapt import wrap_function_wrapper #",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"License, Version 2.0 (the \"License\"); # you may not use",
"permissions and # limitations under the License. # TODO: usage",
"# You may obtain a copy of the License at",
"original_func, instance, args, kwargs): lambda_context = args[1] ctx_aws_request_id = lambda_context.aws_request_id",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"= propagator.extract({\"X-Amzn-Trace-Id\": xray_trace_id}) with self._tracer.start_as_current_span( name=orig_handler, context=parent_context, kind=SpanKind.SERVER ) as",
"= AwsXRayFormat() parent_context = propagator.extract({\"X-Amzn-Trace-Id\": xray_trace_id}) with self._tracer.start_as_current_span( name=orig_handler, context=parent_context,",
"\"\") lambda_name = os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\") function_version = os.environ.get(\"AWS_LAMBDA_FUNCTION_VERSION\") propagator = AwsXRayFormat()",
"the License for the specific language governing permissions and #",
"self._wrapped_function_name, self._functionPatch, ) def _uninstrument(self, **kwargs): unwrap( import_module(self._wrapped_module_name), self._wrapped_function_name, )",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"from opentelemetry.instrumentation.utils import unwrap from opentelemetry.trace import SpanKind, get_tracer, get_tracer_provider",
"either express or implied. # See the License for the",
"governing permissions and # limitations under the License. # TODO:",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"span: # Refer: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/faas.md#example span.set_attribute(\"faas.execution\", ctx_aws_request_id) span.set_attribute(\"faas.id\", ctx_invoked_function_arn) # TODO:",
"logger = logging.getLogger(__name__) class AwsLambdaInstrumentor(BaseInstrumentor): def _instrument(self, **kwargs): self._tracer =",
"import import_module from wrapt import wrap_function_wrapper # TODO: aws propagator",
"lambda_handler.rsplit(\".\", 1) self._wrapped_module_name = wrapped_names[0] self._wrapped_function_name = wrapped_names[1] wrap_function_wrapper( self._wrapped_module_name,",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"result = original_func(*args, **kwargs) # force_flush before function quit in",
"span.set_attribute(\"faas.id\", ctx_invoked_function_arn) # TODO: fix in Collector because they belong",
"span.set_attribute(\"faas.version\", function_version) result = original_func(*args, **kwargs) # force_flush before function",
"self._tracer_provider = get_tracer_provider() lambda_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) wrapped_names = lambda_handler.rsplit(\".\",",
"SpanKind, get_tracer, get_tracer_provider logger = logging.getLogger(__name__) class AwsLambdaInstrumentor(BaseInstrumentor): def _instrument(self,",
"with self._tracer.start_as_current_span( name=orig_handler, context=parent_context, kind=SpanKind.SERVER ) as span: # Refer:",
"\"License\"); # you may not use this file except in",
"into AWS Lambda function # Ref Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html import boto3",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
") from opentelemetry.instrumentation.aws_lambda.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from",
"# distributed under the License is distributed on an \"AS",
"= boto3.resource('s3') for bucket in s3.buckets.all(): print(bucket.name) return \"200 OK\"",
"# Unless required by applicable law or agreed to in",
"import boto3 from opentelemetry.instrumentation.aws_lambda import ( AwsLambdaInstrumentor ) # Enable",
"import_module from wrapt import wrap_function_wrapper # TODO: aws propagator from",
"from AWS by env variable xray_trace_id = os.environ.get(\"_X_AMZN_TRACE_ID\", \"\") lambda_name",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"OpenTelemetry Authors # # Licensed under the Apache License, Version",
"from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( AwsXRayFormat, ) from opentelemetry.instrumentation.aws_lambda.version import __version__",
"by env variable xray_trace_id = os.environ.get(\"_X_AMZN_TRACE_ID\", \"\") lambda_name = os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\")",
"You may obtain a copy of the License at #",
"usage \"\"\" The opentelemetry-instrumentation-aws-lambda package allows tracing AWS Lambda function.",
"this snippet into AWS Lambda function # Ref Doc: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html",
"Copy this snippet into AWS Lambda function # Ref Doc:",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"variable xray_trace_id = os.environ.get(\"_X_AMZN_TRACE_ID\", \"\") lambda_name = os.environ.get(\"AWS_LAMBDA_FUNCTION_NAME\") function_version =",
"kwargs.get(\"tracer_provider\")) self._tracer_provider = get_tracer_provider() lambda_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) wrapped_names =",
"= os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) # TODO: enable propagate from AWS by",
"lambda_context.aws_request_id ctx_invoked_function_arn = lambda_context.invoked_function_arn orig_handler = os.environ.get(\"ORIG_HANDLER\", os.environ.get(\"_HANDLER\")) # TODO:"
] |
[
"] operations = [ migrations.AlterField( model_name='user', name='avatar_url', field=models.ImageField(default='profile_pics/einstein_EqBibwO.jpeg', upload_to='profile_pics'), ),",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('instructors',",
"# Generated by Django 4.0.2 on 2022-04-01 16:09 from django.db",
"4.0.2 on 2022-04-01 16:09 from django.db import migrations, models class",
"Migration(migrations.Migration): dependencies = [ ('instructors', '0020_alter_user_description_alter_user_title'), ] operations = [",
"'0020_alter_user_description_alter_user_title'), ] operations = [ migrations.AlterField( model_name='user', name='avatar_url', field=models.ImageField(default='profile_pics/einstein_EqBibwO.jpeg', upload_to='profile_pics'),",
"by Django 4.0.2 on 2022-04-01 16:09 from django.db import migrations,",
"16:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"2022-04-01 16:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"Generated by Django 4.0.2 on 2022-04-01 16:09 from django.db import",
"models class Migration(migrations.Migration): dependencies = [ ('instructors', '0020_alter_user_description_alter_user_title'), ] operations",
"Django 4.0.2 on 2022-04-01 16:09 from django.db import migrations, models",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"= [ ('instructors', '0020_alter_user_description_alter_user_title'), ] operations = [ migrations.AlterField( model_name='user',",
"('instructors', '0020_alter_user_description_alter_user_title'), ] operations = [ migrations.AlterField( model_name='user', name='avatar_url', field=models.ImageField(default='profile_pics/einstein_EqBibwO.jpeg',",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('instructors', '0020_alter_user_description_alter_user_title'), ]",
"operations = [ migrations.AlterField( model_name='user', name='avatar_url', field=models.ImageField(default='profile_pics/einstein_EqBibwO.jpeg', upload_to='profile_pics'), ), ]",
"dependencies = [ ('instructors', '0020_alter_user_description_alter_user_title'), ] operations = [ migrations.AlterField(",
"on 2022-04-01 16:09 from django.db import migrations, models class Migration(migrations.Migration):",
"[ ('instructors', '0020_alter_user_description_alter_user_title'), ] operations = [ migrations.AlterField( model_name='user', name='avatar_url',",
"class Migration(migrations.Migration): dependencies = [ ('instructors', '0020_alter_user_description_alter_user_title'), ] operations =",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('instructors', '0020_alter_user_description_alter_user_title'),"
] |
[
"current value\"\"\" def __init__(self, momentum=0.99): self.momentum = momentum self.reset() def",
"RunningAverageMeter(object): \"\"\"Computes and stores the average and current value\"\"\" def",
"self.avg * self.momentum + val * (1 - self.momentum) self.val",
"self.momentum) self.val = val def load_model(path): (_, state_dict), (_, model_args),",
"self.val is None: self.avg = val else: self.avg = self.avg",
"(_, model_args), (_, slover_id) = torch.load(path, map_location='cpu').items() is_odenet = model_args.network",
"= self.avg * self.momentum + val * (1 - self.momentum)",
"+ val * (1 - self.momentum) self.val = val def",
"= momentum self.reset() def reset(self): self.val = None self.avg =",
"\"\"\"Computes and stores the average and current value\"\"\" def __init__(self,",
"model_args.network == 'odenet' if not hasattr(model_args, 'in_channels'): model_args.in_channels = 1",
"= False class RunningAverageMeter(object): \"\"\"Computes and stores the average and",
"momentum self.reset() def reset(self): self.val = None self.avg = 0",
"self.avg = self.avg * self.momentum + val * (1 -",
"fix_seeds(seed=502): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.set_printoptions(precision=10) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark",
"and stores the average and current value\"\"\" def __init__(self, momentum=0.99):",
"reset(self): self.val = None self.avg = 0 def update(self, val):",
"MetaNODE def fix_seeds(seed=502): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.set_printoptions(precision=10) torch.backends.cudnn.deterministic =",
"None self.avg = 0 def update(self, val): if self.val is",
"import random from .odenet_mnist.layers import MetaNODE def fix_seeds(seed=502): np.random.seed(seed) random.seed(seed)",
"import numpy as np import torch import random from .odenet_mnist.layers",
"torch import random from .odenet_mnist.layers import MetaNODE def fix_seeds(seed=502): np.random.seed(seed)",
"random from .odenet_mnist.layers import MetaNODE def fix_seeds(seed=502): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed)",
"torch.load(path, map_location='cpu').items() is_odenet = model_args.network == 'odenet' if not hasattr(model_args,",
"average and current value\"\"\" def __init__(self, momentum=0.99): self.momentum = momentum",
"value\"\"\" def __init__(self, momentum=0.99): self.momentum = momentum self.reset() def reset(self):",
"torch.backends.cudnn.benchmark = False class RunningAverageMeter(object): \"\"\"Computes and stores the average",
".odenet_mnist.layers import MetaNODE def fix_seeds(seed=502): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.set_printoptions(precision=10)",
"self.reset() def reset(self): self.val = None self.avg = 0 def",
"is None: self.avg = val else: self.avg = self.avg *",
"state_dict), (_, model_args), (_, slover_id) = torch.load(path, map_location='cpu').items() is_odenet =",
"slover_id) = torch.load(path, map_location='cpu').items() is_odenet = model_args.network == 'odenet' if",
"def __init__(self, momentum=0.99): self.momentum = momentum self.reset() def reset(self): self.val",
"= val else: self.avg = self.avg * self.momentum + val",
"= True torch.backends.cudnn.benchmark = False class RunningAverageMeter(object): \"\"\"Computes and stores",
"model_args), (_, slover_id) = torch.load(path, map_location='cpu').items() is_odenet = model_args.network ==",
"= torch.load(path, map_location='cpu').items() is_odenet = model_args.network == 'odenet' if not",
"(1 - self.momentum) self.val = val def load_model(path): (_, state_dict),",
"(_, slover_id) = torch.load(path, map_location='cpu').items() is_odenet = model_args.network == 'odenet'",
"0 def update(self, val): if self.val is None: self.avg =",
"if not hasattr(model_args, 'in_channels'): model_args.in_channels = 1 model = MetaNODE(downsampling_method=model_args.downsampling_method,",
"hasattr(model_args, 'in_channels'): model_args.in_channels = 1 model = MetaNODE(downsampling_method=model_args.downsampling_method, is_odenet=is_odenet, in_channels=model_args.in_channels)",
"None: self.avg = val else: self.avg = self.avg * self.momentum",
"the average and current value\"\"\" def __init__(self, momentum=0.99): self.momentum =",
"1 model = MetaNODE(downsampling_method=model_args.downsampling_method, is_odenet=is_odenet, in_channels=model_args.in_channels) model.load_state_dict(state_dict) return model, model_args",
"map_location='cpu').items() is_odenet = model_args.network == 'odenet' if not hasattr(model_args, 'in_channels'):",
"update(self, val): if self.val is None: self.avg = val else:",
"<filename>sopa/src/models/utils.py import numpy as np import torch import random from",
"is_odenet = model_args.network == 'odenet' if not hasattr(model_args, 'in_channels'): model_args.in_channels",
"else: self.avg = self.avg * self.momentum + val * (1",
"load_model(path): (_, state_dict), (_, model_args), (_, slover_id) = torch.load(path, map_location='cpu').items()",
"stores the average and current value\"\"\" def __init__(self, momentum=0.99): self.momentum",
"np import torch import random from .odenet_mnist.layers import MetaNODE def",
"def fix_seeds(seed=502): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.set_printoptions(precision=10) torch.backends.cudnn.deterministic = True",
"False class RunningAverageMeter(object): \"\"\"Computes and stores the average and current",
"= None self.avg = 0 def update(self, val): if self.val",
"val): if self.val is None: self.avg = val else: self.avg",
"numpy as np import torch import random from .odenet_mnist.layers import",
"def reset(self): self.val = None self.avg = 0 def update(self,",
"'odenet' if not hasattr(model_args, 'in_channels'): model_args.in_channels = 1 model =",
"= 0 def update(self, val): if self.val is None: self.avg",
"True torch.backends.cudnn.benchmark = False class RunningAverageMeter(object): \"\"\"Computes and stores the",
"torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False class RunningAverageMeter(object): \"\"\"Computes and",
"val else: self.avg = self.avg * self.momentum + val *",
"self.avg = val else: self.avg = self.avg * self.momentum +",
"import torch import random from .odenet_mnist.layers import MetaNODE def fix_seeds(seed=502):",
"= model_args.network == 'odenet' if not hasattr(model_args, 'in_channels'): model_args.in_channels =",
"def load_model(path): (_, state_dict), (_, model_args), (_, slover_id) = torch.load(path,",
"* (1 - self.momentum) self.val = val def load_model(path): (_,",
"random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.set_printoptions(precision=10) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False",
"if self.val is None: self.avg = val else: self.avg =",
"self.avg = 0 def update(self, val): if self.val is None:",
"self.momentum + val * (1 - self.momentum) self.val = val",
"and current value\"\"\" def __init__(self, momentum=0.99): self.momentum = momentum self.reset()",
"val * (1 - self.momentum) self.val = val def load_model(path):",
"torch.set_printoptions(precision=10) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False class RunningAverageMeter(object): \"\"\"Computes",
"torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.set_printoptions(precision=10) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False class",
"self.val = val def load_model(path): (_, state_dict), (_, model_args), (_,",
"- self.momentum) self.val = val def load_model(path): (_, state_dict), (_,",
"import MetaNODE def fix_seeds(seed=502): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.set_printoptions(precision=10) torch.backends.cudnn.deterministic",
"* self.momentum + val * (1 - self.momentum) self.val =",
"class RunningAverageMeter(object): \"\"\"Computes and stores the average and current value\"\"\"",
"'in_channels'): model_args.in_channels = 1 model = MetaNODE(downsampling_method=model_args.downsampling_method, is_odenet=is_odenet, in_channels=model_args.in_channels) model.load_state_dict(state_dict)",
"torch.cuda.manual_seed_all(seed) torch.set_printoptions(precision=10) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False class RunningAverageMeter(object):",
"as np import torch import random from .odenet_mnist.layers import MetaNODE",
"== 'odenet' if not hasattr(model_args, 'in_channels'): model_args.in_channels = 1 model",
"(_, state_dict), (_, model_args), (_, slover_id) = torch.load(path, map_location='cpu').items() is_odenet",
"val def load_model(path): (_, state_dict), (_, model_args), (_, slover_id) =",
"not hasattr(model_args, 'in_channels'): model_args.in_channels = 1 model = MetaNODE(downsampling_method=model_args.downsampling_method, is_odenet=is_odenet,",
"momentum=0.99): self.momentum = momentum self.reset() def reset(self): self.val = None",
"self.momentum = momentum self.reset() def reset(self): self.val = None self.avg",
"self.val = None self.avg = 0 def update(self, val): if",
"from .odenet_mnist.layers import MetaNODE def fix_seeds(seed=502): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)",
"__init__(self, momentum=0.99): self.momentum = momentum self.reset() def reset(self): self.val =",
"= 1 model = MetaNODE(downsampling_method=model_args.downsampling_method, is_odenet=is_odenet, in_channels=model_args.in_channels) model.load_state_dict(state_dict) return model,",
"np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.set_printoptions(precision=10) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark =",
"model_args.in_channels = 1 model = MetaNODE(downsampling_method=model_args.downsampling_method, is_odenet=is_odenet, in_channels=model_args.in_channels) model.load_state_dict(state_dict) return",
"= val def load_model(path): (_, state_dict), (_, model_args), (_, slover_id)",
"def update(self, val): if self.val is None: self.avg = val"
] |
[
"on esp32 1.10.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10",
"pass def b2a_base64(): pass def crc32(): pass def hexlify(): pass",
"def b2a_base64(): pass def crc32(): pass def hexlify(): pass def",
"with ESP32') # Stubber: 1.2.0 def a2b_base64(): pass def b2a_base64():",
"MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module with",
"Stubber: 1.2.0 def a2b_base64(): pass def b2a_base64(): pass def crc32():",
"1.2.0 def a2b_base64(): pass def b2a_base64(): pass def crc32(): pass",
"pass def crc32(): pass def hexlify(): pass def unhexlify(): pass",
"1.10.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25',",
"machine='ESP32 module with ESP32') # Stubber: 1.2.0 def a2b_base64(): pass",
"version='v1.10 on 2019-01-25', machine='ESP32 module with ESP32') # Stubber: 1.2.0",
"'ubinascii' on esp32 1.10.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.10.0',",
"on 2019-01-25', machine='ESP32 module with ESP32') # Stubber: 1.2.0 def",
"esp32 1.10.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on",
"(sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module with ESP32')",
"<filename>packages/micropython-official/v1.10/esp32/stubs/ubinascii.py \"\"\" Module: 'ubinascii' on esp32 1.10.0 \"\"\" # MCU:",
"b2a_base64(): pass def crc32(): pass def hexlify(): pass def unhexlify():",
"release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module with ESP32') # Stubber:",
"# MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module",
"\"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32",
"def a2b_base64(): pass def b2a_base64(): pass def crc32(): pass def",
"2019-01-25', machine='ESP32 module with ESP32') # Stubber: 1.2.0 def a2b_base64():",
"a2b_base64(): pass def b2a_base64(): pass def crc32(): pass def hexlify():",
"\"\"\" Module: 'ubinascii' on esp32 1.10.0 \"\"\" # MCU: (sysname='esp32',",
"ESP32') # Stubber: 1.2.0 def a2b_base64(): pass def b2a_base64(): pass",
"nodename='esp32', release='1.10.0', version='v1.10 on 2019-01-25', machine='ESP32 module with ESP32') #",
"# Stubber: 1.2.0 def a2b_base64(): pass def b2a_base64(): pass def",
"Module: 'ubinascii' on esp32 1.10.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32',",
"module with ESP32') # Stubber: 1.2.0 def a2b_base64(): pass def"
] |
[
"grp): \"gets new solution and updates data file\" V =",
"beta=beta, grid_size=grid_size) cls.jv = jv # compute solution v_init =",
"def test_policy_sizes(self): \"jv: policies correct size\" n = self.jv.x_grid.size self.assertEqual(self.s_pol.size,",
"max_abs_diff # specify params -- use defaults A = 1.4",
"via value function iteration\" v_init = jv.x_grid * 0.6 V",
"sys.version_info[0] == 2: V = jv_group.V[:] else: # python 3",
"== 2: V = jv_group.V[:] else: # python 3 V",
"@classmethod def setUpClass(cls): jv = JvWorker(A=A, alpha=alpha, beta=beta, grid_size=grid_size) cls.jv",
"jv_group = f.getNode(\"/jv\") except: # doesn't exist group_existed = False",
"V = _new_solution(jv, f, jv_group) return V # if we",
"is an early index self.assertGreaterEqual(self.phi_pol[-1], self.s_pol[-1]) def test_policy_sizes(self): \"jv: policies",
"if sys.version_info[0] == 2: V = jv_group.V[:] else: # python",
"= False jv_group = f.create_group(\"/\", \"jv\", \"data for jv.py tests\")",
"c_pfi V = _new_solution(jv, f, jv_group) return V # if",
"= _get_vf_guess(jv) cls.V = compute_fixed_point(jv.bellman_operator, v_init) cls.s_pol, cls.phi_pol = jv.bellman_operator(cls.V",
"function updates f in place and returns v_vfi, c_vfi, c_pfi",
"alpha = 0.6 beta = 0.96 grid_size = 50 if",
"solution and updates data file\" V = _solve_via_vfi(jv) write_array(f, grp,",
"= f.create_group(\"/\", \"jv\", \"data for jv.py tests\") if force_new or",
"f, jv_group) return V class TestJvWorkder(unittest.TestCase): @classmethod def setUpClass(cls): jv",
"_new_solution(jv, f, jv_group) return V class TestJvWorkder(unittest.TestCase): @classmethod def setUpClass(cls):",
"x is an early index self.assertGreaterEqual(self.s_pol[0], self.phi_pol[0]) def test_high_x_prefer_phi(self): \"jv:",
"policies correct size\" n = self.jv.x_grid.size self.assertEqual(self.s_pol.size, n) self.assertEqual(self.phi_pol.size, n)",
"returns v_vfi, c_vfi, c_pfi V = _new_solution(jv, f, jv_group) return",
"jv import JvWorker from quantecon import compute_fixed_point from quantecon.tests import",
"JvWorker(A=A, alpha=alpha, beta=beta, grid_size=grid_size) cls.jv = jv # compute solution",
"_get_vf_guess(jv, force_new=False): with get_h5_data_file() as f: # See if the",
"SkipTest(\"Python 3 tests aren't ready.\") v_nm = \"V_py3\" def _new_solution(jv,",
"forced to create new data. # This function updates f",
"compute_fixed_point(jv.bellman_operator, v_init) cls.s_pol, cls.phi_pol = jv.bellman_operator(cls.V * 0.999, return_policies=True) def",
"solutions try: # Try reading vfi if sys.version_info[0] == 2:",
"== 2: v_nm = \"V\" else: # python 3 raise",
"if we made it here, the group exists and we",
"3 tests aren't ready.\") v_nm = \"V_py3\" def _new_solution(jv, f,",
"bellman is fixed point\" new_V = self.jv.bellman_operator(self.V) self.assertLessEqual(max_abs_diff(new_V, self.V), 1e-4)",
"n) def test_bellman_sol_fixed_point(self): \"jv: solution to bellman is fixed point\"",
"we should try to read # existing solutions try: #",
"# existing solutions try: # Try reading vfi if sys.version_info[0]",
"0.96 grid_size = 50 if sys.version_info[0] == 2: v_nm =",
"early index self.assertGreaterEqual(self.s_pol[0], self.phi_pol[0]) def test_high_x_prefer_phi(self): \"jv: phi preferred to",
"def test_high_x_prefer_phi(self): \"jv: phi preferred to s with high x?\"",
"sys.version_info[0] == 2: v_nm = \"V\" else: # python 3",
"create it V = _new_solution(jv, f, jv_group) return V class",
"_solve_via_vfi(jv) write_array(f, grp, V, v_nm) return V def _solve_via_vfi(jv): \"compute",
"import compute_fixed_point from quantecon.tests import get_h5_data_file, write_array, max_abs_diff # specify",
"V class TestJvWorkder(unittest.TestCase): @classmethod def setUpClass(cls): jv = JvWorker(A=A, alpha=alpha,",
"# python 3 V = jv_group.V_py3[:] except: # doesn't exist.",
"V = _solve_via_vfi(jv) write_array(f, grp, V, v_nm) return V def",
"return V # if we made it here, the group",
"= compute_fixed_point(jv.bellman_operator, v_init) cls.s_pol, cls.phi_pol = jv.bellman_operator(cls.V * 0.999, return_policies=True)",
"V # if we made it here, the group exists",
"not group_existed: # group doesn't exist, or forced to create",
"import get_h5_data_file, write_array, max_abs_diff # specify params -- use defaults",
"v_init = _get_vf_guess(jv) cls.V = compute_fixed_point(jv.bellman_operator, v_init) cls.s_pol, cls.phi_pol =",
"def _get_vf_guess(jv, force_new=False): with get_h5_data_file() as f: # See if",
"with low x?\" # low x is an early index",
"\"gets new solution and updates data file\" V = _solve_via_vfi(jv)",
"= _new_solution(jv, f, jv_group) return V class TestJvWorkder(unittest.TestCase): @classmethod def",
"try: # Try reading vfi if sys.version_info[0] == 2: V",
"low x is an early index self.assertGreaterEqual(self.phi_pol[-1], self.s_pol[-1]) def test_policy_sizes(self):",
"v_vfi, c_vfi, c_pfi V = _new_solution(jv, f, jv_group) return V",
"def test_bellman_sol_fixed_point(self): \"jv: solution to bellman is fixed point\" new_V",
"# python 3 raise SkipTest(\"Python 3 tests aren't ready.\") v_nm",
"= \"V\" else: # python 3 raise SkipTest(\"Python 3 tests",
"1.4 alpha = 0.6 beta = 0.96 grid_size = 50",
"in place and returns v_vfi, c_vfi, c_pfi V = _new_solution(jv,",
"from nose.plugins.skip import SkipTest from jv import JvWorker from quantecon",
"quantecon.tests import get_h5_data_file, write_array, max_abs_diff # specify params -- use",
"quantecon import compute_fixed_point from quantecon.tests import get_h5_data_file, write_array, max_abs_diff #",
"raise SkipTest(\"Python 3 tests aren't ready.\") v_nm = \"V_py3\" def",
"value function iteration\" v_init = jv.x_grid * 0.6 V =",
"alpha=alpha, beta=beta, grid_size=grid_size) cls.jv = jv # compute solution v_init",
"tests\") if force_new or not group_existed: # group doesn't exist,",
"This function updates f in place and returns v_vfi, c_vfi,",
"and updates data file\" V = _solve_via_vfi(jv) write_array(f, grp, V,",
"= self.jv.x_grid.size self.assertEqual(self.s_pol.size, n) self.assertEqual(self.phi_pol.size, n) def test_bellman_sol_fixed_point(self): \"jv: solution",
"V = jv_group.V_py3[:] except: # doesn't exist. Let's create it",
"it here, the group exists and we should try to",
"Let's create it V = _new_solution(jv, f, jv_group) return V",
"See if the jv group already exists group_existed = True",
"or forced to create new data. # This function updates",
"python 3 raise SkipTest(\"Python 3 tests aren't ready.\") v_nm =",
"\"\"\" @author : <NAME> \"\"\" from __future__ import division import",
"made it here, the group exists and we should try",
"= _new_solution(jv, f, jv_group) return V # if we made",
"read # existing solutions try: # Try reading vfi if",
"\"jv: phi preferred to s with high x?\" # low",
"from quantecon.tests import get_h5_data_file, write_array, max_abs_diff # specify params --",
"get_h5_data_file, write_array, max_abs_diff # specify params -- use defaults A",
"# specify params -- use defaults A = 1.4 alpha",
"\"V_py3\" def _new_solution(jv, f, grp): \"gets new solution and updates",
"return V class TestJvWorkder(unittest.TestCase): @classmethod def setUpClass(cls): jv = JvWorker(A=A,",
"exist, or forced to create new data. # This function",
"create new data. # This function updates f in place",
"to s with high x?\" # low x is an",
"data. # This function updates f in place and returns",
"return_policies=True) def test_low_x_prefer_s(self): \"jv: s preferred to phi with low",
"= \"V_py3\" def _new_solution(jv, f, grp): \"gets new solution and",
"compute solution v_init = _get_vf_guess(jv) cls.V = compute_fixed_point(jv.bellman_operator, v_init) cls.s_pol,",
"# This function updates f in place and returns v_vfi,",
"f: # See if the jv group already exists group_existed",
"jv = JvWorker(A=A, alpha=alpha, beta=beta, grid_size=grid_size) cls.jv = jv #",
"# low x is an early index self.assertGreaterEqual(self.phi_pol[-1], self.s_pol[-1]) def",
"correct size\" n = self.jv.x_grid.size self.assertEqual(self.s_pol.size, n) self.assertEqual(self.phi_pol.size, n) def",
"V = compute_fixed_point(jv.bellman_operator, v_init, max_iter=3000, error_tol=1e-5) return V def _get_vf_guess(jv,",
"division import sys import unittest from nose.plugins.skip import SkipTest from",
"# group doesn't exist, or forced to create new data.",
"= JvWorker(A=A, alpha=alpha, beta=beta, grid_size=grid_size) cls.jv = jv # compute",
"-- use defaults A = 1.4 alpha = 0.6 beta",
"SkipTest from jv import JvWorker from quantecon import compute_fixed_point from",
"n = self.jv.x_grid.size self.assertEqual(self.s_pol.size, n) self.assertEqual(self.phi_pol.size, n) def test_bellman_sol_fixed_point(self): \"jv:",
"except: # doesn't exist group_existed = False jv_group = f.create_group(\"/\",",
"= jv.bellman_operator(cls.V * 0.999, return_policies=True) def test_low_x_prefer_s(self): \"jv: s preferred",
"low x is an early index self.assertGreaterEqual(self.s_pol[0], self.phi_pol[0]) def test_high_x_prefer_phi(self):",
"v_init = jv.x_grid * 0.6 V = compute_fixed_point(jv.bellman_operator, v_init, max_iter=3000,",
"v_init) cls.s_pol, cls.phi_pol = jv.bellman_operator(cls.V * 0.999, return_policies=True) def test_low_x_prefer_s(self):",
"n) self.assertEqual(self.phi_pol.size, n) def test_bellman_sol_fixed_point(self): \"jv: solution to bellman is",
"cls.jv = jv # compute solution v_init = _get_vf_guess(jv) cls.V",
"v_nm) return V def _solve_via_vfi(jv): \"compute policy rules via value",
"preferred to phi with low x?\" # low x is",
"v_init, max_iter=3000, error_tol=1e-5) return V def _get_vf_guess(jv, force_new=False): with get_h5_data_file()",
"= 0.6 beta = 0.96 grid_size = 50 if sys.version_info[0]",
"grid_size = 50 if sys.version_info[0] == 2: v_nm = \"V\"",
"should try to read # existing solutions try: # Try",
"exists and we should try to read # existing solutions",
"cls.V = compute_fixed_point(jv.bellman_operator, v_init) cls.s_pol, cls.phi_pol = jv.bellman_operator(cls.V * 0.999,",
": <NAME> \"\"\" from __future__ import division import sys import",
"iteration\" v_init = jv.x_grid * 0.6 V = compute_fixed_point(jv.bellman_operator, v_init,",
"_new_solution(jv, f, jv_group) return V # if we made it",
"jv_group.V[:] else: # python 3 V = jv_group.V_py3[:] except: #",
"setUpClass(cls): jv = JvWorker(A=A, alpha=alpha, beta=beta, grid_size=grid_size) cls.jv = jv",
"\"data for jv.py tests\") if force_new or not group_existed: #",
"= jv.x_grid * 0.6 V = compute_fixed_point(jv.bellman_operator, v_init, max_iter=3000, error_tol=1e-5)",
"JvWorker from quantecon import compute_fixed_point from quantecon.tests import get_h5_data_file, write_array,",
"tests aren't ready.\") v_nm = \"V_py3\" def _new_solution(jv, f, grp):",
"f, grp): \"gets new solution and updates data file\" V",
"index self.assertGreaterEqual(self.phi_pol[-1], self.s_pol[-1]) def test_policy_sizes(self): \"jv: policies correct size\" n",
"to phi with low x?\" # low x is an",
"# if we made it here, the group exists and",
"test_policy_sizes(self): \"jv: policies correct size\" n = self.jv.x_grid.size self.assertEqual(self.s_pol.size, n)",
"test_high_x_prefer_phi(self): \"jv: phi preferred to s with high x?\" #",
"to create new data. # This function updates f in",
"place and returns v_vfi, c_vfi, c_pfi V = _new_solution(jv, f,",
"phi with low x?\" # low x is an early",
"grid_size=grid_size) cls.jv = jv # compute solution v_init = _get_vf_guess(jv)",
"python 3 V = jv_group.V_py3[:] except: # doesn't exist. Let's",
"group already exists group_existed = True try: jv_group = f.getNode(\"/jv\")",
"\"jv: policies correct size\" n = self.jv.x_grid.size self.assertEqual(self.s_pol.size, n) self.assertEqual(self.phi_pol.size,",
"50 if sys.version_info[0] == 2: v_nm = \"V\" else: #",
"doesn't exist. Let's create it V = _new_solution(jv, f, jv_group)",
"an early index self.assertGreaterEqual(self.s_pol[0], self.phi_pol[0]) def test_high_x_prefer_phi(self): \"jv: phi preferred",
"A = 1.4 alpha = 0.6 beta = 0.96 grid_size",
"Try reading vfi if sys.version_info[0] == 2: V = jv_group.V[:]",
"return V def _solve_via_vfi(jv): \"compute policy rules via value function",
"file\" V = _solve_via_vfi(jv) write_array(f, grp, V, v_nm) return V",
"f.create_group(\"/\", \"jv\", \"data for jv.py tests\") if force_new or not",
"group exists and we should try to read # existing",
"True try: jv_group = f.getNode(\"/jv\") except: # doesn't exist group_existed",
"= jv_group.V[:] else: # python 3 V = jv_group.V_py3[:] except:",
"early index self.assertGreaterEqual(self.phi_pol[-1], self.s_pol[-1]) def test_policy_sizes(self): \"jv: policies correct size\"",
"existing solutions try: # Try reading vfi if sys.version_info[0] ==",
"v_nm = \"V\" else: # python 3 raise SkipTest(\"Python 3",
"from jv import JvWorker from quantecon import compute_fixed_point from quantecon.tests",
"high x?\" # low x is an early index self.assertGreaterEqual(self.phi_pol[-1],",
"__future__ import division import sys import unittest from nose.plugins.skip import",
"s with high x?\" # low x is an early",
"* 0.6 V = compute_fixed_point(jv.bellman_operator, v_init, max_iter=3000, error_tol=1e-5) return V",
"_solve_via_vfi(jv): \"compute policy rules via value function iteration\" v_init =",
"to read # existing solutions try: # Try reading vfi",
"self.phi_pol[0]) def test_high_x_prefer_phi(self): \"jv: phi preferred to s with high",
"\"V\" else: # python 3 raise SkipTest(\"Python 3 tests aren't",
"the jv group already exists group_existed = True try: jv_group",
"group_existed = False jv_group = f.create_group(\"/\", \"jv\", \"data for jv.py",
"function iteration\" v_init = jv.x_grid * 0.6 V = compute_fixed_point(jv.bellman_operator,",
"defaults A = 1.4 alpha = 0.6 beta = 0.96",
"\"jv: solution to bellman is fixed point\" new_V = self.jv.bellman_operator(self.V)",
"cls.s_pol, cls.phi_pol = jv.bellman_operator(cls.V * 0.999, return_policies=True) def test_low_x_prefer_s(self): \"jv:",
"size\" n = self.jv.x_grid.size self.assertEqual(self.s_pol.size, n) self.assertEqual(self.phi_pol.size, n) def test_bellman_sol_fixed_point(self):",
"group_existed: # group doesn't exist, or forced to create new",
"self.assertEqual(self.phi_pol.size, n) def test_bellman_sol_fixed_point(self): \"jv: solution to bellman is fixed",
"self.assertEqual(self.s_pol.size, n) self.assertEqual(self.phi_pol.size, n) def test_bellman_sol_fixed_point(self): \"jv: solution to bellman",
"except: # doesn't exist. Let's create it V = _new_solution(jv,",
"try: jv_group = f.getNode(\"/jv\") except: # doesn't exist group_existed =",
"= _solve_via_vfi(jv) write_array(f, grp, V, v_nm) return V def _solve_via_vfi(jv):",
"index self.assertGreaterEqual(self.s_pol[0], self.phi_pol[0]) def test_high_x_prefer_phi(self): \"jv: phi preferred to s",
"and we should try to read # existing solutions try:",
"new data. # This function updates f in place and",
"v_nm = \"V_py3\" def _new_solution(jv, f, grp): \"gets new solution",
"import SkipTest from jv import JvWorker from quantecon import compute_fixed_point",
"self.s_pol[-1]) def test_policy_sizes(self): \"jv: policies correct size\" n = self.jv.x_grid.size",
"solution to bellman is fixed point\" new_V = self.jv.bellman_operator(self.V) self.assertLessEqual(max_abs_diff(new_V,",
"test_bellman_sol_fixed_point(self): \"jv: solution to bellman is fixed point\" new_V =",
"ready.\") v_nm = \"V_py3\" def _new_solution(jv, f, grp): \"gets new",
"is an early index self.assertGreaterEqual(self.s_pol[0], self.phi_pol[0]) def test_high_x_prefer_phi(self): \"jv: phi",
"x?\" # low x is an early index self.assertGreaterEqual(self.s_pol[0], self.phi_pol[0])",
"with high x?\" # low x is an early index",
"here, the group exists and we should try to read",
"specify params -- use defaults A = 1.4 alpha =",
"force_new=False): with get_h5_data_file() as f: # See if the jv",
"= 1.4 alpha = 0.6 beta = 0.96 grid_size =",
"if the jv group already exists group_existed = True try:",
"sys import unittest from nose.plugins.skip import SkipTest from jv import",
"def _solve_via_vfi(jv): \"compute policy rules via value function iteration\" v_init",
"# doesn't exist. Let's create it V = _new_solution(jv, f,",
"aren't ready.\") v_nm = \"V_py3\" def _new_solution(jv, f, grp): \"gets",
"# See if the jv group already exists group_existed =",
"and returns v_vfi, c_vfi, c_pfi V = _new_solution(jv, f, jv_group)",
"group_existed = True try: jv_group = f.getNode(\"/jv\") except: # doesn't",
"nose.plugins.skip import SkipTest from jv import JvWorker from quantecon import",
"get_h5_data_file() as f: # See if the jv group already",
"solution v_init = _get_vf_guess(jv) cls.V = compute_fixed_point(jv.bellman_operator, v_init) cls.s_pol, cls.phi_pol",
"import sys import unittest from nose.plugins.skip import SkipTest from jv",
"low x?\" # low x is an early index self.assertGreaterEqual(self.s_pol[0],",
"f in place and returns v_vfi, c_vfi, c_pfi V =",
"test_low_x_prefer_s(self): \"jv: s preferred to phi with low x?\" #",
"_new_solution(jv, f, grp): \"gets new solution and updates data file\"",
"preferred to s with high x?\" # low x is",
"updates f in place and returns v_vfi, c_vfi, c_pfi V",
"3 V = jv_group.V_py3[:] except: # doesn't exist. Let's create",
"max_iter=3000, error_tol=1e-5) return V def _get_vf_guess(jv, force_new=False): with get_h5_data_file() as",
"params -- use defaults A = 1.4 alpha = 0.6",
"= 50 if sys.version_info[0] == 2: v_nm = \"V\" else:",
"TestJvWorkder(unittest.TestCase): @classmethod def setUpClass(cls): jv = JvWorker(A=A, alpha=alpha, beta=beta, grid_size=grid_size)",
"it V = _new_solution(jv, f, jv_group) return V class TestJvWorkder(unittest.TestCase):",
"phi preferred to s with high x?\" # low x",
"@author : <NAME> \"\"\" from __future__ import division import sys",
"jv.py tests\") if force_new or not group_existed: # group doesn't",
"write_array(f, grp, V, v_nm) return V def _solve_via_vfi(jv): \"compute policy",
"2: V = jv_group.V[:] else: # python 3 V =",
"write_array, max_abs_diff # specify params -- use defaults A =",
"= jv # compute solution v_init = _get_vf_guess(jv) cls.V =",
"try to read # existing solutions try: # Try reading",
"import division import sys import unittest from nose.plugins.skip import SkipTest",
"s preferred to phi with low x?\" # low x",
"V def _solve_via_vfi(jv): \"compute policy rules via value function iteration\"",
"x?\" # low x is an early index self.assertGreaterEqual(self.phi_pol[-1], self.s_pol[-1])",
"class TestJvWorkder(unittest.TestCase): @classmethod def setUpClass(cls): jv = JvWorker(A=A, alpha=alpha, beta=beta,",
"V = _new_solution(jv, f, jv_group) return V class TestJvWorkder(unittest.TestCase): @classmethod",
"c_vfi, c_pfi V = _new_solution(jv, f, jv_group) return V #",
"doesn't exist, or forced to create new data. # This",
"= jv_group.V_py3[:] except: # doesn't exist. Let's create it V",
"group doesn't exist, or forced to create new data. #",
"jv.x_grid * 0.6 V = compute_fixed_point(jv.bellman_operator, v_init, max_iter=3000, error_tol=1e-5) return",
"def _new_solution(jv, f, grp): \"gets new solution and updates data",
"an early index self.assertGreaterEqual(self.phi_pol[-1], self.s_pol[-1]) def test_policy_sizes(self): \"jv: policies correct",
"doesn't exist group_existed = False jv_group = f.create_group(\"/\", \"jv\", \"data",
"reading vfi if sys.version_info[0] == 2: V = jv_group.V[:] else:",
"0.6 V = compute_fixed_point(jv.bellman_operator, v_init, max_iter=3000, error_tol=1e-5) return V def",
"self.jv.x_grid.size self.assertEqual(self.s_pol.size, n) self.assertEqual(self.phi_pol.size, n) def test_bellman_sol_fixed_point(self): \"jv: solution to",
"\"jv\", \"data for jv.py tests\") if force_new or not group_existed:",
"exists group_existed = True try: jv_group = f.getNode(\"/jv\") except: #",
"vfi if sys.version_info[0] == 2: V = jv_group.V[:] else: #",
"unittest from nose.plugins.skip import SkipTest from jv import JvWorker from",
"cls.phi_pol = jv.bellman_operator(cls.V * 0.999, return_policies=True) def test_low_x_prefer_s(self): \"jv: s",
"data file\" V = _solve_via_vfi(jv) write_array(f, grp, V, v_nm) return",
"= 0.96 grid_size = 50 if sys.version_info[0] == 2: v_nm",
"as f: # See if the jv group already exists",
"new solution and updates data file\" V = _solve_via_vfi(jv) write_array(f,",
"self.assertGreaterEqual(self.phi_pol[-1], self.s_pol[-1]) def test_policy_sizes(self): \"jv: policies correct size\" n =",
"def setUpClass(cls): jv = JvWorker(A=A, alpha=alpha, beta=beta, grid_size=grid_size) cls.jv =",
"for jv.py tests\") if force_new or not group_existed: # group",
"V def _get_vf_guess(jv, force_new=False): with get_h5_data_file() as f: # See",
"# compute solution v_init = _get_vf_guess(jv) cls.V = compute_fixed_point(jv.bellman_operator, v_init)",
"grp, V, v_nm) return V def _solve_via_vfi(jv): \"compute policy rules",
"V = jv_group.V[:] else: # python 3 V = jv_group.V_py3[:]",
"2: v_nm = \"V\" else: # python 3 raise SkipTest(\"Python",
"0.6 beta = 0.96 grid_size = 50 if sys.version_info[0] ==",
"import unittest from nose.plugins.skip import SkipTest from jv import JvWorker",
"jv_group) return V class TestJvWorkder(unittest.TestCase): @classmethod def setUpClass(cls): jv =",
"<NAME> \"\"\" from __future__ import division import sys import unittest",
"jv.bellman_operator(cls.V * 0.999, return_policies=True) def test_low_x_prefer_s(self): \"jv: s preferred to",
"if sys.version_info[0] == 2: v_nm = \"V\" else: # python",
"jv # compute solution v_init = _get_vf_guess(jv) cls.V = compute_fixed_point(jv.bellman_operator,",
"self.assertGreaterEqual(self.s_pol[0], self.phi_pol[0]) def test_high_x_prefer_phi(self): \"jv: phi preferred to s with",
"use defaults A = 1.4 alpha = 0.6 beta =",
"from quantecon import compute_fixed_point from quantecon.tests import get_h5_data_file, write_array, max_abs_diff",
"= f.getNode(\"/jv\") except: # doesn't exist group_existed = False jv_group",
"else: # python 3 V = jv_group.V_py3[:] except: # doesn't",
"V, v_nm) return V def _solve_via_vfi(jv): \"compute policy rules via",
"x is an early index self.assertGreaterEqual(self.phi_pol[-1], self.s_pol[-1]) def test_policy_sizes(self): \"jv:",
"from __future__ import division import sys import unittest from nose.plugins.skip",
"we made it here, the group exists and we should",
"# low x is an early index self.assertGreaterEqual(self.s_pol[0], self.phi_pol[0]) def",
"exist. Let's create it V = _new_solution(jv, f, jv_group) return",
"= compute_fixed_point(jv.bellman_operator, v_init, max_iter=3000, error_tol=1e-5) return V def _get_vf_guess(jv, force_new=False):",
"f, jv_group) return V # if we made it here,",
"False jv_group = f.create_group(\"/\", \"jv\", \"data for jv.py tests\") if",
"to bellman is fixed point\" new_V = self.jv.bellman_operator(self.V) self.assertLessEqual(max_abs_diff(new_V, self.V),",
"already exists group_existed = True try: jv_group = f.getNode(\"/jv\") except:",
"force_new or not group_existed: # group doesn't exist, or forced",
"error_tol=1e-5) return V def _get_vf_guess(jv, force_new=False): with get_h5_data_file() as f:",
"compute_fixed_point(jv.bellman_operator, v_init, max_iter=3000, error_tol=1e-5) return V def _get_vf_guess(jv, force_new=False): with",
"* 0.999, return_policies=True) def test_low_x_prefer_s(self): \"jv: s preferred to phi",
"compute_fixed_point from quantecon.tests import get_h5_data_file, write_array, max_abs_diff # specify params",
"policy rules via value function iteration\" v_init = jv.x_grid *",
"beta = 0.96 grid_size = 50 if sys.version_info[0] == 2:",
"_get_vf_guess(jv) cls.V = compute_fixed_point(jv.bellman_operator, v_init) cls.s_pol, cls.phi_pol = jv.bellman_operator(cls.V *",
"\"compute policy rules via value function iteration\" v_init = jv.x_grid",
"return V def _get_vf_guess(jv, force_new=False): with get_h5_data_file() as f: #",
"exist group_existed = False jv_group = f.create_group(\"/\", \"jv\", \"data for",
"rules via value function iteration\" v_init = jv.x_grid * 0.6",
"the group exists and we should try to read #",
"with get_h5_data_file() as f: # See if the jv group",
"# Try reading vfi if sys.version_info[0] == 2: V =",
"jv group already exists group_existed = True try: jv_group =",
"\"\"\" from __future__ import division import sys import unittest from",
"if force_new or not group_existed: # group doesn't exist, or",
"or not group_existed: # group doesn't exist, or forced to",
"0.999, return_policies=True) def test_low_x_prefer_s(self): \"jv: s preferred to phi with",
"jv_group) return V # if we made it here, the",
"import JvWorker from quantecon import compute_fixed_point from quantecon.tests import get_h5_data_file,",
"f.getNode(\"/jv\") except: # doesn't exist group_existed = False jv_group =",
"3 raise SkipTest(\"Python 3 tests aren't ready.\") v_nm = \"V_py3\"",
"else: # python 3 raise SkipTest(\"Python 3 tests aren't ready.\")",
"jv_group.V_py3[:] except: # doesn't exist. Let's create it V =",
"= True try: jv_group = f.getNode(\"/jv\") except: # doesn't exist",
"updates data file\" V = _solve_via_vfi(jv) write_array(f, grp, V, v_nm)",
"# doesn't exist group_existed = False jv_group = f.create_group(\"/\", \"jv\",",
"def test_low_x_prefer_s(self): \"jv: s preferred to phi with low x?\"",
"\"jv: s preferred to phi with low x?\" # low",
"jv_group = f.create_group(\"/\", \"jv\", \"data for jv.py tests\") if force_new"
] |
[
"must try to catch anything that # may come our",
"= dict() _update_single(cfg, names, defaults) _update_from_file(cfg, names, cfg_file) argdict =",
"except IOError: config = OrderedDict() return config def run(arg): \"\"\"Run",
"arg.parser_name == 'to' and arg.lang in cfg: _update_from_arg(cfg, argdict, arg.lang)",
"out a warning message # and ignore it. except Exception",
"for line in fhandle: line_num += 1 if line[0] ==",
"argparse Action class to use when displaying the configuration file",
"that the configuration file can overwrite use the `defaults` command.",
"_read_config(fname, arg): \"\"\"Simple parser to read configuration files. \"\"\" data",
"os.path.expandvars(val) def _update_from_arg(cfg, argdict, key): \"Helper function for get_cfg.\" for",
"% path) arg.cfg = path try: config = _read_config('%s/xcpp.config' %",
"come our way so that we may give out a",
"match = RE_IFELSE.match(val) if match: cond, enum = _eval_condition( match.group('cond'),",
"condition without creating a whole # new parser we can",
"= val return data def read_config(arg): \"\"\"Read the configuration file",
"path = arg.cfg if path == '.' and not os.path.exists('xcpp.config'):",
"be used in the configuration file. # ARG gives us",
"= dict(key_val) replacement_function = lambda match: replace_dict[match.group(0)] pattern = re.compile(\"|\".join([re.escape(k)",
"enum def _read_config(fname, arg): \"\"\"Simple parser to read configuration files.",
"collections import OrderedDict from excentury.command import error, trace, import_mod DESC",
"\"Add a parser to the main subparser. \" tmpp =",
"%s = %s\\n' % (key, config[sec][key])) disp('\\n') return try: command,",
"cfg_file) argdict = vars(arg) if arg.parser_name in cfg: _update_from_arg(cfg, argdict,",
"this reason we must try to catch anything that #",
"disable=eval-used # To be able to evaluate a condition without",
"namespace.cfg) else: disp('path to xcpp.config: \"%s\"\\n' % namespace.cfg) with open('%s/xcpp.config'",
") return replacements # pylint: disable=invalid-name # ARG and CFG",
"\"\"\"Replacement of strings done in one pass. Example: >>> replace(\"a",
"re.compile(\"|\".join([re.escape(k) for k, _ in key_val]), re.M) return lambda string:",
"we can use the eval function. We could have use",
"if arg.var is None: for sec in config: disp('[%s]\\n' %",
"= OrderedDict() return config def run(arg): \"\"\"Run command. \"\"\" config",
"for get_cfg.\" if name in cfg_file: for var, val in",
"access to the current configuration. Note that using CFG[key][sec] #",
"= RE_IFELSE.match(val) if match: cond, enum = _eval_condition( match.group('cond'), arg,",
"which is meant to behave as the print function but",
"= line[1:-2] data[sec] = OrderedDict() elif '=' in line: tmp",
"= 0 with open(fname, 'r') as fhandle: for line in",
"path) arg.cfg = path try: config = _read_config('%s/xcpp.config' % path,",
"= re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]ELSE (?P<iffalse>.*)' ) def disp(msg): \"\"\"Wrapper around",
"\"\"\"Config This module is in charge of providing all the",
"to use when displaying the configuration file and location.\"\"\" def",
"val = groups[0] if cond else groups[2] else: match =",
"xcpp.config\"\"\" path = arg.cfg if path == '.' and not",
"use the eval function. We could have use # a",
"error, trace, import_mod DESC = \"\"\"Edit a configuration file for",
"replace_dict = dict(key_val) replacement_function = lambda match: replace_dict[match.group(0)] pattern =",
"# a python file as a configuration but then there",
"the result of the evaluation and an error number: 0",
"arg.var is None: for sec in config: disp('[%s]\\n' % sec)",
"replacements # pylint: disable=invalid-name # ARG and CFG are names",
"cfg_file): \"Helper function for get_cfg.\" if name in cfg_file: for",
"\"\"\"Helper function for _read_config. \"\"\" replacements = list() for token",
"actions performed by excentury can be overwritten by using configuration",
"\"%s\"\\n' % arg.cfg) if arg.var is None: for sec in",
"was an error. \"\"\" ARG.FILEPATH = '%s/%s/%s' % (ARG.cfg, CFG['xcpp']['path'],",
"\"\"\" config = read_config(arg) if arg.v: disp('path to xcpp.config: \"%s\"\\n'",
"var = arg.var.split('.', 1) except ValueError: error(\"ERROR: '%s' is not",
"import os import re import sys import textwrap import argparse",
"current configuration. Note that using CFG[key][sec] # is equivalent to",
"able to evaluate a condition without creating a whole #",
"groups[2] else: match = RE_IF.match(val) if match: cond, enum =",
"arguments and CFG gives us # access to the current",
"= vars(arg) if arg.parser_name in cfg: _update_from_arg(cfg, argdict, arg.parser_name) elif",
"def _update_from_arg(cfg, argdict, key): \"Helper function for get_cfg.\" for var",
"% name) if hasattr(mod, \"DEFAULTS\"): for var, val in mod.DEFAULTS.iteritems():",
"parser we can use the eval function. We could have",
"in a configuration file. def _eval_condition(cond, ARG, CFG, line_num, fname):",
"% path, arg) except IOError: config = OrderedDict() return config",
"'&')) 'a < b && b < c' Source: <http://stackoverflow.com/a/15221068/788553>",
"us # access to the current configuration. Note that using",
"get_cfg.\" if defaults: for var, val in defaults.iteritems(): cfg[name][var] =",
"'to' and arg.lang in cfg: _update_from_arg(cfg, argdict, arg.lang) _update_from_arg(cfg, argdict,",
"line_num, fname, exception.message ) ) return cond, enum def _read_config(fname,",
"path, arg) except IOError: config = OrderedDict() return config def",
"To see the values that the configuration file can overwrite",
"would be # no simple structure to the files. cond",
"could have use # a python file as a configuration",
"no simple structure to the files. cond = eval(cond) enum",
"for replace. Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" replace_dict = dict(key_val) replacement_function =",
"result of the evaluation and an error number: 0 if",
"if match: cond, enum = _eval_condition( match.group('cond'), arg, data, line_num,",
"argparse from collections import OrderedDict from excentury.command import error, trace,",
"against the convention # so that they may be easy",
"# pylint: disable=star-args if replacements: val = replace(val, *replacements) match",
"is not None: cfg[key][var] = argdict[var] def get_cfg(arg, names, defaults=None):",
"# pylint: disable=R0903 \"\"\"Derived argparse Action class to use when",
"var, val in mod.DEFAULTS.iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_file(cfg, name,",
"fhandle: line_num += 1 if line[0] == '[': sec =",
"os.path.expandvars(val) replacements = _get_replacements( RE.findall(val), data, sec ) # pylint:",
"in mod.DEFAULTS.iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_file(cfg, name, cfg_file): \"Helper",
"for var in cfg[key]: if var in argdict and argdict[var]",
"as fhandle: for line in fhandle: line_num += 1 if",
"\"\"\"Read the configuration file xcpp.config\"\"\" path = arg.cfg if path",
"= match.group('iftrue') else: continue data[sec][key] = val return data def",
"excentury. Some actions performed by excentury can be overwritten by",
"CFG are names that may be used in the configuration",
"# and ignore it. except Exception as exception: cond =",
"%r\\n' % namespace.cfg) else: disp('path to xcpp.config: \"%s\"\\n' % namespace.cfg)",
"else: if token in data[sec]: tval = data[sec][token] else: tval",
"# ARG gives us access to the command line arguments",
"trace(\"Configured with: '%s/xcpp.config'\\n\" % tmp_path) path = tmp_path elif not",
"access to the command line arguments and CFG gives us",
"execution of the `eval` # function. For this reason we",
"== 1: continue groups = match.groups() val = groups[0] if",
"re.compile(r'\\${(?P<key>.*?)}') RE_IF = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]' ) RE_IFELSE = re.compile(",
"${key:sec}. These names go against the convention # so that",
"= os.environ['XCPP_CONFIG_PATH'] if os.path.exists('%s/xcpp.config' % tmp_path): trace(\"Configured with: '%s/xcpp.config'\\n\" %",
"go wrong during the execution of the `eval` # function.",
"line_num, fname ) if enum == 1: continue if cond:",
"'.' and not os.path.exists('xcpp.config'): if 'XCPP_CONFIG_PATH' in os.environ: tmp_path =",
"== 'to' and arg.lang in cfg: _update_from_arg(cfg, argdict, arg.lang) _update_from_arg(cfg,",
"cfg_file) else: if names != 'xcpp': cfg[names] = dict() _update_single(cfg,",
"= OrderedDict() sec = None line_num = 0 with open(fname,",
"if tkey in data[tsec]: tval = data[tsec][tkey] else: if token",
"return lambda string: pattern.sub(replacement_function, string) def replace(string, *key_val): \"\"\"Replacement of",
"_fp: disp(_fp.read()) exit(0) def add_parser(subp, raw): \"Add a parser to",
"sec): \"\"\"Helper function for _read_config. \"\"\" replacements = list() for",
"data = OrderedDict() sec = None line_num = 0 with",
"config: disp('[%s]\\n' % sec) for key in config[sec]: disp(' %s",
"= data[tsec][tkey] else: if token in data[sec]: tval = data[sec][token]",
"CFG['xcpp']['path'], ARG.inputfile) try: # pylint: disable=eval-used # To be able",
"'.', 'path': '.' } } cfg_file = read_config(arg) if 'xcpp'",
"is not of the form sec.key\\n\" % arg.var) try: disp(config[command][var]+'\\n')",
"command. This will print a list of the keys and",
"config file and exit') def _get_replacements(tokens, data, sec): \"\"\"Helper function",
"replace(val, *replacements) match = RE_IFELSE.match(val) if match: cond, enum =",
"a warning if there are any errors. Returns the result",
"# may come our way so that we may give",
"in the configuration file. # ARG gives us access to",
"the eval function. We could have use # a python",
"sec = None line_num = 0 with open(fname, 'r') as",
"xcpp.config: \"%s\"\\n' % arg.cfg) if arg.var is None: for sec",
"disp(' %s = %s\\n' % (key, config[sec][key])) disp('\\n') return try:",
"( line_num, fname, exception.message ) ) return cond, enum def",
"= None enum = 1 trace( 'WARNING: error in line",
"to evaluate a condition without creating a whole # new",
"= %s\\n' % (key, config[sec][key])) disp('\\n') return try: command, var",
"= data[sec][token] else: tval = '' replacements.append( ('${%s}' % token,",
"None: cfg[key][var] = argdict[var] def get_cfg(arg, names, defaults=None): \"\"\"Obtain the",
"a python file as a configuration but then there would",
"This will print a list of the keys and values",
"< c\", ('<', '<'), ('&', '&')) 'a < b &&",
"= replace(val, *replacements) match = RE_IFELSE.match(val) if match: cond, enum",
"eval(cond) enum = 0 # pylint: disable=broad-except # Anything can",
">>> replace(\"a < b && b < c\", ('<', '<'),",
"def disp(msg): \"\"\"Wrapper around sys.stdout.write which is meant to behave",
"enum = _eval_condition( match.group('cond'), arg, data, line_num, fname ) if",
"function for get_cfg.\" if name in cfg_file: for var, val",
"= _get_replacements( RE.findall(val), data, sec ) # pylint: disable=star-args if",
"replace(\"a < b && b < c\", ('<', '<'), ('&',",
"an error. \"\"\" ARG.FILEPATH = '%s/%s/%s' % (ARG.cfg, CFG['xcpp']['path'], ARG.inputfile)",
"configuration file for excentury. Some actions performed by excentury can",
"cond = None enum = 1 trace( 'WARNING: error in",
"'.' } } cfg_file = read_config(arg) if 'xcpp' in cfg_file:",
"and exit') def _get_replacements(tokens, data, sec): \"\"\"Helper function for _read_config.",
") if enum == 1: continue groups = match.groups() val",
"as exception: cond = None enum = 1 trace( 'WARNING:",
"continue groups = match.groups() val = groups[0] if cond else",
"replace. Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" replace_dict = dict(key_val) replacement_function = lambda",
"else: mod = import_mod('excentury.command.%s' % name) if hasattr(mod, \"DEFAULTS\"): for",
"= eval(cond) enum = 0 # pylint: disable=broad-except # Anything",
"return replacements # pylint: disable=invalid-name # ARG and CFG are",
"to catch anything that # may come our way so",
"config = OrderedDict() return config def run(arg): \"\"\"Run command. \"\"\"",
"file and location.\"\"\" def __call__(self, parser, namespace, values, option_string=None): try:",
"OrderedDict() return config def run(arg): \"\"\"Run command. \"\"\" config =",
"cfg[name][var] = os.path.expandvars(val) def _update_from_file(cfg, name, cfg_file): \"Helper function for",
"for var, val in cfg_file[name].iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_arg(cfg,",
"if name in cfg_file: for var, val in cfg_file[name].iteritems(): cfg[name][var]",
"cfg[key]: if var in argdict and argdict[var] is not None:",
"{ 'root': '.', 'path': '.' } } cfg_file = read_config(arg)",
"overwritten by using configuration files. To see the values that",
"os.path.exists('%s/xcpp.config' % tmp_path): trace(\"Configured with: '%s/xcpp.config'\\n\" % tmp_path) path =",
"tmp_path = os.environ['XCPP_CONFIG_PATH'] if os.path.exists('%s/xcpp.config' % tmp_path): trace(\"Configured with: '%s/xcpp.config'\\n\"",
"= list() for token in tokens: if ':' in token:",
"line arguments and CFG gives us # access to the",
"arg.v: disp('path to xcpp.config: \"%s\"\\n' % arg.cfg) if arg.var is",
"if hasattr(mod, \"DEFAULTS\"): for var, val in mod.DEFAULTS.iteritems(): cfg[name][var] =",
"'WARNING: error in line %d of %r: %s\\n' % (",
"cond: val = match.group('iftrue') else: continue data[sec][key] = val return",
"= read_config(arg) if arg.v: disp('path to xcpp.config: \"%s\"\\n' % arg.cfg)",
"\"\"\"Derived argparse Action class to use when displaying the configuration",
"of strings done in one pass. Example: >>> replace(\"a <",
"in names: cfg[name] = dict() _update_single(cfg, name) _update_from_file(cfg, name, cfg_file)",
"Exception as exception: cond = None enum = 1 trace(",
"sec.key\\n\" % arg.var) try: disp(config[command][var]+'\\n') except KeyError: pass return def",
"parser, namespace, values, option_string=None): try: read_config(namespace) except IOError: disp('xcpp.config not",
"configuration but then there would be # no simple structure",
"character. \"\"\" sys.stdout.write(msg) def _replacer(*key_val): \"\"\"Helper function for replace. Source:",
"and CFG are names that may be used in the",
"in cfg_file['xcpp'].iteritems(): cfg['xcpp'][var] = os.path.expandvars(val) cfg['xcpp']['root'] = arg.cfg if isinstance(names,",
"% arg.var) try: disp(config[command][var]+'\\n') except KeyError: pass return def _update_single(cfg,",
"if enum == 1: continue groups = match.groups() val =",
"tmpp.add_argument('-v', action='store_true', help='print config file location') tmpp.add_argument('--print', action=ConfigDispAction, nargs=0, help='print",
"the values that the configuration file can overwrite use the",
"lambda match: replace_dict[match.group(0)] pattern = re.compile(\"|\".join([re.escape(k) for k, _ in",
"be easy to spot in a configuration file. def _eval_condition(cond,",
"namespace, values, option_string=None): try: read_config(namespace) except IOError: disp('xcpp.config not found",
"open('%s/xcpp.config' % namespace.cfg, 'r') as _fp: disp(_fp.read()) exit(0) def add_parser(subp,",
"if token in data[sec]: tval = data[sec][token] else: tval =",
"exit') def _get_replacements(tokens, data, sec): \"\"\"Helper function for _read_config. \"\"\"",
"config = _read_config('%s/xcpp.config' % path, arg) except IOError: config =",
"if 'xcpp' in cfg_file: for var, val in cfg_file['xcpp'].iteritems(): cfg['xcpp'][var]",
"arg.var) try: disp(config[command][var]+'\\n') except KeyError: pass return def _update_single(cfg, name,",
"disp('[%s]\\n' % sec) for key in config[sec]: disp(' %s =",
"CFG gives us # access to the current configuration. Note",
"be # no simple structure to the files. cond =",
"data, sec): \"\"\"Helper function for _read_config. \"\"\" replacements = list()",
"sec) for key in config[sec]: disp(' %s = %s\\n' %",
"%s/xcpp.config does not exist\\n\" % path) arg.cfg = path try:",
") def disp(msg): \"\"\"Wrapper around sys.stdout.write which is meant to",
"% arg.cfg) if arg.var is None: for sec in config:",
"newline character. \"\"\" sys.stdout.write(msg) def _replacer(*key_val): \"\"\"Helper function for replace.",
"\"%s\"\\n' % namespace.cfg) with open('%s/xcpp.config' % namespace.cfg, 'r') as _fp:",
"token, tval) ) return replacements # pylint: disable=invalid-name # ARG",
"given command. \"\"\" RE = re.compile(r'\\${(?P<key>.*?)}') RE_IF = re.compile( r'(?P<iftrue>.*?)",
"location.\"\"\" def __call__(self, parser, namespace, values, option_string=None): try: read_config(namespace) except",
"for sec in config: disp('[%s]\\n' % sec) for key in",
"prints a warning if there are any errors. Returns the",
"'%s' is not of the form sec.key\\n\" % arg.var) try:",
"_update_from_file(cfg, name, cfg_file): \"Helper function for get_cfg.\" if name in",
"read_config(arg) if 'xcpp' in cfg_file: for var, val in cfg_file['xcpp'].iteritems():",
"cfg_file['xcpp'].iteritems(): cfg['xcpp'][var] = os.path.expandvars(val) cfg['xcpp']['root'] = arg.cfg if isinstance(names, list):",
"if replacements: val = replace(val, *replacements) match = RE_IFELSE.match(val) if",
"# so that they may be easy to spot in",
"a list of the keys and values excentury uses for",
"reason we must try to catch anything that # may",
"files. To see the values that the configuration file can",
"\"\"\" RE = re.compile(r'\\${(?P<key>.*?)}') RE_IF = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]' )",
"if enum == 1: continue if cond: val = match.group('iftrue')",
"= RE_IF.match(val) if match: cond, enum = _eval_condition( match.group('cond'), arg,",
"except KeyError: pass return def _update_single(cfg, name, defaults=None): \"Helper function",
"_eval_condition( match.group('cond'), arg, data, line_num, fname ) if enum ==",
"error(\"ERROR: '%s' is not of the form sec.key\\n\" % arg.var)",
"% namespace.cfg) with open('%s/xcpp.config' % namespace.cfg, 'r') as _fp: disp(_fp.read())",
"they may be easy to spot in a configuration file.",
"else: match = RE_IF.match(val) if match: cond, enum = _eval_condition(",
"number: 0 if everything is fine, 1 if there was",
"names: cfg[name] = dict() _update_single(cfg, name) _update_from_file(cfg, name, cfg_file) else:",
"values excentury uses for the given command. \"\"\" RE =",
"spot in a configuration file. def _eval_condition(cond, ARG, CFG, line_num,",
") return cond, enum def _read_config(fname, arg): \"\"\"Simple parser to",
"dict(key_val) replacement_function = lambda match: replace_dict[match.group(0)] pattern = re.compile(\"|\".join([re.escape(k) for",
"cond = eval(cond) enum = 0 # pylint: disable=broad-except #",
"the convention # so that they may be easy to",
"a configuration file for excentury. Some actions performed by excentury",
"_update_from_arg(cfg, argdict, key): \"Helper function for get_cfg.\" for var in",
"r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]' ) RE_IFELSE = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]ELSE (?P<iffalse>.*)' )",
"= argdict[var] def get_cfg(arg, names, defaults=None): \"\"\"Obtain the settings for",
"# access to the current configuration. Note that using CFG[key][sec]",
"form sec.key\\n\" % arg.var) try: disp(config[command][var]+'\\n') except KeyError: pass return",
"var in cfg[key]: if var in argdict and argdict[var] is",
"token.split(':') tval = '' if tsec in data: if tkey",
"use the `defaults` command. This will print a list of",
"and CFG gives us # access to the current configuration.",
"'<'), ('&', '&')) 'a < b && b < c'",
"\"\"\" replacements = list() for token in tokens: if ':'",
"data[sec]: tval = data[sec][token] else: tval = '' replacements.append( ('${%s}'",
"in line: tmp = line.split('=', 1) key = tmp[0].strip() val",
"data[tsec]: tval = data[tsec][tkey] else: if token in data[sec]: tval",
"function. We could have use # a python file as",
"data, line_num, fname ) if enum == 1: continue if",
"equivalent to ${key:sec}. These names go against the convention #",
"import error, trace, import_mod DESC = \"\"\"Edit a configuration file",
"function but it does not add the newline character. \"\"\"",
"read configuration files. \"\"\" data = OrderedDict() sec = None",
"<http://stackoverflow.com/a/15221068/788553> \"\"\" replace_dict = dict(key_val) replacement_function = lambda match: replace_dict[match.group(0)]",
"val = replace(val, *replacements) match = RE_IFELSE.match(val) if match: cond,",
"of the form sec.key\\n\" % arg.var) try: disp(config[command][var]+'\\n') except KeyError:",
"import re import sys import textwrap import argparse from collections",
"'%s/%s/%s' % (ARG.cfg, CFG['xcpp']['path'], ARG.inputfile) try: # pylint: disable=eval-used #",
"if 'XCPP_CONFIG_PATH' in os.environ: tmp_path = os.environ['XCPP_CONFIG_PATH'] if os.path.exists('%s/xcpp.config' %",
"be able to evaluate a condition without creating a whole",
"c\", ('<', '<'), ('&', '&')) 'a < b && b",
"0 with open(fname, 'r') as fhandle: for line in fhandle:",
"but then there would be # no simple structure to",
"the configuration file can overwrite use the `defaults` command. This",
"disable=broad-except # Anything can go wrong during the execution of",
"to the main subparser. \" tmpp = subp.add_parser('config', help='configure excentury',",
"None: for sec in config: disp('[%s]\\n' % sec) for key",
"arg) except IOError: config = OrderedDict() return config def run(arg):",
"defaults.iteritems(): cfg[name][var] = os.path.expandvars(str(val)) else: mod = import_mod('excentury.command.%s' % name)",
"in %r\\n' % namespace.cfg) else: disp('path to xcpp.config: \"%s\"\\n' %",
"get_cfg.\" if name in cfg_file: for var, val in cfg_file[name].iteritems():",
"not os.path.exists('%s/xcpp.config' % path): error(\"ERROR: %s/xcpp.config does not exist\\n\" %",
"\"Helper function for get_cfg.\" for var in cfg[key]: if var",
"return try: command, var = arg.var.split('.', 1) except ValueError: error(\"ERROR:",
"for the given command. \"\"\" RE = re.compile(r'\\${(?P<key>.*?)}') RE_IF =",
"in one pass. Example: >>> replace(\"a < b && b",
"cfg: _update_from_arg(cfg, argdict, arg.parser_name) elif arg.parser_name == 'to' and arg.lang",
"isinstance(names, list): for name in names: cfg[name] = dict() _update_single(cfg,",
"a parser to the main subparser. \" tmpp = subp.add_parser('config',",
"nargs='?', default=None, help='Must be in the form of sec.key') tmpp.add_argument('-v',",
"if cond else groups[2] else: match = RE_IF.match(val) if match:",
"= '%s/%s/%s' % (ARG.cfg, CFG['xcpp']['path'], ARG.inputfile) try: # pylint: disable=eval-used",
"defaults) _update_from_file(cfg, names, cfg_file) argdict = vars(arg) if arg.parser_name in",
"line_num, fname ) if enum == 1: continue groups =",
"name) if hasattr(mod, \"DEFAULTS\"): for var, val in mod.DEFAULTS.iteritems(): cfg[name][var]",
"configuration file. # ARG gives us access to the command",
"a configuration file. def _eval_condition(cond, ARG, CFG, line_num, fname): \"\"\"Evaluates",
"{ 'xcpp': { 'root': '.', 'path': '.' } } cfg_file",
"None line_num = 0 with open(fname, 'r') as fhandle: for",
"None enum = 1 trace( 'WARNING: error in line %d",
"arg.parser_name) elif arg.parser_name == 'to' and arg.lang in cfg: _update_from_arg(cfg,",
"\"\"\"Run command. \"\"\" config = read_config(arg) if arg.v: disp('path to",
"to the command line arguments and CFG gives us #",
"catch anything that # may come our way so that",
"names that may be used in the configuration file. #",
"data[sec][token] else: tval = '' replacements.append( ('${%s}' % token, tval)",
"names != 'xcpp': cfg[names] = dict() _update_single(cfg, names, defaults) _update_from_file(cfg,",
"try: read_config(namespace) except IOError: disp('xcpp.config not found in %r\\n' %",
"be in the form of sec.key') tmpp.add_argument('-v', action='store_true', help='print config",
"'xcpp': cfg[names] = dict() _update_single(cfg, names, defaults) _update_from_file(cfg, names, cfg_file)",
"there would be # no simple structure to the files.",
"%s\\n' % ( line_num, fname, exception.message ) ) return cond,",
"of the evaluation and an error number: 0 if everything",
"for key in config[sec]: disp(' %s = %s\\n' % (key,",
"line[0] == '[': sec = line[1:-2] data[sec] = OrderedDict() elif",
"match.group('iftrue') else: continue data[sec][key] = val return data def read_config(arg):",
"file. # ARG gives us access to the command line",
"the command line arguments and CFG gives us # access",
"trace, import_mod DESC = \"\"\"Edit a configuration file for excentury.",
"b < c' Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" return _replacer(*key_val)(string) class ConfigDispAction(argparse.Action):",
"1 if line[0] == '[': sec = line[1:-2] data[sec] =",
"'[': sec = line[1:-2] data[sec] = OrderedDict() elif '=' in",
"token in data[sec]: tval = data[sec][token] else: tval = ''",
"disp(_fp.read()) exit(0) def add_parser(subp, raw): \"Add a parser to the",
"+= 1 if line[0] == '[': sec = line[1:-2] data[sec]",
"= os.path.expandvars(val) cfg['xcpp']['root'] = arg.cfg if isinstance(names, list): for name",
"it does not add the newline character. \"\"\" sys.stdout.write(msg) def",
"tval = data[sec][token] else: tval = '' replacements.append( ('${%s}' %",
"list() for token in tokens: if ':' in token: tsec,",
"file. def _eval_condition(cond, ARG, CFG, line_num, fname): \"\"\"Evaluates a string",
"== 1: continue if cond: val = match.group('iftrue') else: continue",
"a command. \"\"\" cfg = { 'xcpp': { 'root': '.',",
"else: if names != 'xcpp': cfg[names] = dict() _update_single(cfg, names,",
"'=' in line: tmp = line.split('=', 1) key = tmp[0].strip()",
"configuration file can overwrite use the `defaults` command. This will",
"re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]ELSE (?P<iffalse>.*)' ) def disp(msg): \"\"\"Wrapper around sys.stdout.write",
"trace( 'WARNING: error in line %d of %r: %s\\n' %",
"the necessary settings to the rest of the modules in",
"raw): \"Add a parser to the main subparser. \" tmpp",
"strings done in one pass. Example: >>> replace(\"a < b",
"by excentury can be overwritten by using configuration files. To",
"sec.key') tmpp.add_argument('-v', action='store_true', help='print config file location') tmpp.add_argument('--print', action=ConfigDispAction, nargs=0,",
"# no simple structure to the files. cond = eval(cond)",
"in fhandle: line_num += 1 if line[0] == '[': sec",
"tval = '' if tsec in data: if tkey in",
"if there was an error. \"\"\" ARG.FILEPATH = '%s/%s/%s' %",
"'%s/xcpp.config'\\n\" % tmp_path) path = tmp_path elif not os.path.exists('%s/xcpp.config' %",
"does not add the newline character. \"\"\" sys.stdout.write(msg) def _replacer(*key_val):",
"_update_from_file(cfg, name, cfg_file) else: if names != 'xcpp': cfg[names] =",
"can use the eval function. We could have use #",
"subp.add_parser('config', help='configure excentury', formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('var', type=str, nargs='?', default=None, help='Must",
"overwrite use the `defaults` command. This will print a list",
"('<', '<'), ('&', '&')) 'a < b && b <",
"the files. cond = eval(cond) enum = 0 # pylint:",
"< b && b < c\", ('<', '<'), ('&', '&'))",
"(key, config[sec][key])) disp('\\n') return try: command, var = arg.var.split('.', 1)",
"name, defaults=None): \"Helper function for get_cfg.\" if defaults: for var,",
"replacements = _get_replacements( RE.findall(val), data, sec ) # pylint: disable=star-args",
"RE.findall(val), data, sec ) # pylint: disable=star-args if replacements: val",
"ARG.inputfile) try: # pylint: disable=eval-used # To be able to",
"in cfg: _update_from_arg(cfg, argdict, arg.parser_name) elif arg.parser_name == 'to' and",
"disable=invalid-name # ARG and CFG are names that may be",
"disp(msg): \"\"\"Wrapper around sys.stdout.write which is meant to behave as",
"% (key, config[sec][key])) disp('\\n') return try: command, var = arg.var.split('.',",
"'a < b && b < c' Source: <http://stackoverflow.com/a/15221068/788553> \"\"\"",
"tmp_path): trace(\"Configured with: '%s/xcpp.config'\\n\" % tmp_path) path = tmp_path elif",
"not exist\\n\" % path) arg.cfg = path try: config =",
"may be used in the configuration file. # ARG gives",
"excentury can be overwritten by using configuration files. To see",
"== '[': sec = line[1:-2] data[sec] = OrderedDict() elif '='",
"message # and ignore it. except Exception as exception: cond",
"vars(arg) if arg.parser_name in cfg: _update_from_arg(cfg, argdict, arg.parser_name) elif arg.parser_name",
"Anything can go wrong during the execution of the `eval`",
"the print function but it does not add the newline",
"= 0 # pylint: disable=broad-except # Anything can go wrong",
"Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" replace_dict = dict(key_val) replacement_function = lambda match:",
"with: '%s/xcpp.config'\\n\" % tmp_path) path = tmp_path elif not os.path.exists('%s/xcpp.config'",
"'root': '.', 'path': '.' } } cfg_file = read_config(arg) if",
"cfg_file: for var, val in cfg_file['xcpp'].iteritems(): cfg['xcpp'][var] = os.path.expandvars(val) cfg['xcpp']['root']",
"= re.compile(r'\\${(?P<key>.*?)}') RE_IF = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]' ) RE_IFELSE =",
"continue data[sec][key] = val return data def read_config(arg): \"\"\"Read the",
"excentury.command import error, trace, import_mod DESC = \"\"\"Edit a configuration",
"path == '.' and not os.path.exists('xcpp.config'): if 'XCPP_CONFIG_PATH' in os.environ:",
"key in config[sec]: disp(' %s = %s\\n' % (key, config[sec][key]))",
"can be overwritten by using configuration files. To see the",
"are names that may be used in the configuration file.",
"# new parser we can use the eval function. We",
"file and exit') def _get_replacements(tokens, data, sec): \"\"\"Helper function for",
"except Exception as exception: cond = None enum = 1",
"These names go against the convention # so that they",
"cfg_file: for var, val in cfg_file[name].iteritems(): cfg[name][var] = os.path.expandvars(val) def",
"will print a list of the keys and values excentury",
"} } cfg_file = read_config(arg) if 'xcpp' in cfg_file: for",
"may give out a warning message # and ignore it.",
"('${%s}' % token, tval) ) return replacements # pylint: disable=invalid-name",
"token in tokens: if ':' in token: tsec, tkey =",
"def _update_single(cfg, name, defaults=None): \"Helper function for get_cfg.\" if defaults:",
"% token, tval) ) return replacements # pylint: disable=invalid-name #",
"elif arg.parser_name == 'to' and arg.lang in cfg: _update_from_arg(cfg, argdict,",
"our way so that we may give out a warning",
"config[sec]: disp(' %s = %s\\n' % (key, config[sec][key])) disp('\\n') return",
"in charge of providing all the necessary settings to the",
"of providing all the necessary settings to the rest of",
"of the modules in excentury. \"\"\" import os import re",
"class ConfigDispAction(argparse.Action): # pylint: disable=R0903 \"\"\"Derived argparse Action class to",
"if line[0] == '[': sec = line[1:-2] data[sec] = OrderedDict()",
"# Anything can go wrong during the execution of the",
"\"DEFAULTS\"): for var, val in mod.DEFAULTS.iteritems(): cfg[name][var] = os.path.expandvars(val) def",
"replacements = list() for token in tokens: if ':' in",
"configuration. Note that using CFG[key][sec] # is equivalent to ${key:sec}.",
"line_num += 1 if line[0] == '[': sec = line[1:-2]",
"in excentury. \"\"\" import os import re import sys import",
"\"\"\" replace_dict = dict(key_val) replacement_function = lambda match: replace_dict[match.group(0)] pattern",
"the main subparser. \" tmpp = subp.add_parser('config', help='configure excentury', formatter_class=raw,",
"\"\"\" cfg = { 'xcpp': { 'root': '.', 'path': '.'",
"to the rest of the modules in excentury. \"\"\" import",
"_get_replacements(tokens, data, sec): \"\"\"Helper function for _read_config. \"\"\" replacements =",
"replace_dict[match.group(0)] pattern = re.compile(\"|\".join([re.escape(k) for k, _ in key_val]), re.M)",
"key): \"Helper function for get_cfg.\" for var in cfg[key]: if",
"fhandle: for line in fhandle: line_num += 1 if line[0]",
"\"\"\" data = OrderedDict() sec = None line_num = 0",
"list): for name in names: cfg[name] = dict() _update_single(cfg, name)",
"arg): \"\"\"Simple parser to read configuration files. \"\"\" data =",
"tmp_path elif not os.path.exists('%s/xcpp.config' % path): error(\"ERROR: %s/xcpp.config does not",
"and ignore it. except Exception as exception: cond = None",
"= dict() _update_single(cfg, name) _update_from_file(cfg, name, cfg_file) else: if names",
"For this reason we must try to catch anything that",
"the `eval` # function. For this reason we must try",
"the form of sec.key') tmpp.add_argument('-v', action='store_true', help='print config file location')",
"without creating a whole # new parser we can use",
"files. cond = eval(cond) enum = 0 # pylint: disable=broad-except",
"xcpp.config: \"%s\"\\n' % namespace.cfg) with open('%s/xcpp.config' % namespace.cfg, 'r') as",
"RE = re.compile(r'\\${(?P<key>.*?)}') RE_IF = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]' ) RE_IFELSE",
"values, option_string=None): try: read_config(namespace) except IOError: disp('xcpp.config not found in",
"python file as a configuration but then there would be",
"import_mod('excentury.command.%s' % name) if hasattr(mod, \"DEFAULTS\"): for var, val in",
") ) return cond, enum def _read_config(fname, arg): \"\"\"Simple parser",
"_update_from_arg(cfg, argdict, arg.parser_name) elif arg.parser_name == 'to' and arg.lang in",
"configuration files. To see the values that the configuration file",
"def _replacer(*key_val): \"\"\"Helper function for replace. Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" replace_dict",
"RE_IF = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]' ) RE_IFELSE = re.compile( r'(?P<iftrue>.*?)",
"RE_IFELSE.match(val) if match: cond, enum = _eval_condition( match.group('cond'), arg, data,",
"ARG and CFG are names that may be used in",
"values that the configuration file can overwrite use the `defaults`",
"be overwritten by using configuration files. To see the values",
"print a list of the keys and values excentury uses",
"namespace.cfg) with open('%s/xcpp.config' % namespace.cfg, 'r') as _fp: disp(_fp.read()) exit(0)",
"'' if tsec in data: if tkey in data[tsec]: tval",
"config[sec][key])) disp('\\n') return try: command, var = arg.var.split('.', 1) except",
"get_cfg(arg, names, defaults=None): \"\"\"Obtain the settings for a command. \"\"\"",
"%d of %r: %s\\n' % ( line_num, fname, exception.message )",
"using configuration files. To see the values that the configuration",
"to behave as the print function but it does not",
"arg.cfg if isinstance(names, list): for name in names: cfg[name] =",
"hasattr(mod, \"DEFAULTS\"): for var, val in mod.DEFAULTS.iteritems(): cfg[name][var] = os.path.expandvars(val)",
"a configuration but then there would be # no simple",
"with open(fname, 'r') as fhandle: for line in fhandle: line_num",
"= OrderedDict() elif '=' in line: tmp = line.split('=', 1)",
"for token in tokens: if ':' in token: tsec, tkey",
"(ARG.cfg, CFG['xcpp']['path'], ARG.inputfile) try: # pylint: disable=eval-used # To be",
"in config: disp('[%s]\\n' % sec) for key in config[sec]: disp('",
"dict() _update_single(cfg, names, defaults) _update_from_file(cfg, names, cfg_file) argdict = vars(arg)",
"match = RE_IF.match(val) if match: cond, enum = _eval_condition( match.group('cond'),",
"one pass. Example: >>> replace(\"a < b && b <",
"option_string=None): try: read_config(namespace) except IOError: disp('xcpp.config not found in %r\\n'",
"location') tmpp.add_argument('--print', action=ConfigDispAction, nargs=0, help='print config file and exit') def",
"pass. Example: >>> replace(\"a < b && b < c\",",
"of sec.key') tmpp.add_argument('-v', action='store_true', help='print config file location') tmpp.add_argument('--print', action=ConfigDispAction,",
"a whole # new parser we can use the eval",
"line[1:-2] data[sec] = OrderedDict() elif '=' in line: tmp =",
"tmp[1].strip() val = os.path.expandvars(val) replacements = _get_replacements( RE.findall(val), data, sec",
"ValueError: error(\"ERROR: '%s' is not of the form sec.key\\n\" %",
"in cfg[key]: if var in argdict and argdict[var] is not",
"IOError: config = OrderedDict() return config def run(arg): \"\"\"Run command.",
"help='print config file and exit') def _get_replacements(tokens, data, sec): \"\"\"Helper",
"function. For this reason we must try to catch anything",
"enum = 1 trace( 'WARNING: error in line %d of",
"Example: >>> replace(\"a < b && b < c\", ('<',",
"function. It prints a warning if there are any errors.",
"evaluate a condition without creating a whole # new parser",
"= os.path.expandvars(val) def _update_from_arg(cfg, argdict, key): \"Helper function for get_cfg.\"",
"is meant to behave as the print function but it",
"% path): error(\"ERROR: %s/xcpp.config does not exist\\n\" % path) arg.cfg",
"disp('\\n') return try: command, var = arg.var.split('.', 1) except ValueError:",
"(?P<iffalse>.*)' ) def disp(msg): \"\"\"Wrapper around sys.stdout.write which is meant",
"groups = match.groups() val = groups[0] if cond else groups[2]",
"data def read_config(arg): \"\"\"Read the configuration file xcpp.config\"\"\" path =",
"cfg = { 'xcpp': { 'root': '.', 'path': '.' }",
"replacement_function = lambda match: replace_dict[match.group(0)] pattern = re.compile(\"|\".join([re.escape(k) for k,",
"= lambda match: replace_dict[match.group(0)] pattern = re.compile(\"|\".join([re.escape(k) for k, _",
"disable=R0903 \"\"\"Derived argparse Action class to use when displaying the",
"return data def read_config(arg): \"\"\"Read the configuration file xcpp.config\"\"\" path",
"val in mod.DEFAULTS.iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_file(cfg, name, cfg_file):",
"read_config(arg) if arg.v: disp('path to xcpp.config: \"%s\"\\n' % arg.cfg) if",
"= '' if tsec in data: if tkey in data[tsec]:",
"pattern = re.compile(\"|\".join([re.escape(k) for k, _ in key_val]), re.M) return",
"command line arguments and CFG gives us # access to",
"% tmp_path) path = tmp_path elif not os.path.exists('%s/xcpp.config' % path):",
"new parser we can use the eval function. We could",
"if os.path.exists('%s/xcpp.config' % tmp_path): trace(\"Configured with: '%s/xcpp.config'\\n\" % tmp_path) path",
"= token.split(':') tval = '' if tsec in data: if",
"in token: tsec, tkey = token.split(':') tval = '' if",
"except IOError: disp('xcpp.config not found in %r\\n' % namespace.cfg) else:",
"of the `eval` # function. For this reason we must",
"Action class to use when displaying the configuration file and",
"in data[sec]: tval = data[sec][token] else: tval = '' replacements.append(",
"CFG, line_num, fname): \"\"\"Evaluates a string using the eval function.",
"sec in config: disp('[%s]\\n' % sec) for key in config[sec]:",
"= os.path.expandvars(val) def _update_from_file(cfg, name, cfg_file): \"Helper function for get_cfg.\"",
"names, defaults) _update_from_file(cfg, names, cfg_file) argdict = vars(arg) if arg.parser_name",
"os.path.expandvars(val) cfg['xcpp']['root'] = arg.cfg if isinstance(names, list): for name in",
"sys.stdout.write(msg) def _replacer(*key_val): \"\"\"Helper function for replace. Source: <http://stackoverflow.com/a/15221068/788553> \"\"\"",
"< c' Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" return _replacer(*key_val)(string) class ConfigDispAction(argparse.Action): #",
"open(fname, 'r') as fhandle: for line in fhandle: line_num +=",
"help='Must be in the form of sec.key') tmpp.add_argument('-v', action='store_true', help='print",
"1 trace( 'WARNING: error in line %d of %r: %s\\n'",
"not os.path.exists('xcpp.config'): if 'XCPP_CONFIG_PATH' in os.environ: tmp_path = os.environ['XCPP_CONFIG_PATH'] if",
"there are any errors. Returns the result of the evaluation",
"name, cfg_file): \"Helper function for get_cfg.\" if name in cfg_file:",
"argdict, key): \"Helper function for get_cfg.\" for var in cfg[key]:",
"settings to the rest of the modules in excentury. \"\"\"",
"path): error(\"ERROR: %s/xcpp.config does not exist\\n\" % path) arg.cfg =",
"may be easy to spot in a configuration file. def",
"using the eval function. It prints a warning if there",
"cond, enum def _read_config(fname, arg): \"\"\"Simple parser to read configuration",
"val in cfg_file['xcpp'].iteritems(): cfg['xcpp'][var] = os.path.expandvars(val) cfg['xcpp']['root'] = arg.cfg if",
"with open('%s/xcpp.config' % namespace.cfg, 'r') as _fp: disp(_fp.read()) exit(0) def",
"the eval function. It prints a warning if there are",
"match.groups() val = groups[0] if cond else groups[2] else: match",
"return _replacer(*key_val)(string) class ConfigDispAction(argparse.Action): # pylint: disable=R0903 \"\"\"Derived argparse Action",
"found in %r\\n' % namespace.cfg) else: disp('path to xcpp.config: \"%s\"\\n'",
"def __call__(self, parser, namespace, values, option_string=None): try: read_config(namespace) except IOError:",
"b && b < c\", ('<', '<'), ('&', '&')) 'a",
"arg.var.split('.', 1) except ValueError: error(\"ERROR: '%s' is not of the",
"as _fp: disp(_fp.read()) exit(0) def add_parser(subp, raw): \"Add a parser",
"= arg.cfg if path == '.' and not os.path.exists('xcpp.config'): if",
"if tsec in data: if tkey in data[tsec]: tval =",
"textwrap import argparse from collections import OrderedDict from excentury.command import",
"action=ConfigDispAction, nargs=0, help='print config file and exit') def _get_replacements(tokens, data,",
"exception.message ) ) return cond, enum def _read_config(fname, arg): \"\"\"Simple",
"enum == 1: continue groups = match.groups() val = groups[0]",
"os import re import sys import textwrap import argparse from",
"= \"\"\"Edit a configuration file for excentury. Some actions performed",
"providing all the necessary settings to the rest of the",
"mod.DEFAULTS.iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_file(cfg, name, cfg_file): \"Helper function",
"'r') as _fp: disp(_fp.read()) exit(0) def add_parser(subp, raw): \"Add a",
"OrderedDict from excentury.command import error, trace, import_mod DESC = \"\"\"Edit",
"os.path.expandvars(val) def _update_from_file(cfg, name, cfg_file): \"Helper function for get_cfg.\" if",
"DESC = \"\"\"Edit a configuration file for excentury. Some actions",
"= import_mod('excentury.command.%s' % name) if hasattr(mod, \"DEFAULTS\"): for var, val",
"% (ARG.cfg, CFG['xcpp']['path'], ARG.inputfile) try: # pylint: disable=eval-used # To",
"to the files. cond = eval(cond) enum = 0 #",
"try: config = _read_config('%s/xcpp.config' % path, arg) except IOError: config",
"in cfg: _update_from_arg(cfg, argdict, arg.lang) _update_from_arg(cfg, argdict, 'xcpp') return cfg",
"warning message # and ignore it. except Exception as exception:",
"disp('xcpp.config not found in %r\\n' % namespace.cfg) else: disp('path to",
"data, sec ) # pylint: disable=star-args if replacements: val =",
"nargs=0, help='print config file and exit') def _get_replacements(tokens, data, sec):",
"of %r: %s\\n' % ( line_num, fname, exception.message ) )",
"b < c\", ('<', '<'), ('&', '&')) 'a < b",
"= match.groups() val = groups[0] if cond else groups[2] else:",
"OrderedDict() elif '=' in line: tmp = line.split('=', 1) key",
"arg.parser_name in cfg: _update_from_arg(cfg, argdict, arg.parser_name) elif arg.parser_name == 'to'",
"if arg.parser_name in cfg: _update_from_arg(cfg, argdict, arg.parser_name) elif arg.parser_name ==",
"path = tmp_path elif not os.path.exists('%s/xcpp.config' % path): error(\"ERROR: %s/xcpp.config",
"file as a configuration but then there would be #",
"a warning message # and ignore it. except Exception as",
"have use # a python file as a configuration but",
"import sys import textwrap import argparse from collections import OrderedDict",
"names, cfg_file) argdict = vars(arg) if arg.parser_name in cfg: _update_from_arg(cfg,",
"'' replacements.append( ('${%s}' % token, tval) ) return replacements #",
"os.path.exists('xcpp.config'): if 'XCPP_CONFIG_PATH' in os.environ: tmp_path = os.environ['XCPP_CONFIG_PATH'] if os.path.exists('%s/xcpp.config'",
"the modules in excentury. \"\"\" import os import re import",
"gives us access to the command line arguments and CFG",
"error(\"ERROR: %s/xcpp.config does not exist\\n\" % path) arg.cfg = path",
"run(arg): \"\"\"Run command. \"\"\" config = read_config(arg) if arg.v: disp('path",
"fname ) if enum == 1: continue if cond: val",
"argdict[var] def get_cfg(arg, names, defaults=None): \"\"\"Obtain the settings for a",
") RE_IFELSE = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]ELSE (?P<iffalse>.*)' ) def disp(msg):",
"rest of the modules in excentury. \"\"\" import os import",
"lambda string: pattern.sub(replacement_function, string) def replace(string, *key_val): \"\"\"Replacement of strings",
"b && b < c' Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" return _replacer(*key_val)(string)",
"excentury', formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('var', type=str, nargs='?', default=None, help='Must be in",
"cfg[name] = dict() _update_single(cfg, name) _update_from_file(cfg, name, cfg_file) else: if",
"IOError: disp('xcpp.config not found in %r\\n' % namespace.cfg) else: disp('path",
"ARG gives us access to the command line arguments and",
"cfg_file[name].iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_arg(cfg, argdict, key): \"Helper function",
"try to catch anything that # may come our way",
"string using the eval function. It prints a warning if",
"\"Helper function for get_cfg.\" if name in cfg_file: for var,",
"% ( line_num, fname, exception.message ) ) return cond, enum",
"in the form of sec.key') tmpp.add_argument('-v', action='store_true', help='print config file",
"val = match.group('iftrue') else: continue data[sec][key] = val return data",
"the execution of the `eval` # function. For this reason",
"('&', '&')) 'a < b && b < c' Source:",
"pylint: disable=eval-used # To be able to evaluate a condition",
"for k, _ in key_val]), re.M) return lambda string: pattern.sub(replacement_function,",
"name in names: cfg[name] = dict() _update_single(cfg, name) _update_from_file(cfg, name,",
"there was an error. \"\"\" ARG.FILEPATH = '%s/%s/%s' % (ARG.cfg,",
"line_num = 0 with open(fname, 'r') as fhandle: for line",
"the given command. \"\"\" RE = re.compile(r'\\${(?P<key>.*?)}') RE_IF = re.compile(",
"command. \"\"\" cfg = { 'xcpp': { 'root': '.', 'path':",
"enum = 0 # pylint: disable=broad-except # Anything can go",
"anything that # may come our way so that we",
"performed by excentury can be overwritten by using configuration files.",
"&& b < c' Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" return _replacer(*key_val)(string) class",
"# To be able to evaluate a condition without creating",
"if isinstance(names, list): for name in names: cfg[name] = dict()",
"cfg[name][var] = os.path.expandvars(val) def _update_from_arg(cfg, argdict, key): \"Helper function for",
"done in one pass. Example: >>> replace(\"a < b &&",
"as the print function but it does not add the",
"&& b < c\", ('<', '<'), ('&', '&')) 'a <",
"var, val in cfg_file[name].iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_arg(cfg, argdict,",
"that they may be easy to spot in a configuration",
"the keys and values excentury uses for the given command.",
"for excentury. Some actions performed by excentury can be overwritten",
"to xcpp.config: \"%s\"\\n' % namespace.cfg) with open('%s/xcpp.config' % namespace.cfg, 'r')",
"':' in token: tsec, tkey = token.split(':') tval = ''",
"= tmp[0].strip() val = tmp[1].strip() val = os.path.expandvars(val) replacements =",
"path try: config = _read_config('%s/xcpp.config' % path, arg) except IOError:",
"in key_val]), re.M) return lambda string: pattern.sub(replacement_function, string) def replace(string,",
"string: pattern.sub(replacement_function, string) def replace(string, *key_val): \"\"\"Replacement of strings done",
"val return data def read_config(arg): \"\"\"Read the configuration file xcpp.config\"\"\"",
"Note that using CFG[key][sec] # is equivalent to ${key:sec}. These",
"def _read_config(fname, arg): \"\"\"Simple parser to read configuration files. \"\"\"",
"keys and values excentury uses for the given command. \"\"\"",
"is equivalent to ${key:sec}. These names go against the convention",
"names go against the convention # so that they may",
"var, val in cfg_file['xcpp'].iteritems(): cfg['xcpp'][var] = os.path.expandvars(val) cfg['xcpp']['root'] = arg.cfg",
"that # may come our way so that we may",
"\"\"\"Evaluates a string using the eval function. It prints a",
"os.environ: tmp_path = os.environ['XCPP_CONFIG_PATH'] if os.path.exists('%s/xcpp.config' % tmp_path): trace(\"Configured with:",
"from collections import OrderedDict from excentury.command import error, trace, import_mod",
"replacements.append( ('${%s}' % token, tval) ) return replacements # pylint:",
"and an error number: 0 if everything is fine, 1",
"behave as the print function but it does not add",
"\"\"\"Edit a configuration file for excentury. Some actions performed by",
"charge of providing all the necessary settings to the rest",
"used in the configuration file. # ARG gives us access",
"creating a whole # new parser we can use the",
"name in cfg_file: for var, val in cfg_file[name].iteritems(): cfg[name][var] =",
"\"\"\"Obtain the settings for a command. \"\"\" cfg = {",
"that may be used in the configuration file. # ARG",
"a string using the eval function. It prints a warning",
"give out a warning message # and ignore it. except",
"we may give out a warning message # and ignore",
"files. \"\"\" data = OrderedDict() sec = None line_num =",
"pylint: disable=R0903 \"\"\"Derived argparse Action class to use when displaying",
"r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]ELSE (?P<iffalse>.*)' ) def disp(msg): \"\"\"Wrapper around sys.stdout.write which",
"the settings for a command. \"\"\" cfg = { 'xcpp':",
"= arg.var.split('.', 1) except ValueError: error(\"ERROR: '%s' is not of",
"val in defaults.iteritems(): cfg[name][var] = os.path.expandvars(str(val)) else: mod = import_mod('excentury.command.%s'",
"pylint: disable=invalid-name # ARG and CFG are names that may",
"disp('path to xcpp.config: \"%s\"\\n' % arg.cfg) if arg.var is None:",
"data[sec][key] = val return data def read_config(arg): \"\"\"Read the configuration",
"c' Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" return _replacer(*key_val)(string) class ConfigDispAction(argparse.Action): # pylint:",
"eval function. We could have use # a python file",
"warning if there are any errors. Returns the result of",
"elif '=' in line: tmp = line.split('=', 1) key =",
"is in charge of providing all the necessary settings to",
"import argparse from collections import OrderedDict from excentury.command import error,",
"form of sec.key') tmpp.add_argument('-v', action='store_true', help='print config file location') tmpp.add_argument('--print',",
"\"\"\" import os import re import sys import textwrap import",
"add_parser(subp, raw): \"Add a parser to the main subparser. \"",
"type=str, nargs='?', default=None, help='Must be in the form of sec.key')",
"else: tval = '' replacements.append( ('${%s}' % token, tval) )",
"errors. Returns the result of the evaluation and an error",
"command, var = arg.var.split('.', 1) except ValueError: error(\"ERROR: '%s' is",
"settings for a command. \"\"\" cfg = { 'xcpp': {",
"Some actions performed by excentury can be overwritten by using",
"'xcpp': { 'root': '.', 'path': '.' } } cfg_file =",
"key = tmp[0].strip() val = tmp[1].strip() val = os.path.expandvars(val) replacements",
"def get_cfg(arg, names, defaults=None): \"\"\"Obtain the settings for a command.",
"modules in excentury. \"\"\" import os import re import sys",
"main subparser. \" tmpp = subp.add_parser('config', help='configure excentury', formatter_class=raw, description=textwrap.dedent(DESC))",
"sys import textwrap import argparse from collections import OrderedDict from",
"of the keys and values excentury uses for the given",
"sec = line[1:-2] data[sec] = OrderedDict() elif '=' in line:",
"_eval_condition(cond, ARG, CFG, line_num, fname): \"\"\"Evaluates a string using the",
"match: cond, enum = _eval_condition( match.group('cond'), arg, data, line_num, fname",
"exist\\n\" % path) arg.cfg = path try: config = _read_config('%s/xcpp.config'",
"cfg['xcpp']['root'] = arg.cfg if isinstance(names, list): for name in names:",
"file for excentury. Some actions performed by excentury can be",
"match: replace_dict[match.group(0)] pattern = re.compile(\"|\".join([re.escape(k) for k, _ in key_val]),",
"module is in charge of providing all the necessary settings",
"an error number: 0 if everything is fine, 1 if",
"so that they may be easy to spot in a",
"# pylint: disable=broad-except # Anything can go wrong during the",
"`defaults` command. This will print a list of the keys",
"if var in argdict and argdict[var] is not None: cfg[key][var]",
"# pylint: disable=invalid-name # ARG and CFG are names that",
"def _eval_condition(cond, ARG, CFG, line_num, fname): \"\"\"Evaluates a string using",
"a condition without creating a whole # new parser we",
"OrderedDict() sec = None line_num = 0 with open(fname, 'r')",
"# is equivalent to ${key:sec}. These names go against the",
"%r: %s\\n' % ( line_num, fname, exception.message ) ) return",
"disable=star-args if replacements: val = replace(val, *replacements) match = RE_IFELSE.match(val)",
"_update_single(cfg, name, defaults=None): \"Helper function for get_cfg.\" if defaults: for",
"!= 'xcpp': cfg[names] = dict() _update_single(cfg, names, defaults) _update_from_file(cfg, names,",
"_get_replacements( RE.findall(val), data, sec ) # pylint: disable=star-args if replacements:",
"% tmp_path): trace(\"Configured with: '%s/xcpp.config'\\n\" % tmp_path) path = tmp_path",
"does not exist\\n\" % path) arg.cfg = path try: config",
"= { 'xcpp': { 'root': '.', 'path': '.' } }",
"% sec) for key in config[sec]: disp(' %s = %s\\n'",
"1 if there was an error. \"\"\" ARG.FILEPATH = '%s/%s/%s'",
"sys.stdout.write which is meant to behave as the print function",
"for var, val in cfg_file['xcpp'].iteritems(): cfg['xcpp'][var] = os.path.expandvars(val) cfg['xcpp']['root'] =",
"exception: cond = None enum = 1 trace( 'WARNING: error",
"if names != 'xcpp': cfg[names] = dict() _update_single(cfg, names, defaults)",
"evaluation and an error number: 0 if everything is fine,",
"groups[0] if cond else groups[2] else: match = RE_IF.match(val) if",
"line %d of %r: %s\\n' % ( line_num, fname, exception.message",
"try: disp(config[command][var]+'\\n') except KeyError: pass return def _update_single(cfg, name, defaults=None):",
"arg.cfg = path try: config = _read_config('%s/xcpp.config' % path, arg)",
"_update_single(cfg, names, defaults) _update_from_file(cfg, names, cfg_file) argdict = vars(arg) if",
"tkey in data[tsec]: tval = data[tsec][tkey] else: if token in",
"class to use when displaying the configuration file and location.\"\"\"",
"to the current configuration. Note that using CFG[key][sec] # is",
"continue if cond: val = match.group('iftrue') else: continue data[sec][key] =",
"def _update_from_file(cfg, name, cfg_file): \"Helper function for get_cfg.\" if name",
"ignore it. except Exception as exception: cond = None enum",
"and argdict[var] is not None: cfg[key][var] = argdict[var] def get_cfg(arg,",
"and not os.path.exists('xcpp.config'): if 'XCPP_CONFIG_PATH' in os.environ: tmp_path = os.environ['XCPP_CONFIG_PATH']",
"re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]' ) RE_IFELSE = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]ELSE (?P<iffalse>.*)'",
"line_num, fname): \"\"\"Evaluates a string using the eval function. It",
"tokens: if ':' in token: tsec, tkey = token.split(':') tval",
"% namespace.cfg) else: disp('path to xcpp.config: \"%s\"\\n' % namespace.cfg) with",
"data[tsec][tkey] else: if token in data[sec]: tval = data[sec][token] else:",
"'path': '.' } } cfg_file = read_config(arg) if 'xcpp' in",
"the current configuration. Note that using CFG[key][sec] # is equivalent",
"= re.compile(\"|\".join([re.escape(k) for k, _ in key_val]), re.M) return lambda",
"= path try: config = _read_config('%s/xcpp.config' % path, arg) except",
"name, cfg_file) else: if names != 'xcpp': cfg[names] = dict()",
"0 if everything is fine, 1 if there was an",
"= os.path.expandvars(str(val)) else: mod = import_mod('excentury.command.%s' % name) if hasattr(mod,",
"cfg[name][var] = os.path.expandvars(str(val)) else: mod = import_mod('excentury.command.%s' % name) if",
"for var, val in mod.DEFAULTS.iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_file(cfg,",
"if cond: val = match.group('iftrue') else: continue data[sec][key] = val",
"return def _update_single(cfg, name, defaults=None): \"Helper function for get_cfg.\" if",
"tmp_path) path = tmp_path elif not os.path.exists('%s/xcpp.config' % path): error(\"ERROR:",
"try: command, var = arg.var.split('.', 1) except ValueError: error(\"ERROR: '%s'",
"cfg[key][var] = argdict[var] def get_cfg(arg, names, defaults=None): \"\"\"Obtain the settings",
"necessary settings to the rest of the modules in excentury.",
"# function. For this reason we must try to catch",
"This module is in charge of providing all the necessary",
"sec ) # pylint: disable=star-args if replacements: val = replace(val,",
"description=textwrap.dedent(DESC)) tmpp.add_argument('var', type=str, nargs='?', default=None, help='Must be in the form",
"the evaluation and an error number: 0 if everything is",
"_ in key_val]), re.M) return lambda string: pattern.sub(replacement_function, string) def",
"everything is fine, 1 if there was an error. \"\"\"",
"os.path.exists('%s/xcpp.config' % path): error(\"ERROR: %s/xcpp.config does not exist\\n\" % path)",
"the configuration file. # ARG gives us access to the",
"key_val]), re.M) return lambda string: pattern.sub(replacement_function, string) def replace(string, *key_val):",
"cfg_file = read_config(arg) if 'xcpp' in cfg_file: for var, val",
"token: tsec, tkey = token.split(':') tval = '' if tsec",
"tval) ) return replacements # pylint: disable=invalid-name # ARG and",
"k, _ in key_val]), re.M) return lambda string: pattern.sub(replacement_function, string)",
"CFG[key][sec] # is equivalent to ${key:sec}. These names go against",
"help='configure excentury', formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('var', type=str, nargs='?', default=None, help='Must be",
"defaults=None): \"\"\"Obtain the settings for a command. \"\"\" cfg =",
"if everything is fine, 1 if there was an error.",
"\"\"\" ARG.FILEPATH = '%s/%s/%s' % (ARG.cfg, CFG['xcpp']['path'], ARG.inputfile) try: #",
"tmpp.add_argument('var', type=str, nargs='?', default=None, help='Must be in the form of",
"print function but it does not add the newline character.",
"\"\"\"Wrapper around sys.stdout.write which is meant to behave as the",
"not found in %r\\n' % namespace.cfg) else: disp('path to xcpp.config:",
"the newline character. \"\"\" sys.stdout.write(msg) def _replacer(*key_val): \"\"\"Helper function for",
"arg.cfg if path == '.' and not os.path.exists('xcpp.config'): if 'XCPP_CONFIG_PATH'",
"defaults: for var, val in defaults.iteritems(): cfg[name][var] = os.path.expandvars(str(val)) else:",
"it. except Exception as exception: cond = None enum =",
"command. \"\"\" RE = re.compile(r'\\${(?P<key>.*?)}') RE_IF = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]'",
"replace(string, *key_val): \"\"\"Replacement of strings done in one pass. Example:",
"eval function. It prints a warning if there are any",
"in cfg_file[name].iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_arg(cfg, argdict, key): \"Helper",
"tsec in data: if tkey in data[tsec]: tval = data[tsec][tkey]",
"return cond, enum def _read_config(fname, arg): \"\"\"Simple parser to read",
"exit(0) def add_parser(subp, raw): \"Add a parser to the main",
"Returns the result of the evaluation and an error number:",
"if arg.v: disp('path to xcpp.config: \"%s\"\\n' % arg.cfg) if arg.var",
"to spot in a configuration file. def _eval_condition(cond, ARG, CFG,",
"see the values that the configuration file can overwrite use",
"if there are any errors. Returns the result of the",
"To be able to evaluate a condition without creating a",
"in cfg_file: for var, val in cfg_file['xcpp'].iteritems(): cfg['xcpp'][var] = os.path.expandvars(val)",
"replacements: val = replace(val, *replacements) match = RE_IFELSE.match(val) if match:",
"= '' replacements.append( ('${%s}' % token, tval) ) return replacements",
"dict() _update_single(cfg, name) _update_from_file(cfg, name, cfg_file) else: if names !=",
"config = read_config(arg) if arg.v: disp('path to xcpp.config: \"%s\"\\n' %",
"wrong during the execution of the `eval` # function. For",
"argdict[var] is not None: cfg[key][var] = argdict[var] def get_cfg(arg, names,",
"tmp = line.split('=', 1) key = tmp[0].strip() val = tmp[1].strip()",
"= arg.cfg if isinstance(names, list): for name in names: cfg[name]",
"as a configuration but then there would be # no",
"for a command. \"\"\" cfg = { 'xcpp': { 'root':",
"It prints a warning if there are any errors. Returns",
"cond, enum = _eval_condition( match.group('cond'), arg, data, line_num, fname )",
"simple structure to the files. cond = eval(cond) enum =",
"\"\"\"Helper function for replace. Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" replace_dict = dict(key_val)",
"_replacer(*key_val)(string) class ConfigDispAction(argparse.Action): # pylint: disable=R0903 \"\"\"Derived argparse Action class",
"ARG, CFG, line_num, fname): \"\"\"Evaluates a string using the eval",
"argdict and argdict[var] is not None: cfg[key][var] = argdict[var] def",
"line.split('=', 1) key = tmp[0].strip() val = tmp[1].strip() val =",
"var in argdict and argdict[var] is not None: cfg[key][var] =",
"file xcpp.config\"\"\" path = arg.cfg if path == '.' and",
"We could have use # a python file as a",
"import textwrap import argparse from collections import OrderedDict from excentury.command",
"= _read_config('%s/xcpp.config' % path, arg) except IOError: config = OrderedDict()",
"go against the convention # so that they may be",
"%s\\n' % (key, config[sec][key])) disp('\\n') return try: command, var =",
"for get_cfg.\" for var in cfg[key]: if var in argdict",
"command. \"\"\" config = read_config(arg) if arg.v: disp('path to xcpp.config:",
"= re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]' ) RE_IFELSE = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]ELSE",
"around sys.stdout.write which is meant to behave as the print",
"data: if tkey in data[tsec]: tval = data[tsec][tkey] else: if",
"'XCPP_CONFIG_PATH' in os.environ: tmp_path = os.environ['XCPP_CONFIG_PATH'] if os.path.exists('%s/xcpp.config' % tmp_path):",
"_read_config. \"\"\" replacements = list() for token in tokens: if",
"\"Helper function for get_cfg.\" if defaults: for var, val in",
"ARG.FILEPATH = '%s/%s/%s' % (ARG.cfg, CFG['xcpp']['path'], ARG.inputfile) try: # pylint:",
"name) _update_from_file(cfg, name, cfg_file) else: if names != 'xcpp': cfg[names]",
"cfg[names] = dict() _update_single(cfg, names, defaults) _update_from_file(cfg, names, cfg_file) argdict",
"way so that we may give out a warning message",
"= subp.add_parser('config', help='configure excentury', formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('var', type=str, nargs='?', default=None,",
"def replace(string, *key_val): \"\"\"Replacement of strings done in one pass.",
"meant to behave as the print function but it does",
"import OrderedDict from excentury.command import error, trace, import_mod DESC =",
"data[sec] = OrderedDict() elif '=' in line: tmp = line.split('=',",
"tkey = token.split(':') tval = '' if tsec in data:",
"gives us # access to the current configuration. Note that",
"_replacer(*key_val): \"\"\"Helper function for replace. Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" replace_dict =",
"\" tmpp = subp.add_parser('config', help='configure excentury', formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('var', type=str,",
"1: continue if cond: val = match.group('iftrue') else: continue data[sec][key]",
"configuration files. \"\"\" data = OrderedDict() sec = None line_num",
"_update_from_file(cfg, names, cfg_file) argdict = vars(arg) if arg.parser_name in cfg:",
"\"\"\" sys.stdout.write(msg) def _replacer(*key_val): \"\"\"Helper function for replace. Source: <http://stackoverflow.com/a/15221068/788553>",
"function for get_cfg.\" for var in cfg[key]: if var in",
"tval = '' replacements.append( ('${%s}' % token, tval) ) return",
"help='print config file location') tmpp.add_argument('--print', action=ConfigDispAction, nargs=0, help='print config file",
"1) key = tmp[0].strip() val = tmp[1].strip() val = os.path.expandvars(val)",
"excentury uses for the given command. \"\"\" RE = re.compile(r'\\${(?P<key>.*?)}')",
"if path == '.' and not os.path.exists('xcpp.config'): if 'XCPP_CONFIG_PATH' in",
"by using configuration files. To see the values that the",
"\"\"\" return _replacer(*key_val)(string) class ConfigDispAction(argparse.Action): # pylint: disable=R0903 \"\"\"Derived argparse",
"file location') tmpp.add_argument('--print', action=ConfigDispAction, nargs=0, help='print config file and exit')",
"except ValueError: error(\"ERROR: '%s' is not of the form sec.key\\n\"",
"from excentury.command import error, trace, import_mod DESC = \"\"\"Edit a",
"configuration file. def _eval_condition(cond, ARG, CFG, line_num, fname): \"\"\"Evaluates a",
"can overwrite use the `defaults` command. This will print a",
"return config def run(arg): \"\"\"Run command. \"\"\" config = read_config(arg)",
"all the necessary settings to the rest of the modules",
"match.group('cond'), arg, data, line_num, fname ) if enum == 1:",
"are any errors. Returns the result of the evaluation and",
"fname ) if enum == 1: continue groups = match.groups()",
"def run(arg): \"\"\"Run command. \"\"\" config = read_config(arg) if arg.v:",
"try: # pylint: disable=eval-used # To be able to evaluate",
"KeyError: pass return def _update_single(cfg, name, defaults=None): \"Helper function for",
"the configuration file and location.\"\"\" def __call__(self, parser, namespace, values,",
"to xcpp.config: \"%s\"\\n' % arg.cfg) if arg.var is None: for",
"} cfg_file = read_config(arg) if 'xcpp' in cfg_file: for var,",
"RE_IF.match(val) if match: cond, enum = _eval_condition( match.group('cond'), arg, data,",
"use # a python file as a configuration but then",
"= read_config(arg) if 'xcpp' in cfg_file: for var, val in",
"and arg.lang in cfg: _update_from_arg(cfg, argdict, arg.lang) _update_from_arg(cfg, argdict, 'xcpp')",
"= tmp[1].strip() val = os.path.expandvars(val) replacements = _get_replacements( RE.findall(val), data,",
"\"\"\"Simple parser to read configuration files. \"\"\" data = OrderedDict()",
"in data: if tkey in data[tsec]: tval = data[tsec][tkey] else:",
"IF\\[\\[(?P<cond>.*?)\\]\\]' ) RE_IFELSE = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]ELSE (?P<iffalse>.*)' ) def",
"we must try to catch anything that # may come",
"1) except ValueError: error(\"ERROR: '%s' is not of the form",
"not of the form sec.key\\n\" % arg.var) try: disp(config[command][var]+'\\n') except",
"disp(config[command][var]+'\\n') except KeyError: pass return def _update_single(cfg, name, defaults=None): \"Helper",
"pass return def _update_single(cfg, name, defaults=None): \"Helper function for get_cfg.\"",
"tmpp = subp.add_parser('config', help='configure excentury', formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('var', type=str, nargs='?',",
"is fine, 1 if there was an error. \"\"\" ARG.FILEPATH",
"in tokens: if ':' in token: tsec, tkey = token.split(':')",
"default=None, help='Must be in the form of sec.key') tmpp.add_argument('-v', action='store_true',",
"us access to the command line arguments and CFG gives",
") if enum == 1: continue if cond: val =",
"_read_config('%s/xcpp.config' % path, arg) except IOError: config = OrderedDict() return",
"<http://stackoverflow.com/a/15221068/788553> \"\"\" return _replacer(*key_val)(string) class ConfigDispAction(argparse.Action): # pylint: disable=R0903 \"\"\"Derived",
"displaying the configuration file and location.\"\"\" def __call__(self, parser, namespace,",
"easy to spot in a configuration file. def _eval_condition(cond, ARG,",
"excentury. \"\"\" import os import re import sys import textwrap",
"namespace.cfg, 'r') as _fp: disp(_fp.read()) exit(0) def add_parser(subp, raw): \"Add",
"IF\\[\\[(?P<cond>.*?)\\]\\]ELSE (?P<iffalse>.*)' ) def disp(msg): \"\"\"Wrapper around sys.stdout.write which is",
"arg, data, line_num, fname ) if enum == 1: continue",
"string) def replace(string, *key_val): \"\"\"Replacement of strings done in one",
"def _get_replacements(tokens, data, sec): \"\"\"Helper function for _read_config. \"\"\" replacements",
"enum == 1: continue if cond: val = match.group('iftrue') else:",
"config def run(arg): \"\"\"Run command. \"\"\" config = read_config(arg) if",
"the configuration file xcpp.config\"\"\" path = arg.cfg if path ==",
"in os.environ: tmp_path = os.environ['XCPP_CONFIG_PATH'] if os.path.exists('%s/xcpp.config' % tmp_path): trace(\"Configured",
"= line.split('=', 1) key = tmp[0].strip() val = tmp[1].strip() val",
"= _eval_condition( match.group('cond'), arg, data, line_num, fname ) if enum",
"data, line_num, fname ) if enum == 1: continue groups",
"argdict = vars(arg) if arg.parser_name in cfg: _update_from_arg(cfg, argdict, arg.parser_name)",
"ConfigDispAction(argparse.Action): # pylint: disable=R0903 \"\"\"Derived argparse Action class to use",
"read_config(arg): \"\"\"Read the configuration file xcpp.config\"\"\" path = arg.cfg if",
"in data[tsec]: tval = data[tsec][tkey] else: if token in data[sec]:",
"for var, val in defaults.iteritems(): cfg[name][var] = os.path.expandvars(str(val)) else: mod",
"structure to the files. cond = eval(cond) enum = 0",
"in line %d of %r: %s\\n' % ( line_num, fname,",
"# ARG and CFG are names that may be used",
"add the newline character. \"\"\" sys.stdout.write(msg) def _replacer(*key_val): \"\"\"Helper function",
"uses for the given command. \"\"\" RE = re.compile(r'\\${(?P<key>.*?)}') RE_IF",
"whole # new parser we can use the eval function.",
"fname): \"\"\"Evaluates a string using the eval function. It prints",
"convention # so that they may be easy to spot",
"% namespace.cfg, 'r') as _fp: disp(_fp.read()) exit(0) def add_parser(subp, raw):",
"line: tmp = line.split('=', 1) key = tmp[0].strip() val =",
"names, defaults=None): \"\"\"Obtain the settings for a command. \"\"\" cfg",
"< b && b < c' Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" return",
"if ':' in token: tsec, tkey = token.split(':') tval =",
"arg.lang in cfg: _update_from_arg(cfg, argdict, arg.lang) _update_from_arg(cfg, argdict, 'xcpp') return",
"pylint: disable=broad-except # Anything can go wrong during the execution",
"get_cfg.\" for var in cfg[key]: if var in argdict and",
"in config[sec]: disp(' %s = %s\\n' % (key, config[sec][key])) disp('\\n')",
"subparser. \" tmpp = subp.add_parser('config', help='configure excentury', formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('var',",
"= tmp_path elif not os.path.exists('%s/xcpp.config' % path): error(\"ERROR: %s/xcpp.config does",
"pylint: disable=star-args if replacements: val = replace(val, *replacements) match =",
"then there would be # no simple structure to the",
"may come our way so that we may give out",
"val = tmp[1].strip() val = os.path.expandvars(val) replacements = _get_replacements( RE.findall(val),",
"when displaying the configuration file and location.\"\"\" def __call__(self, parser,",
"is None: for sec in config: disp('[%s]\\n' % sec) for",
"import_mod DESC = \"\"\"Edit a configuration file for excentury. Some",
"def add_parser(subp, raw): \"Add a parser to the main subparser.",
"'r') as fhandle: for line in fhandle: line_num += 1",
"else: continue data[sec][key] = val return data def read_config(arg): \"\"\"Read",
"defaults=None): \"Helper function for get_cfg.\" if defaults: for var, val",
"var, val in defaults.iteritems(): cfg[name][var] = os.path.expandvars(str(val)) else: mod =",
"val = os.path.expandvars(val) replacements = _get_replacements( RE.findall(val), data, sec )",
"== '.' and not os.path.exists('xcpp.config'): if 'XCPP_CONFIG_PATH' in os.environ: tmp_path",
"function for _read_config. \"\"\" replacements = list() for token in",
"in defaults.iteritems(): cfg[name][var] = os.path.expandvars(str(val)) else: mod = import_mod('excentury.command.%s' %",
"using CFG[key][sec] # is equivalent to ${key:sec}. These names go",
"configuration file and location.\"\"\" def __call__(self, parser, namespace, values, option_string=None):",
"*replacements) match = RE_IFELSE.match(val) if match: cond, enum = _eval_condition(",
"else: disp('path to xcpp.config: \"%s\"\\n' % namespace.cfg) with open('%s/xcpp.config' %",
"read_config(namespace) except IOError: disp('xcpp.config not found in %r\\n' % namespace.cfg)",
"and location.\"\"\" def __call__(self, parser, namespace, values, option_string=None): try: read_config(namespace)",
"the `defaults` command. This will print a list of the",
"but it does not add the newline character. \"\"\" sys.stdout.write(msg)",
"error. \"\"\" ARG.FILEPATH = '%s/%s/%s' % (ARG.cfg, CFG['xcpp']['path'], ARG.inputfile) try:",
"configuration file xcpp.config\"\"\" path = arg.cfg if path == '.'",
"def read_config(arg): \"\"\"Read the configuration file xcpp.config\"\"\" path = arg.cfg",
"error number: 0 if everything is fine, 1 if there",
"function for replace. Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" replace_dict = dict(key_val) replacement_function",
"else groups[2] else: match = RE_IF.match(val) if match: cond, enum",
"formatter_class=raw, description=textwrap.dedent(DESC)) tmpp.add_argument('var', type=str, nargs='?', default=None, help='Must be in the",
"disp('path to xcpp.config: \"%s\"\\n' % namespace.cfg) with open('%s/xcpp.config' % namespace.cfg,",
"re import sys import textwrap import argparse from collections import",
"RE_IFELSE = re.compile( r'(?P<iftrue>.*?) IF\\[\\[(?P<cond>.*?)\\]\\]ELSE (?P<iffalse>.*)' ) def disp(msg): \"\"\"Wrapper",
"for get_cfg.\" if defaults: for var, val in defaults.iteritems(): cfg[name][var]",
"in argdict and argdict[var] is not None: cfg[key][var] = argdict[var]",
"config file location') tmpp.add_argument('--print', action=ConfigDispAction, nargs=0, help='print config file and",
"_update_single(cfg, name) _update_from_file(cfg, name, cfg_file) else: if names != 'xcpp':",
"Source: <http://stackoverflow.com/a/15221068/788553> \"\"\" return _replacer(*key_val)(string) class ConfigDispAction(argparse.Action): # pylint: disable=R0903",
"during the execution of the `eval` # function. For this",
"pattern.sub(replacement_function, string) def replace(string, *key_val): \"\"\"Replacement of strings done in",
"can go wrong during the execution of the `eval` #",
"to read configuration files. \"\"\" data = OrderedDict() sec =",
"if defaults: for var, val in defaults.iteritems(): cfg[name][var] = os.path.expandvars(str(val))",
"parser to the main subparser. \" tmpp = subp.add_parser('config', help='configure",
"for name in names: cfg[name] = dict() _update_single(cfg, name) _update_from_file(cfg,",
"arg.cfg) if arg.var is None: for sec in config: disp('[%s]\\n'",
"*key_val): \"\"\"Replacement of strings done in one pass. Example: >>>",
"to ${key:sec}. These names go against the convention # so",
"elif not os.path.exists('%s/xcpp.config' % path): error(\"ERROR: %s/xcpp.config does not exist\\n\"",
"cfg['xcpp'][var] = os.path.expandvars(val) cfg['xcpp']['root'] = arg.cfg if isinstance(names, list): for",
") # pylint: disable=star-args if replacements: val = replace(val, *replacements)",
"# pylint: disable=eval-used # To be able to evaluate a",
"mod = import_mod('excentury.command.%s' % name) if hasattr(mod, \"DEFAULTS\"): for var,",
"list of the keys and values excentury uses for the",
"any errors. Returns the result of the evaluation and an",
"= groups[0] if cond else groups[2] else: match = RE_IF.match(val)",
"not None: cfg[key][var] = argdict[var] def get_cfg(arg, names, defaults=None): \"\"\"Obtain",
"so that we may give out a warning message #",
"val in cfg_file[name].iteritems(): cfg[name][var] = os.path.expandvars(val) def _update_from_arg(cfg, argdict, key):",
"1: continue groups = match.groups() val = groups[0] if cond",
"and values excentury uses for the given command. \"\"\" RE",
"action='store_true', help='print config file location') tmpp.add_argument('--print', action=ConfigDispAction, nargs=0, help='print config",
"os.path.expandvars(str(val)) else: mod = import_mod('excentury.command.%s' % name) if hasattr(mod, \"DEFAULTS\"):",
"`eval` # function. For this reason we must try to",
"error in line %d of %r: %s\\n' % ( line_num,",
"cond else groups[2] else: match = RE_IF.match(val) if match: cond,",
"0 # pylint: disable=broad-except # Anything can go wrong during",
"file can overwrite use the `defaults` command. This will print",
"use when displaying the configuration file and location.\"\"\" def __call__(self,",
"not add the newline character. \"\"\" sys.stdout.write(msg) def _replacer(*key_val): \"\"\"Helper",
"for _read_config. \"\"\" replacements = list() for token in tokens:",
"tmp[0].strip() val = tmp[1].strip() val = os.path.expandvars(val) replacements = _get_replacements(",
"__call__(self, parser, namespace, values, option_string=None): try: read_config(namespace) except IOError: disp('xcpp.config",
"tmpp.add_argument('--print', action=ConfigDispAction, nargs=0, help='print config file and exit') def _get_replacements(tokens,",
"fname, exception.message ) ) return cond, enum def _read_config(fname, arg):",
"line in fhandle: line_num += 1 if line[0] == '[':",
"= os.path.expandvars(val) replacements = _get_replacements( RE.findall(val), data, sec ) #",
"argdict, arg.parser_name) elif arg.parser_name == 'to' and arg.lang in cfg:",
"tsec, tkey = token.split(':') tval = '' if tsec in",
"= None line_num = 0 with open(fname, 'r') as fhandle:",
"os.environ['XCPP_CONFIG_PATH'] if os.path.exists('%s/xcpp.config' % tmp_path): trace(\"Configured with: '%s/xcpp.config'\\n\" % tmp_path)",
"the form sec.key\\n\" % arg.var) try: disp(config[command][var]+'\\n') except KeyError: pass",
"= 1 trace( 'WARNING: error in line %d of %r:",
"in cfg_file: for var, val in cfg_file[name].iteritems(): cfg[name][var] = os.path.expandvars(val)",
"the rest of the modules in excentury. \"\"\" import os",
"tval = data[tsec][tkey] else: if token in data[sec]: tval =",
"parser to read configuration files. \"\"\" data = OrderedDict() sec",
"function for get_cfg.\" if defaults: for var, val in defaults.iteritems():",
"re.M) return lambda string: pattern.sub(replacement_function, string) def replace(string, *key_val): \"\"\"Replacement",
"'xcpp' in cfg_file: for var, val in cfg_file['xcpp'].iteritems(): cfg['xcpp'][var] =",
"that using CFG[key][sec] # is equivalent to ${key:sec}. These names",
"fine, 1 if there was an error. \"\"\" ARG.FILEPATH =",
"that we may give out a warning message # and"
] |
[
"for key in TestUrls.__dict__.keys(): if key.find('test') == 0: TestUrls.__dict__[key](self) def",
"if six.PY2: if result.wasSuccessful(): print('tests OK') for (test, error) in",
"tearDown(self): super().tearDown() if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUrls) result",
"result.wasSuccessful(): print('tests OK') for (test, error) in result.errors: print('=========Error in:",
"if proxy_on: urls.session.proxies.update({'http': 'proxy1.wipro.com:8080'}) def runTest(self): for key in TestUrls.__dict__.keys():",
"derivative_history_url(instrumentType='FUTIDX', symbol='NIFTY', expiryDate='26-12-2019', optionType='select', strikePrice='', dateRange='', fromDate='25-Dec-2019', toDate='26-Dec-2019') self.assertGreaterEqual(resp.text.find('NIFTY'), 0)",
"0) def test_derivative_history_url(self): resp = derivative_history_url(instrumentType='FUTIDX', symbol='NIFTY', expiryDate='26-12-2019', optionType='select', strikePrice='',",
"def test_index_pe_history_url(self): resp = index_pe_history_url(fromDate='01-01-2015', toDate='10-01-2015', indexName='NIFTY 50') self.assertGreaterEqual(resp.text.find('<th>P/E'), 0)",
"import nseta.common.urls as urls from six.moves.urllib.parse import urlparse from baseUnitTest",
"time from bs4 import BeautifulSoup from tests import htmls import",
"test_derivative_derivative_expiry_dates_url(self): resp = derivative_expiry_dates_url() self.assertGreaterEqual(resp.text.find('vixExpryDt'), 0) def test_derivative_history_url(self): resp =",
"resp = daily_volatility_url('19112015') self.assertGreaterEqual(resp.text.find('SBIN'), 0) def test_pr_price_list_zipped_url(self): resp = pr_price_list_zipped_url('191115')",
"datetime import unittest import time from bs4 import BeautifulSoup from",
"19 20:52:33 2015 @author: SW274998 ''' from nseta.common.commons import *",
"'1') force_count = get_symbol_count(symbol='SBIN', force_refresh=True) self.assertEqual(force_count, '1') def test_equity_history_url(self): sym_count",
"str(resp.content) self.assertGreaterEqual(csv.find('Nifty 50'), 0) self.assertGreaterEqual(csv.find('Nifty IT'), 0) self.assertGreaterEqual(csv.find('Nifty Bank'), 0)",
"False if proxy_on: urls.session.proxies.update({'http': 'proxy1.wipro.com:8080'}) def runTest(self): for key in",
"on Thu Nov 19 20:52:33 2015 @author: SW274998 ''' from",
"test_equity_history_url(self): sym_count = get_symbol_count(symbol='SBIN') txt = 'Data for SBIN -",
"= index_vix_history_url(fromDate='01-Jan-2015', toDate='10-Jan-2015', ) self.assertGreaterEqual(resp.text.find('VIX'), 0) self.assertGreaterEqual(resp.text.find('Change'), 0) def test_derivative_derivative_expiry_dates_url(self):",
"unzip_str(resp.content) self.assertGreaterEqual(csv.find('SBIN'), 0) def tests_daily_volatility_url(self): resp = daily_volatility_url('19112015') self.assertGreaterEqual(resp.text.find('SBIN'), 0)",
"* import nseta.common.urls as urls from six.moves.urllib.parse import urlparse from",
"def test_pr_price_list_zipped_url(self): resp = pr_price_list_zipped_url('191115') csv = unzip_str(resp.content) def test_index_history_url(self):",
"Created on Thu Nov 19 20:52:33 2015 @author: SW274998 '''",
"baseUnitTest import baseUnitTest class TestUrls(baseUnitTest): def setUp(self, redirect_logs=True): super().setUp() proxy_on",
"test_nse_intraday_url(self): txt = 'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL' #'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>' resp = nse_intraday_url(CDSymbol='SBIN', Periodicity='1') self.assertIn(txt,",
"def test_price_list_url(self): resp = price_list_url('2019', 'DEC', '31DEC2019') csv = unzip_str(resp.content)",
"csv = unzip_str(resp.content) self.assertGreaterEqual(csv.find('SBIN'), 0) def tests_daily_volatility_url(self): resp = daily_volatility_url('19112015')",
"% test) print(error) print('======================================') for (test, failures) in result.failures: print('=========Error",
"self.assertGreaterEqual(resp.text.find('High'), 0) self.assertGreaterEqual(resp.text.find('Low'), 0) def test_index_daily_snapshot_url(self): resp = index_daily_snapshot_url('06012020') csv",
"six.PY2: if result.wasSuccessful(): print('tests OK') for (test, error) in result.errors:",
"0) def test_pr_price_list_zipped_url(self): resp = pr_price_list_zipped_url('191115') csv = unzip_str(resp.content) def",
"self.assertGreaterEqual(csv.find('Nifty 50'), 0) self.assertGreaterEqual(csv.find('Nifty IT'), 0) self.assertGreaterEqual(csv.find('Nifty Bank'), 0) self.assertGreaterEqual(csv.find('Nifty",
"'19JUL2019') csv = unzip_str(resp.content) def tearDown(self): super().tearDown() if __name__ ==",
"SW274998 ''' from nseta.common.commons import * import datetime import unittest",
"nseta.common.urls as urls from six.moves.urllib.parse import urlparse from baseUnitTest import",
"self.assertGreaterEqual(resp.text.find('<th>P/B'), 0) def test_index_vix_history_url(self): resp = index_vix_history_url(fromDate='01-Jan-2015', toDate='10-Jan-2015', ) self.assertGreaterEqual(resp.text.find('VIX'),",
"csv = unzip_str(resp.content) def tearDown(self): super().tearDown() if __name__ == '__main__':",
"import BeautifulSoup from tests import htmls import json import requests",
"Bank'), 0) self.assertGreaterEqual(csv.find('Nifty Next 50'), 0) def test_index_pe_history_url(self): resp =",
"equity_history_url(symbol='SBIN', symbolCount=sym_count, series='EQ', fromDate='01-01-2000', toDate='10-01-2000', dateRange='') self.assertGreaterEqual(resp.text.find(txt), 0, resp.text) def",
"get_symbol_count(symbol='SBIN') self.assertEqual(count, '1') force_count = get_symbol_count(symbol='SBIN', force_refresh=True) self.assertEqual(force_count, '1') def",
"'DEC', '31DEC2019') csv = unzip_str(resp.content) self.assertGreaterEqual(csv.find('SBIN'), 0) def tests_daily_volatility_url(self): resp",
"def test_index_daily_snapshot_url(self): resp = index_daily_snapshot_url('06012020') csv = str(resp.content) self.assertGreaterEqual(csv.find('Nifty 50'),",
"0) self.assertGreaterEqual(csv.find('Nifty IT'), 0) self.assertGreaterEqual(csv.find('Nifty Bank'), 0) self.assertGreaterEqual(csv.find('Nifty Next 50'),",
"def setUp(self, redirect_logs=True): super().setUp() proxy_on = False if proxy_on: urls.session.proxies.update({'http':",
"self.assertIn(txt, resp.text) def test_price_list_url(self): resp = price_list_url('2019', 'DEC', '31DEC2019') csv",
"import urlparse from baseUnitTest import baseUnitTest class TestUrls(baseUnitTest): def setUp(self,",
"= str(resp.content) self.assertGreaterEqual(csv.find('Nifty 50'), 0) self.assertGreaterEqual(csv.find('Nifty IT'), 0) self.assertGreaterEqual(csv.find('Nifty Bank'),",
"result = unittest.TextTestRunner(verbosity=2).run(suite) if six.PY2: if result.wasSuccessful(): print('tests OK') for",
"in TestUrls.__dict__.keys(): if key.find('test') == 0: TestUrls.__dict__[key](self) def test_get_symbol_count(self): count",
"txt = 'Data for SBIN - EQ' resp = equity_history_url(symbol='SBIN',",
"get_symbol_count(symbol='SBIN') txt = 'Data for SBIN - EQ' resp =",
"50') self.assertGreaterEqual(resp.text.find('<th>P/E'), 0) self.assertGreaterEqual(resp.text.find('<th>P/B'), 0) def test_index_vix_history_url(self): resp = index_vix_history_url(fromDate='01-Jan-2015',",
"expiryDate='26-12-2019', optionType='select', strikePrice='', dateRange='', fromDate='25-Dec-2019', toDate='26-Dec-2019') self.assertGreaterEqual(resp.text.find('NIFTY'), 0) self.assertGreaterEqual(resp.text.find('Expiry'), 0)",
"tests_daily_volatility_url(self): resp = daily_volatility_url('19112015') self.assertGreaterEqual(resp.text.find('SBIN'), 0) def test_pr_price_list_zipped_url(self): resp =",
"from baseUnitTest import baseUnitTest class TestUrls(baseUnitTest): def setUp(self, redirect_logs=True): super().setUp()",
"resp = derivative_price_list_url('2019', 'JUL', '19JUL2019') csv = unzip_str(resp.content) def tearDown(self):",
"import time from bs4 import BeautifulSoup from tests import htmls",
"self.assertGreaterEqual(csv.find('Nifty Bank'), 0) self.assertGreaterEqual(csv.find('Nifty Next 50'), 0) def test_index_pe_history_url(self): resp",
"sym_count = get_symbol_count(symbol='SBIN') txt = 'Data for SBIN - EQ'",
"print('======================================') for (test, failures) in result.failures: print('=========Error in: %s===========' %",
"daily_volatility_url('19112015') self.assertGreaterEqual(resp.text.find('SBIN'), 0) def test_pr_price_list_zipped_url(self): resp = pr_price_list_zipped_url('191115') csv =",
"from nseta.common.urls import * import nseta.common.urls as urls from six.moves.urllib.parse",
"tests import htmls import json import requests import six from",
"unittest.TextTestRunner(verbosity=2).run(suite) if six.PY2: if result.wasSuccessful(): print('tests OK') for (test, error)",
"super().setUp() proxy_on = False if proxy_on: urls.session.proxies.update({'http': 'proxy1.wipro.com:8080'}) def runTest(self):",
"toDate='10-Jan-2015', ) self.assertGreaterEqual(resp.text.find('VIX'), 0) self.assertGreaterEqual(resp.text.find('Change'), 0) def test_derivative_derivative_expiry_dates_url(self): resp =",
"'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL' #'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>' resp = nse_intraday_url(CDSymbol='SBIN', Periodicity='1') self.assertIn(txt, resp.text) def test_price_list_url(self):",
"self.assertEqual(force_count, '1') def test_equity_history_url(self): sym_count = get_symbol_count(symbol='SBIN') txt = 'Data",
"nseta.common.urls import * import nseta.common.urls as urls from six.moves.urllib.parse import",
"= price_list_url('2019', 'DEC', '31DEC2019') csv = unzip_str(resp.content) self.assertGreaterEqual(csv.find('SBIN'), 0) def",
"utf-8 -*- ''' Created on Thu Nov 19 20:52:33 2015",
"test_index_daily_snapshot_url(self): resp = index_daily_snapshot_url('06012020') csv = str(resp.content) self.assertGreaterEqual(csv.find('Nifty 50'), 0)",
"import baseUnitTest class TestUrls(baseUnitTest): def setUp(self, redirect_logs=True): super().setUp() proxy_on =",
"resp = index_vix_history_url(fromDate='01-Jan-2015', toDate='10-Jan-2015', ) self.assertGreaterEqual(resp.text.find('VIX'), 0) self.assertGreaterEqual(resp.text.find('Change'), 0) def",
"unittest import time from bs4 import BeautifulSoup from tests import",
"resp = nse_intraday_url(CDSymbol='SBIN', Periodicity='1') self.assertIn(txt, resp.text) def test_price_list_url(self): resp =",
"index_history_url(indexType='NIFTY 50', fromDate='01-01-2015', toDate='10-01-2015') self.assertGreaterEqual(resp.text.find('High'), 0) self.assertGreaterEqual(resp.text.find('Low'), 0) def test_index_daily_snapshot_url(self):",
"OK') for (test, error) in result.errors: print('=========Error in: %s===========' %",
"= nse_intraday_url(CDSymbol='SBIN', Periodicity='1') self.assertIn(txt, resp.text) def test_price_list_url(self): resp = price_list_url('2019',",
"= derivative_price_list_url('2019', 'JUL', '19JUL2019') csv = unzip_str(resp.content) def tearDown(self): super().tearDown()",
"BeautifulSoup from tests import htmls import json import requests import",
"redirect_logs=True): super().setUp() proxy_on = False if proxy_on: urls.session.proxies.update({'http': 'proxy1.wipro.com:8080'}) def",
"0: TestUrls.__dict__[key](self) def test_get_symbol_count(self): count = get_symbol_count(symbol='SBIN') self.assertEqual(count, '1') force_count",
"= unzip_str(resp.content) def tearDown(self): super().tearDown() if __name__ == '__main__': suite",
"resp = equity_history_url(symbol='SBIN', symbolCount=sym_count, series='EQ', fromDate='01-01-2000', toDate='10-01-2000', dateRange='') self.assertGreaterEqual(resp.text.find(txt), 0,",
"def test_nse_intraday_url(self): txt = 'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL' #'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>' resp = nse_intraday_url(CDSymbol='SBIN', Periodicity='1')",
"self.assertGreaterEqual(resp.text.find('VIX'), 0) self.assertGreaterEqual(resp.text.find('Change'), 0) def test_derivative_derivative_expiry_dates_url(self): resp = derivative_expiry_dates_url() self.assertGreaterEqual(resp.text.find('vixExpryDt'),",
"result.errors: print('=========Error in: %s===========' % test) print(error) print('======================================') for (test,",
"'Data for SBIN - EQ' resp = equity_history_url(symbol='SBIN', symbolCount=sym_count, series='EQ',",
"Nov 19 20:52:33 2015 @author: SW274998 ''' from nseta.common.commons import",
"self.assertGreaterEqual(resp.text.find(txt), 0, resp.text) def test_nse_intraday_url(self): txt = 'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL' #'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>' resp",
"bs4 import BeautifulSoup from tests import htmls import json import",
"import requests import six from nseta.common.urls import * import nseta.common.urls",
") self.assertGreaterEqual(resp.text.find('VIX'), 0) self.assertGreaterEqual(resp.text.find('Change'), 0) def test_derivative_derivative_expiry_dates_url(self): resp = derivative_expiry_dates_url()",
"import json import requests import six from nseta.common.urls import *",
"test_pr_price_list_zipped_url(self): resp = pr_price_list_zipped_url('191115') csv = unzip_str(resp.content) def test_index_history_url(self): resp",
"pr_price_list_zipped_url('191115') csv = unzip_str(resp.content) def test_index_history_url(self): resp = index_history_url(indexType='NIFTY 50',",
"Thu Nov 19 20:52:33 2015 @author: SW274998 ''' from nseta.common.commons",
"__name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUrls) result = unittest.TextTestRunner(verbosity=2).run(suite) if",
"= daily_volatility_url('19112015') self.assertGreaterEqual(resp.text.find('SBIN'), 0) def test_pr_price_list_zipped_url(self): resp = pr_price_list_zipped_url('191115') csv",
"fromDate='01-01-2000', toDate='10-01-2000', dateRange='') self.assertGreaterEqual(resp.text.find(txt), 0, resp.text) def test_nse_intraday_url(self): txt =",
"csv = str(resp.content) self.assertGreaterEqual(csv.find('Nifty 50'), 0) self.assertGreaterEqual(csv.find('Nifty IT'), 0) self.assertGreaterEqual(csv.find('Nifty",
"self.assertGreaterEqual(resp.text.find('Change'), 0) def test_derivative_derivative_expiry_dates_url(self): resp = derivative_expiry_dates_url() self.assertGreaterEqual(resp.text.find('vixExpryDt'), 0) def",
"0) def test_index_daily_snapshot_url(self): resp = index_daily_snapshot_url('06012020') csv = str(resp.content) self.assertGreaterEqual(csv.find('Nifty",
"in: %s===========' % test) print(error) print('======================================') for (test, failures) in",
"json import requests import six from nseta.common.urls import * import",
"def test_index_history_url(self): resp = index_history_url(indexType='NIFTY 50', fromDate='01-01-2015', toDate='10-01-2015') self.assertGreaterEqual(resp.text.find('High'), 0)",
"def test_index_vix_history_url(self): resp = index_vix_history_url(fromDate='01-Jan-2015', toDate='10-Jan-2015', ) self.assertGreaterEqual(resp.text.find('VIX'), 0) self.assertGreaterEqual(resp.text.find('Change'),",
"unzip_str(resp.content) def test_index_history_url(self): resp = index_history_url(indexType='NIFTY 50', fromDate='01-01-2015', toDate='10-01-2015') self.assertGreaterEqual(resp.text.find('High'),",
"coding: utf-8 -*- ''' Created on Thu Nov 19 20:52:33",
"- EQ' resp = equity_history_url(symbol='SBIN', symbolCount=sym_count, series='EQ', fromDate='01-01-2000', toDate='10-01-2000', dateRange='')",
"for (test, error) in result.errors: print('=========Error in: %s===========' % test)",
"''' Created on Thu Nov 19 20:52:33 2015 @author: SW274998",
"0) self.assertGreaterEqual(csv.find('Nifty Bank'), 0) self.assertGreaterEqual(csv.find('Nifty Next 50'), 0) def test_index_pe_history_url(self):",
"50'), 0) self.assertGreaterEqual(csv.find('Nifty IT'), 0) self.assertGreaterEqual(csv.find('Nifty Bank'), 0) self.assertGreaterEqual(csv.find('Nifty Next",
"self.assertEqual(count, '1') force_count = get_symbol_count(symbol='SBIN', force_refresh=True) self.assertEqual(force_count, '1') def test_equity_history_url(self):",
"= index_daily_snapshot_url('06012020') csv = str(resp.content) self.assertGreaterEqual(csv.find('Nifty 50'), 0) self.assertGreaterEqual(csv.find('Nifty IT'),",
"baseUnitTest class TestUrls(baseUnitTest): def setUp(self, redirect_logs=True): super().setUp() proxy_on = False",
"resp.text) def test_nse_intraday_url(self): txt = 'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL' #'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>' resp = nse_intraday_url(CDSymbol='SBIN',",
"Periodicity='1') self.assertIn(txt, resp.text) def test_price_list_url(self): resp = price_list_url('2019', 'DEC', '31DEC2019')",
"requests import six from nseta.common.urls import * import nseta.common.urls as",
"#'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>' resp = nse_intraday_url(CDSymbol='SBIN', Periodicity='1') self.assertIn(txt, resp.text) def test_price_list_url(self): resp",
"toDate='10-01-2015', indexName='NIFTY 50') self.assertGreaterEqual(resp.text.find('<th>P/E'), 0) self.assertGreaterEqual(resp.text.find('<th>P/B'), 0) def test_index_vix_history_url(self): resp",
"* import datetime import unittest import time from bs4 import",
"def test_derivative_derivative_expiry_dates_url(self): resp = derivative_expiry_dates_url() self.assertGreaterEqual(resp.text.find('vixExpryDt'), 0) def test_derivative_history_url(self): resp",
"test_index_history_url(self): resp = index_history_url(indexType='NIFTY 50', fromDate='01-01-2015', toDate='10-01-2015') self.assertGreaterEqual(resp.text.find('High'), 0) self.assertGreaterEqual(resp.text.find('Low'),",
"%s===========' % test) print(error) print('======================================') for (test, failures) in result.failures:",
"urls from six.moves.urllib.parse import urlparse from baseUnitTest import baseUnitTest class",
"self.assertGreaterEqual(csv.find('Nifty Next 50'), 0) def test_index_pe_history_url(self): resp = index_pe_history_url(fromDate='01-01-2015', toDate='10-01-2015',",
"0) self.assertGreaterEqual(resp.text.find('Expiry'), 0) def test_derivative_price_list_url(self): resp = derivative_price_list_url('2019', 'JUL', '19JUL2019')",
"self.assertGreaterEqual(resp.text.find('Expiry'), 0) def test_derivative_price_list_url(self): resp = derivative_price_list_url('2019', 'JUL', '19JUL2019') csv",
"test) print(error) print('======================================') for (test, failures) in result.failures: print('=========Error in:",
"0) def test_derivative_derivative_expiry_dates_url(self): resp = derivative_expiry_dates_url() self.assertGreaterEqual(resp.text.find('vixExpryDt'), 0) def test_derivative_history_url(self):",
"= get_symbol_count(symbol='SBIN', force_refresh=True) self.assertEqual(force_count, '1') def test_equity_history_url(self): sym_count = get_symbol_count(symbol='SBIN')",
"as urls from six.moves.urllib.parse import urlparse from baseUnitTest import baseUnitTest",
"== 0: TestUrls.__dict__[key](self) def test_get_symbol_count(self): count = get_symbol_count(symbol='SBIN') self.assertEqual(count, '1')",
"(test, failures) in result.failures: print('=========Error in: %s===========' % test) print(failures)",
"six.moves.urllib.parse import urlparse from baseUnitTest import baseUnitTest class TestUrls(baseUnitTest): def",
"symbolCount=sym_count, series='EQ', fromDate='01-01-2000', toDate='10-01-2000', dateRange='') self.assertGreaterEqual(resp.text.find(txt), 0, resp.text) def test_nse_intraday_url(self):",
"setUp(self, redirect_logs=True): super().setUp() proxy_on = False if proxy_on: urls.session.proxies.update({'http': 'proxy1.wipro.com:8080'})",
"key in TestUrls.__dict__.keys(): if key.find('test') == 0: TestUrls.__dict__[key](self) def test_get_symbol_count(self):",
"import unittest import time from bs4 import BeautifulSoup from tests",
"for SBIN - EQ' resp = equity_history_url(symbol='SBIN', symbolCount=sym_count, series='EQ', fromDate='01-01-2000',",
"'31DEC2019') csv = unzip_str(resp.content) self.assertGreaterEqual(csv.find('SBIN'), 0) def tests_daily_volatility_url(self): resp =",
"derivative_price_list_url('2019', 'JUL', '19JUL2019') csv = unzip_str(resp.content) def tearDown(self): super().tearDown() if",
"print('tests OK') for (test, error) in result.errors: print('=========Error in: %s==========='",
"runTest(self): for key in TestUrls.__dict__.keys(): if key.find('test') == 0: TestUrls.__dict__[key](self)",
"0) def test_index_vix_history_url(self): resp = index_vix_history_url(fromDate='01-Jan-2015', toDate='10-Jan-2015', ) self.assertGreaterEqual(resp.text.find('VIX'), 0)",
"self.assertGreaterEqual(csv.find('Nifty IT'), 0) self.assertGreaterEqual(csv.find('Nifty Bank'), 0) self.assertGreaterEqual(csv.find('Nifty Next 50'), 0)",
"from bs4 import BeautifulSoup from tests import htmls import json",
"print(error) print('======================================') for (test, failures) in result.failures: print('=========Error in: %s==========='",
"urls.session.proxies.update({'http': 'proxy1.wipro.com:8080'}) def runTest(self): for key in TestUrls.__dict__.keys(): if key.find('test')",
"symbol='NIFTY', expiryDate='26-12-2019', optionType='select', strikePrice='', dateRange='', fromDate='25-Dec-2019', toDate='26-Dec-2019') self.assertGreaterEqual(resp.text.find('NIFTY'), 0) self.assertGreaterEqual(resp.text.find('Expiry'),",
"import * import nseta.common.urls as urls from six.moves.urllib.parse import urlparse",
"fromDate='01-01-2015', toDate='10-01-2015') self.assertGreaterEqual(resp.text.find('High'), 0) self.assertGreaterEqual(resp.text.find('Low'), 0) def test_index_daily_snapshot_url(self): resp =",
"index_daily_snapshot_url('06012020') csv = str(resp.content) self.assertGreaterEqual(csv.find('Nifty 50'), 0) self.assertGreaterEqual(csv.find('Nifty IT'), 0)",
"IT'), 0) self.assertGreaterEqual(csv.find('Nifty Bank'), 0) self.assertGreaterEqual(csv.find('Nifty Next 50'), 0) def",
"self.assertGreaterEqual(csv.find('SBIN'), 0) def tests_daily_volatility_url(self): resp = daily_volatility_url('19112015') self.assertGreaterEqual(resp.text.find('SBIN'), 0) def",
"TestUrls.__dict__[key](self) def test_get_symbol_count(self): count = get_symbol_count(symbol='SBIN') self.assertEqual(count, '1') force_count =",
"def tests_daily_volatility_url(self): resp = daily_volatility_url('19112015') self.assertGreaterEqual(resp.text.find('SBIN'), 0) def test_pr_price_list_zipped_url(self): resp",
"def test_derivative_history_url(self): resp = derivative_history_url(instrumentType='FUTIDX', symbol='NIFTY', expiryDate='26-12-2019', optionType='select', strikePrice='', dateRange='',",
"count = get_symbol_count(symbol='SBIN') self.assertEqual(count, '1') force_count = get_symbol_count(symbol='SBIN', force_refresh=True) self.assertEqual(force_count,",
"htmls import json import requests import six from nseta.common.urls import",
"0) self.assertGreaterEqual(resp.text.find('Low'), 0) def test_index_daily_snapshot_url(self): resp = index_daily_snapshot_url('06012020') csv =",
"self.assertGreaterEqual(resp.text.find('vixExpryDt'), 0) def test_derivative_history_url(self): resp = derivative_history_url(instrumentType='FUTIDX', symbol='NIFTY', expiryDate='26-12-2019', optionType='select',",
"0) def test_index_pe_history_url(self): resp = index_pe_history_url(fromDate='01-01-2015', toDate='10-01-2015', indexName='NIFTY 50') self.assertGreaterEqual(resp.text.find('<th>P/E'),",
"suite = unittest.TestLoader().loadTestsFromTestCase(TestUrls) result = unittest.TextTestRunner(verbosity=2).run(suite) if six.PY2: if result.wasSuccessful():",
"0) self.assertGreaterEqual(resp.text.find('<th>P/B'), 0) def test_index_vix_history_url(self): resp = index_vix_history_url(fromDate='01-Jan-2015', toDate='10-Jan-2015', )",
"0) self.assertGreaterEqual(csv.find('Nifty Next 50'), 0) def test_index_pe_history_url(self): resp = index_pe_history_url(fromDate='01-01-2015',",
"= get_symbol_count(symbol='SBIN') txt = 'Data for SBIN - EQ' resp",
"proxy_on = False if proxy_on: urls.session.proxies.update({'http': 'proxy1.wipro.com:8080'}) def runTest(self): for",
"force_count = get_symbol_count(symbol='SBIN', force_refresh=True) self.assertEqual(force_count, '1') def test_equity_history_url(self): sym_count =",
"self.assertGreaterEqual(resp.text.find('Low'), 0) def test_index_daily_snapshot_url(self): resp = index_daily_snapshot_url('06012020') csv = str(resp.content)",
"20:52:33 2015 @author: SW274998 ''' from nseta.common.commons import * import",
"indexName='NIFTY 50') self.assertGreaterEqual(resp.text.find('<th>P/E'), 0) self.assertGreaterEqual(resp.text.find('<th>P/B'), 0) def test_index_vix_history_url(self): resp =",
"''' from nseta.common.commons import * import datetime import unittest import",
"from nseta.common.commons import * import datetime import unittest import time",
"if key.find('test') == 0: TestUrls.__dict__[key](self) def test_get_symbol_count(self): count = get_symbol_count(symbol='SBIN')",
"EQ' resp = equity_history_url(symbol='SBIN', symbolCount=sym_count, series='EQ', fromDate='01-01-2000', toDate='10-01-2000', dateRange='') self.assertGreaterEqual(resp.text.find(txt),",
"TestUrls(baseUnitTest): def setUp(self, redirect_logs=True): super().setUp() proxy_on = False if proxy_on:",
"resp = derivative_expiry_dates_url() self.assertGreaterEqual(resp.text.find('vixExpryDt'), 0) def test_derivative_history_url(self): resp = derivative_history_url(instrumentType='FUTIDX',",
"import * import datetime import unittest import time from bs4",
"= unzip_str(resp.content) def test_index_history_url(self): resp = index_history_url(indexType='NIFTY 50', fromDate='01-01-2015', toDate='10-01-2015')",
"self.assertGreaterEqual(resp.text.find('NIFTY'), 0) self.assertGreaterEqual(resp.text.find('Expiry'), 0) def test_derivative_price_list_url(self): resp = derivative_price_list_url('2019', 'JUL',",
"super().tearDown() if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUrls) result =",
"'__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUrls) result = unittest.TextTestRunner(verbosity=2).run(suite) if six.PY2: if",
"fromDate='25-Dec-2019', toDate='26-Dec-2019') self.assertGreaterEqual(resp.text.find('NIFTY'), 0) self.assertGreaterEqual(resp.text.find('Expiry'), 0) def test_derivative_price_list_url(self): resp =",
"print('=========Error in: %s===========' % test) print(error) print('======================================') for (test, failures)",
"from six.moves.urllib.parse import urlparse from baseUnitTest import baseUnitTest class TestUrls(baseUnitTest):",
"txt = 'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL' #'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>' resp = nse_intraday_url(CDSymbol='SBIN', Periodicity='1') self.assertIn(txt, resp.text)",
"self.assertGreaterEqual(resp.text.find('<th>P/E'), 0) self.assertGreaterEqual(resp.text.find('<th>P/B'), 0) def test_index_vix_history_url(self): resp = index_vix_history_url(fromDate='01-Jan-2015', toDate='10-Jan-2015',",
"-*- ''' Created on Thu Nov 19 20:52:33 2015 @author:",
"import htmls import json import requests import six from nseta.common.urls",
"urlparse from baseUnitTest import baseUnitTest class TestUrls(baseUnitTest): def setUp(self, redirect_logs=True):",
"get_symbol_count(symbol='SBIN', force_refresh=True) self.assertEqual(force_count, '1') def test_equity_history_url(self): sym_count = get_symbol_count(symbol='SBIN') txt",
"2015 @author: SW274998 ''' from nseta.common.commons import * import datetime",
"'1') def test_equity_history_url(self): sym_count = get_symbol_count(symbol='SBIN') txt = 'Data for",
"50'), 0) def test_index_pe_history_url(self): resp = index_pe_history_url(fromDate='01-01-2015', toDate='10-01-2015', indexName='NIFTY 50')",
"strikePrice='', dateRange='', fromDate='25-Dec-2019', toDate='26-Dec-2019') self.assertGreaterEqual(resp.text.find('NIFTY'), 0) self.assertGreaterEqual(resp.text.find('Expiry'), 0) def test_derivative_price_list_url(self):",
"'JUL', '19JUL2019') csv = unzip_str(resp.content) def tearDown(self): super().tearDown() if __name__",
"== '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUrls) result = unittest.TextTestRunner(verbosity=2).run(suite) if six.PY2:",
"= get_symbol_count(symbol='SBIN') self.assertEqual(count, '1') force_count = get_symbol_count(symbol='SBIN', force_refresh=True) self.assertEqual(force_count, '1')",
"derivative_expiry_dates_url() self.assertGreaterEqual(resp.text.find('vixExpryDt'), 0) def test_derivative_history_url(self): resp = derivative_history_url(instrumentType='FUTIDX', symbol='NIFTY', expiryDate='26-12-2019',",
"= index_pe_history_url(fromDate='01-01-2015', toDate='10-01-2015', indexName='NIFTY 50') self.assertGreaterEqual(resp.text.find('<th>P/E'), 0) self.assertGreaterEqual(resp.text.find('<th>P/B'), 0) def",
"= derivative_history_url(instrumentType='FUTIDX', symbol='NIFTY', expiryDate='26-12-2019', optionType='select', strikePrice='', dateRange='', fromDate='25-Dec-2019', toDate='26-Dec-2019') self.assertGreaterEqual(resp.text.find('NIFTY'),",
"resp = index_pe_history_url(fromDate='01-01-2015', toDate='10-01-2015', indexName='NIFTY 50') self.assertGreaterEqual(resp.text.find('<th>P/E'), 0) self.assertGreaterEqual(resp.text.find('<th>P/B'), 0)",
"def runTest(self): for key in TestUrls.__dict__.keys(): if key.find('test') == 0:",
"dateRange='') self.assertGreaterEqual(resp.text.find(txt), 0, resp.text) def test_nse_intraday_url(self): txt = 'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL' #'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>'",
"resp = price_list_url('2019', 'DEC', '31DEC2019') csv = unzip_str(resp.content) self.assertGreaterEqual(csv.find('SBIN'), 0)",
"from tests import htmls import json import requests import six",
"= False if proxy_on: urls.session.proxies.update({'http': 'proxy1.wipro.com:8080'}) def runTest(self): for key",
"0) self.assertGreaterEqual(resp.text.find('Change'), 0) def test_derivative_derivative_expiry_dates_url(self): resp = derivative_expiry_dates_url() self.assertGreaterEqual(resp.text.find('vixExpryDt'), 0)",
"resp = derivative_history_url(instrumentType='FUTIDX', symbol='NIFTY', expiryDate='26-12-2019', optionType='select', strikePrice='', dateRange='', fromDate='25-Dec-2019', toDate='26-Dec-2019')",
"unittest.TestLoader().loadTestsFromTestCase(TestUrls) result = unittest.TextTestRunner(verbosity=2).run(suite) if six.PY2: if result.wasSuccessful(): print('tests OK')",
"if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUrls) result = unittest.TextTestRunner(verbosity=2).run(suite)",
"test_derivative_history_url(self): resp = derivative_history_url(instrumentType='FUTIDX', symbol='NIFTY', expiryDate='26-12-2019', optionType='select', strikePrice='', dateRange='', fromDate='25-Dec-2019',",
"error) in result.errors: print('=========Error in: %s===========' % test) print(error) print('======================================')",
"def test_equity_history_url(self): sym_count = get_symbol_count(symbol='SBIN') txt = 'Data for SBIN",
"toDate='26-Dec-2019') self.assertGreaterEqual(resp.text.find('NIFTY'), 0) self.assertGreaterEqual(resp.text.find('Expiry'), 0) def test_derivative_price_list_url(self): resp = derivative_price_list_url('2019',",
"in result.errors: print('=========Error in: %s===========' % test) print(error) print('======================================') for",
"= 'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL' #'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>' resp = nse_intraday_url(CDSymbol='SBIN', Periodicity='1') self.assertIn(txt, resp.text) def",
"= unzip_str(resp.content) self.assertGreaterEqual(csv.find('SBIN'), 0) def tests_daily_volatility_url(self): resp = daily_volatility_url('19112015') self.assertGreaterEqual(resp.text.find('SBIN'),",
"self.assertGreaterEqual(resp.text.find('SBIN'), 0) def test_pr_price_list_zipped_url(self): resp = pr_price_list_zipped_url('191115') csv = unzip_str(resp.content)",
"def test_get_symbol_count(self): count = get_symbol_count(symbol='SBIN') self.assertEqual(count, '1') force_count = get_symbol_count(symbol='SBIN',",
"for (test, failures) in result.failures: print('=========Error in: %s===========' % test)",
"key.find('test') == 0: TestUrls.__dict__[key](self) def test_get_symbol_count(self): count = get_symbol_count(symbol='SBIN') self.assertEqual(count,",
"test_index_pe_history_url(self): resp = index_pe_history_url(fromDate='01-01-2015', toDate='10-01-2015', indexName='NIFTY 50') self.assertGreaterEqual(resp.text.find('<th>P/E'), 0) self.assertGreaterEqual(resp.text.find('<th>P/B'),",
"= unittest.TestLoader().loadTestsFromTestCase(TestUrls) result = unittest.TextTestRunner(verbosity=2).run(suite) if six.PY2: if result.wasSuccessful(): print('tests",
"resp.text) def test_price_list_url(self): resp = price_list_url('2019', 'DEC', '31DEC2019') csv =",
"if result.wasSuccessful(): print('tests OK') for (test, error) in result.errors: print('=========Error",
"test_index_vix_history_url(self): resp = index_vix_history_url(fromDate='01-Jan-2015', toDate='10-Jan-2015', ) self.assertGreaterEqual(resp.text.find('VIX'), 0) self.assertGreaterEqual(resp.text.find('Change'), 0)",
"resp = index_daily_snapshot_url('06012020') csv = str(resp.content) self.assertGreaterEqual(csv.find('Nifty 50'), 0) self.assertGreaterEqual(csv.find('Nifty",
"nseta.common.commons import * import datetime import unittest import time from",
"test_derivative_price_list_url(self): resp = derivative_price_list_url('2019', 'JUL', '19JUL2019') csv = unzip_str(resp.content) def",
"= index_history_url(indexType='NIFTY 50', fromDate='01-01-2015', toDate='10-01-2015') self.assertGreaterEqual(resp.text.find('High'), 0) self.assertGreaterEqual(resp.text.find('Low'), 0) def",
"class TestUrls(baseUnitTest): def setUp(self, redirect_logs=True): super().setUp() proxy_on = False if",
"def tearDown(self): super().tearDown() if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestUrls)",
"-*- coding: utf-8 -*- ''' Created on Thu Nov 19",
"six from nseta.common.urls import * import nseta.common.urls as urls from",
"= unittest.TextTestRunner(verbosity=2).run(suite) if six.PY2: if result.wasSuccessful(): print('tests OK') for (test,",
"'proxy1.wipro.com:8080'}) def runTest(self): for key in TestUrls.__dict__.keys(): if key.find('test') ==",
"proxy_on: urls.session.proxies.update({'http': 'proxy1.wipro.com:8080'}) def runTest(self): for key in TestUrls.__dict__.keys(): if",
"(test, error) in result.errors: print('=========Error in: %s===========' % test) print(error)",
"resp = pr_price_list_zipped_url('191115') csv = unzip_str(resp.content) def test_index_history_url(self): resp =",
"unzip_str(resp.content) def tearDown(self): super().tearDown() if __name__ == '__main__': suite =",
"price_list_url('2019', 'DEC', '31DEC2019') csv = unzip_str(resp.content) self.assertGreaterEqual(csv.find('SBIN'), 0) def tests_daily_volatility_url(self):",
"= derivative_expiry_dates_url() self.assertGreaterEqual(resp.text.find('vixExpryDt'), 0) def test_derivative_history_url(self): resp = derivative_history_url(instrumentType='FUTIDX', symbol='NIFTY',",
"dateRange='', fromDate='25-Dec-2019', toDate='26-Dec-2019') self.assertGreaterEqual(resp.text.find('NIFTY'), 0) self.assertGreaterEqual(resp.text.find('Expiry'), 0) def test_derivative_price_list_url(self): resp",
"def test_derivative_price_list_url(self): resp = derivative_price_list_url('2019', 'JUL', '19JUL2019') csv = unzip_str(resp.content)",
"SBIN - EQ' resp = equity_history_url(symbol='SBIN', symbolCount=sym_count, series='EQ', fromDate='01-01-2000', toDate='10-01-2000',",
"= pr_price_list_zipped_url('191115') csv = unzip_str(resp.content) def test_index_history_url(self): resp = index_history_url(indexType='NIFTY",
"# -*- coding: utf-8 -*- ''' Created on Thu Nov",
"optionType='select', strikePrice='', dateRange='', fromDate='25-Dec-2019', toDate='26-Dec-2019') self.assertGreaterEqual(resp.text.find('NIFTY'), 0) self.assertGreaterEqual(resp.text.find('Expiry'), 0) def",
"= 'Data for SBIN - EQ' resp = equity_history_url(symbol='SBIN', symbolCount=sym_count,",
"nse_intraday_url(CDSymbol='SBIN', Periodicity='1') self.assertIn(txt, resp.text) def test_price_list_url(self): resp = price_list_url('2019', 'DEC',",
"test_get_symbol_count(self): count = get_symbol_count(symbol='SBIN') self.assertEqual(count, '1') force_count = get_symbol_count(symbol='SBIN', force_refresh=True)",
"0) def tests_daily_volatility_url(self): resp = daily_volatility_url('19112015') self.assertGreaterEqual(resp.text.find('SBIN'), 0) def test_pr_price_list_zipped_url(self):",
"= equity_history_url(symbol='SBIN', symbolCount=sym_count, series='EQ', fromDate='01-01-2000', toDate='10-01-2000', dateRange='') self.assertGreaterEqual(resp.text.find(txt), 0, resp.text)",
"50', fromDate='01-01-2015', toDate='10-01-2015') self.assertGreaterEqual(resp.text.find('High'), 0) self.assertGreaterEqual(resp.text.find('Low'), 0) def test_index_daily_snapshot_url(self): resp",
"toDate='10-01-2015') self.assertGreaterEqual(resp.text.find('High'), 0) self.assertGreaterEqual(resp.text.find('Low'), 0) def test_index_daily_snapshot_url(self): resp = index_daily_snapshot_url('06012020')",
"0) def test_derivative_price_list_url(self): resp = derivative_price_list_url('2019', 'JUL', '19JUL2019') csv =",
"failures) in result.failures: print('=========Error in: %s===========' % test) print(failures) print('======================================')",
"toDate='10-01-2000', dateRange='') self.assertGreaterEqual(resp.text.find(txt), 0, resp.text) def test_nse_intraday_url(self): txt = 'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL'",
"csv = unzip_str(resp.content) def test_index_history_url(self): resp = index_history_url(indexType='NIFTY 50', fromDate='01-01-2015',",
"Next 50'), 0) def test_index_pe_history_url(self): resp = index_pe_history_url(fromDate='01-01-2015', toDate='10-01-2015', indexName='NIFTY",
"index_pe_history_url(fromDate='01-01-2015', toDate='10-01-2015', indexName='NIFTY 50') self.assertGreaterEqual(resp.text.find('<th>P/E'), 0) self.assertGreaterEqual(resp.text.find('<th>P/B'), 0) def test_index_vix_history_url(self):",
"index_vix_history_url(fromDate='01-Jan-2015', toDate='10-Jan-2015', ) self.assertGreaterEqual(resp.text.find('VIX'), 0) self.assertGreaterEqual(resp.text.find('Change'), 0) def test_derivative_derivative_expiry_dates_url(self): resp",
"TestUrls.__dict__.keys(): if key.find('test') == 0: TestUrls.__dict__[key](self) def test_get_symbol_count(self): count =",
"series='EQ', fromDate='01-01-2000', toDate='10-01-2000', dateRange='') self.assertGreaterEqual(resp.text.find(txt), 0, resp.text) def test_nse_intraday_url(self): txt",
"resp = index_history_url(indexType='NIFTY 50', fromDate='01-01-2015', toDate='10-01-2015') self.assertGreaterEqual(resp.text.find('High'), 0) self.assertGreaterEqual(resp.text.find('Low'), 0)",
"force_refresh=True) self.assertEqual(force_count, '1') def test_equity_history_url(self): sym_count = get_symbol_count(symbol='SBIN') txt =",
"test_price_list_url(self): resp = price_list_url('2019', 'DEC', '31DEC2019') csv = unzip_str(resp.content) self.assertGreaterEqual(csv.find('SBIN'),",
"@author: SW274998 ''' from nseta.common.commons import * import datetime import",
"import six from nseta.common.urls import * import nseta.common.urls as urls",
"import datetime import unittest import time from bs4 import BeautifulSoup",
"0, resp.text) def test_nse_intraday_url(self): txt = 'date|g1_o|g1_h|g1_l|g1_c|g2|g2_CUMVOL' #'<columns><column>date</column><column>pltp</column><column>nltp</column><column>previousclose</column><column>allltp</column>' resp ="
] |
[
"[ (\"\", \"--Country--\"), ] + list(self.fields[\"billing_country\"].choices)[1:] self.fields[\"lead\"].queryset = Lead.objects.all( ).exclude(status='closed')",
"= kwargs.pop('request_user', None) super(AccountForm, self).__init__(*args, **kwargs) for field in self.fields.values():",
"self.fields['status'].required = False for key, value in self.fields.items(): if key",
"*args, **kwargs): account_view = kwargs.pop('account', False) request_user = kwargs.pop('request_user', None)",
"super(AccountForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs = {\"class\":",
"'8'}) self.fields['status'].choices = [ (each[0], each[1]) for each in Account.ACCOUNT_STATUS_CHOICE]",
"if account_view: self.fields['billing_address_line'].required = True self.fields['billing_street'].required = True self.fields['billing_city'].required =",
"django import forms from .models import Account from common.models import",
"**kwargs) for field in self.fields.values(): field.widget.attrs = {\"class\": \"form-control\"} self.fields['description'].widget.attrs.update({'rows':",
"fields = ('name', 'phone', 'email', 'website', 'industry', 'description', 'status', 'billing_address_line',",
"**kwargs): account_view = kwargs.pop('account', False) request_user = kwargs.pop('request_user', None) super(AccountForm,",
"'billing_address_line', 'billing_street', 'billing_city', 'billing_state', 'billing_postcode', 'billing_country', 'lead', 'contacts') class AccountCommentForm(forms.ModelForm):",
"True class Meta: model = Account fields = ('name', 'phone',",
"Q(created_by=request_user)).exclude(status='closed') self.fields[\"contacts\"].queryset = Contact.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)) if account_view: self.fields['billing_address_line'].required",
"'billing_street', 'billing_city', 'billing_state', 'billing_postcode', 'billing_country', 'lead', 'contacts') class AccountCommentForm(forms.ModelForm): comment",
"Lead.objects.all( ).exclude(status='closed') if request_user: self.fields[\"lead\"].queryset = Lead.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)).exclude(status='closed')",
"'placeholder': 'Postcode'}) self.fields[\"billing_country\"].choices = [ (\"\", \"--Country--\"), ] + list(self.fields[\"billing_country\"].choices)[1:]",
"Comment, Attachments from leads.models import Lead from contacts.models import Contact",
"field in self.fields.values(): field.widget.attrs = {\"class\": \"form-control\"} self.fields['description'].widget.attrs.update({'rows': '8'}) self.fields['status'].choices",
"True self.fields['billing_postcode'].required = True self.fields['billing_country'].required = True class Meta: model",
"Attachments from leads.models import Lead from contacts.models import Contact from",
"\"+91-123-456-7890\" else: value.widget.attrs['placeholder'] = value.label self.fields['billing_address_line'].widget.attrs.update({ 'placeholder': 'Address Line'}) self.fields['billing_street'].widget.attrs.update({",
"Contact from django.db.models import Q class AccountForm(forms.ModelForm): def __init__(self, *args,",
"= True self.fields['billing_state'].required = True self.fields['billing_postcode'].required = True self.fields['billing_country'].required =",
"'placeholder': 'State'}) self.fields['billing_postcode'].widget.attrs.update({ 'placeholder': 'Postcode'}) self.fields[\"billing_country\"].choices = [ (\"\", \"--Country--\"),",
"= [ (\"\", \"--Country--\"), ] + list(self.fields[\"billing_country\"].choices)[1:] self.fields[\"lead\"].queryset = Lead.objects.all(",
"for key, value in self.fields.items(): if key == 'phone': value.widget.attrs['placeholder']",
"in self.fields.items(): if key == 'phone': value.widget.attrs['placeholder'] = \"+91-123-456-7890\" else:",
"class Meta: model = Comment fields = ('comment', 'account', 'commented_by')",
"Comment fields = ('comment', 'account', 'commented_by') class AccountAttachmentForm(forms.ModelForm): attachment =",
"Q(created_by=request_user)) if account_view: self.fields['billing_address_line'].required = True self.fields['billing_street'].required = True self.fields['billing_city'].required",
"'placeholder': 'City'}) self.fields['billing_state'].widget.attrs.update({ 'placeholder': 'State'}) self.fields['billing_postcode'].widget.attrs.update({ 'placeholder': 'Postcode'}) self.fields[\"billing_country\"].choices =",
"self.fields['billing_city'].required = True self.fields['billing_state'].required = True self.fields['billing_postcode'].required = True self.fields['billing_country'].required",
"self.fields['description'].widget.attrs.update({'rows': '8'}) self.fields['status'].choices = [ (each[0], each[1]) for each in",
"Account.ACCOUNT_STATUS_CHOICE] self.fields['status'].required = False for key, value in self.fields.items(): if",
"] + list(self.fields[\"billing_country\"].choices)[1:] self.fields[\"lead\"].queryset = Lead.objects.all( ).exclude(status='closed') if request_user: self.fields[\"lead\"].queryset",
"Lead from contacts.models import Contact from django.db.models import Q class",
"self.fields['billing_country'].required = True class Meta: model = Account fields =",
"'industry', 'description', 'status', 'billing_address_line', 'billing_street', 'billing_city', 'billing_state', 'billing_postcode', 'billing_country', 'lead',",
"[ (each[0], each[1]) for each in Account.ACCOUNT_STATUS_CHOICE] self.fields['status'].required = False",
"Contact.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)) if account_view: self.fields['billing_address_line'].required = True self.fields['billing_street'].required",
"import Contact from django.db.models import Q class AccountForm(forms.ModelForm): def __init__(self,",
"attachment = forms.FileField(max_length=1001, required=True) class Meta: model = Attachments fields",
"if key == 'phone': value.widget.attrs['placeholder'] = \"+91-123-456-7890\" else: value.widget.attrs['placeholder'] =",
"required=True) class Meta: model = Comment fields = ('comment', 'account',",
"| Q(created_by=request_user)).exclude(status='closed') self.fields[\"contacts\"].queryset = Contact.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)) if account_view:",
"True self.fields['billing_street'].required = True self.fields['billing_city'].required = True self.fields['billing_state'].required = True",
"= True self.fields['billing_postcode'].required = True self.fields['billing_country'].required = True class Meta:",
"self.fields[\"lead\"].queryset = Lead.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)).exclude(status='closed') self.fields[\"contacts\"].queryset = Contact.objects.filter( Q(assigned_to__in=[request_user])",
"from django.db.models import Q class AccountForm(forms.ModelForm): def __init__(self, *args, **kwargs):",
"import Q class AccountForm(forms.ModelForm): def __init__(self, *args, **kwargs): account_view =",
"'billing_city', 'billing_state', 'billing_postcode', 'billing_country', 'lead', 'contacts') class AccountCommentForm(forms.ModelForm): comment =",
"AccountCommentForm(forms.ModelForm): comment = forms.CharField(max_length=64, required=True) class Meta: model = Comment",
"self.fields['billing_state'].required = True self.fields['billing_postcode'].required = True self.fields['billing_country'].required = True class",
"self.fields['billing_city'].widget.attrs.update({ 'placeholder': 'City'}) self.fields['billing_state'].widget.attrs.update({ 'placeholder': 'State'}) self.fields['billing_postcode'].widget.attrs.update({ 'placeholder': 'Postcode'}) self.fields[\"billing_country\"].choices",
"= True class Meta: model = Account fields = ('name',",
"forms.FileField(max_length=1001, required=True) class Meta: model = Attachments fields = ('attachment',",
"== 'phone': value.widget.attrs['placeholder'] = \"+91-123-456-7890\" else: value.widget.attrs['placeholder'] = value.label self.fields['billing_address_line'].widget.attrs.update({",
"'Postcode'}) self.fields[\"billing_country\"].choices = [ (\"\", \"--Country--\"), ] + list(self.fields[\"billing_country\"].choices)[1:] self.fields[\"lead\"].queryset",
"value in self.fields.items(): if key == 'phone': value.widget.attrs['placeholder'] = \"+91-123-456-7890\"",
"self.fields['billing_street'].required = True self.fields['billing_city'].required = True self.fields['billing_state'].required = True self.fields['billing_postcode'].required",
"= \"+91-123-456-7890\" else: value.widget.attrs['placeholder'] = value.label self.fields['billing_address_line'].widget.attrs.update({ 'placeholder': 'Address Line'})",
"__init__(self, *args, **kwargs): account_view = kwargs.pop('account', False) request_user = kwargs.pop('request_user',",
"self.fields[\"lead\"].queryset = Lead.objects.all( ).exclude(status='closed') if request_user: self.fields[\"lead\"].queryset = Lead.objects.filter( Q(assigned_to__in=[request_user])",
"class AccountAttachmentForm(forms.ModelForm): attachment = forms.FileField(max_length=1001, required=True) class Meta: model =",
"'description', 'status', 'billing_address_line', 'billing_street', 'billing_city', 'billing_state', 'billing_postcode', 'billing_country', 'lead', 'contacts')",
"import Lead from contacts.models import Contact from django.db.models import Q",
"('name', 'phone', 'email', 'website', 'industry', 'description', 'status', 'billing_address_line', 'billing_street', 'billing_city',",
"AccountAttachmentForm(forms.ModelForm): attachment = forms.FileField(max_length=1001, required=True) class Meta: model = Attachments",
"fields = ('comment', 'account', 'commented_by') class AccountAttachmentForm(forms.ModelForm): attachment = forms.FileField(max_length=1001,",
"self.fields['billing_state'].widget.attrs.update({ 'placeholder': 'State'}) self.fields['billing_postcode'].widget.attrs.update({ 'placeholder': 'Postcode'}) self.fields[\"billing_country\"].choices = [ (\"\",",
"from django import forms from .models import Account from common.models",
"for field in self.fields.values(): field.widget.attrs = {\"class\": \"form-control\"} self.fields['description'].widget.attrs.update({'rows': '8'})",
"in Account.ACCOUNT_STATUS_CHOICE] self.fields['status'].required = False for key, value in self.fields.items():",
"True self.fields['billing_state'].required = True self.fields['billing_postcode'].required = True self.fields['billing_country'].required = True",
"= ('comment', 'account', 'commented_by') class AccountAttachmentForm(forms.ModelForm): attachment = forms.FileField(max_length=1001, required=True)",
"'billing_postcode', 'billing_country', 'lead', 'contacts') class AccountCommentForm(forms.ModelForm): comment = forms.CharField(max_length=64, required=True)",
"value.label self.fields['billing_address_line'].widget.attrs.update({ 'placeholder': 'Address Line'}) self.fields['billing_street'].widget.attrs.update({ 'placeholder': 'Street'}) self.fields['billing_city'].widget.attrs.update({ 'placeholder':",
"request_user: self.fields[\"lead\"].queryset = Lead.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)).exclude(status='closed') self.fields[\"contacts\"].queryset = Contact.objects.filter(",
"request_user = kwargs.pop('request_user', None) super(AccountForm, self).__init__(*args, **kwargs) for field in",
").exclude(status='closed') if request_user: self.fields[\"lead\"].queryset = Lead.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)).exclude(status='closed') self.fields[\"contacts\"].queryset",
"Q class AccountForm(forms.ModelForm): def __init__(self, *args, **kwargs): account_view = kwargs.pop('account',",
"kwargs.pop('request_user', None) super(AccountForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs",
"each in Account.ACCOUNT_STATUS_CHOICE] self.fields['status'].required = False for key, value in",
"= True self.fields['billing_city'].required = True self.fields['billing_state'].required = True self.fields['billing_postcode'].required =",
"list(self.fields[\"billing_country\"].choices)[1:] self.fields[\"lead\"].queryset = Lead.objects.all( ).exclude(status='closed') if request_user: self.fields[\"lead\"].queryset = Lead.objects.filter(",
"key == 'phone': value.widget.attrs['placeholder'] = \"+91-123-456-7890\" else: value.widget.attrs['placeholder'] = value.label",
"= False for key, value in self.fields.items(): if key ==",
"import Comment, Attachments from leads.models import Lead from contacts.models import",
"None) super(AccountForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs =",
"self.fields['billing_address_line'].widget.attrs.update({ 'placeholder': 'Address Line'}) self.fields['billing_street'].widget.attrs.update({ 'placeholder': 'Street'}) self.fields['billing_city'].widget.attrs.update({ 'placeholder': 'City'})",
"'phone': value.widget.attrs['placeholder'] = \"+91-123-456-7890\" else: value.widget.attrs['placeholder'] = value.label self.fields['billing_address_line'].widget.attrs.update({ 'placeholder':",
"forms.CharField(max_length=64, required=True) class Meta: model = Comment fields = ('comment',",
"'website', 'industry', 'description', 'status', 'billing_address_line', 'billing_street', 'billing_city', 'billing_state', 'billing_postcode', 'billing_country',",
"key, value in self.fields.items(): if key == 'phone': value.widget.attrs['placeholder'] =",
"'account', 'commented_by') class AccountAttachmentForm(forms.ModelForm): attachment = forms.FileField(max_length=1001, required=True) class Meta:",
"kwargs.pop('account', False) request_user = kwargs.pop('request_user', None) super(AccountForm, self).__init__(*args, **kwargs) for",
"import forms from .models import Account from common.models import Comment,",
"(each[0], each[1]) for each in Account.ACCOUNT_STATUS_CHOICE] self.fields['status'].required = False for",
"each[1]) for each in Account.ACCOUNT_STATUS_CHOICE] self.fields['status'].required = False for key,",
"Meta: model = Comment fields = ('comment', 'account', 'commented_by') class",
"'Address Line'}) self.fields['billing_street'].widget.attrs.update({ 'placeholder': 'Street'}) self.fields['billing_city'].widget.attrs.update({ 'placeholder': 'City'}) self.fields['billing_state'].widget.attrs.update({ 'placeholder':",
"self.fields['billing_postcode'].required = True self.fields['billing_country'].required = True class Meta: model =",
"Meta: model = Account fields = ('name', 'phone', 'email', 'website',",
"(\"\", \"--Country--\"), ] + list(self.fields[\"billing_country\"].choices)[1:] self.fields[\"lead\"].queryset = Lead.objects.all( ).exclude(status='closed') if",
"model = Comment fields = ('comment', 'account', 'commented_by') class AccountAttachmentForm(forms.ModelForm):",
"forms from .models import Account from common.models import Comment, Attachments",
"self.fields.values(): field.widget.attrs = {\"class\": \"form-control\"} self.fields['description'].widget.attrs.update({'rows': '8'}) self.fields['status'].choices = [",
"True self.fields['billing_country'].required = True class Meta: model = Account fields",
"= forms.CharField(max_length=64, required=True) class Meta: model = Comment fields =",
"model = Account fields = ('name', 'phone', 'email', 'website', 'industry',",
"= True self.fields['billing_street'].required = True self.fields['billing_city'].required = True self.fields['billing_state'].required =",
"+ list(self.fields[\"billing_country\"].choices)[1:] self.fields[\"lead\"].queryset = Lead.objects.all( ).exclude(status='closed') if request_user: self.fields[\"lead\"].queryset =",
"required=True) class Meta: model = Attachments fields = ('attachment', 'account')",
".models import Account from common.models import Comment, Attachments from leads.models",
"leads.models import Lead from contacts.models import Contact from django.db.models import",
"account_view = kwargs.pop('account', False) request_user = kwargs.pop('request_user', None) super(AccountForm, self).__init__(*args,",
"contacts.models import Contact from django.db.models import Q class AccountForm(forms.ModelForm): def",
"field.widget.attrs = {\"class\": \"form-control\"} self.fields['description'].widget.attrs.update({'rows': '8'}) self.fields['status'].choices = [ (each[0],",
"value.widget.attrs['placeholder'] = value.label self.fields['billing_address_line'].widget.attrs.update({ 'placeholder': 'Address Line'}) self.fields['billing_street'].widget.attrs.update({ 'placeholder': 'Street'})",
"= True self.fields['billing_country'].required = True class Meta: model = Account",
"from contacts.models import Contact from django.db.models import Q class AccountForm(forms.ModelForm):",
"'email', 'website', 'industry', 'description', 'status', 'billing_address_line', 'billing_street', 'billing_city', 'billing_state', 'billing_postcode',",
"django.db.models import Q class AccountForm(forms.ModelForm): def __init__(self, *args, **kwargs): account_view",
"'lead', 'contacts') class AccountCommentForm(forms.ModelForm): comment = forms.CharField(max_length=64, required=True) class Meta:",
"= Comment fields = ('comment', 'account', 'commented_by') class AccountAttachmentForm(forms.ModelForm): attachment",
"if request_user: self.fields[\"lead\"].queryset = Lead.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)).exclude(status='closed') self.fields[\"contacts\"].queryset =",
"class AccountCommentForm(forms.ModelForm): comment = forms.CharField(max_length=64, required=True) class Meta: model =",
"AccountForm(forms.ModelForm): def __init__(self, *args, **kwargs): account_view = kwargs.pop('account', False) request_user",
"= Account fields = ('name', 'phone', 'email', 'website', 'industry', 'description',",
"from common.models import Comment, Attachments from leads.models import Lead from",
"'commented_by') class AccountAttachmentForm(forms.ModelForm): attachment = forms.FileField(max_length=1001, required=True) class Meta: model",
"self.fields[\"contacts\"].queryset = Contact.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)) if account_view: self.fields['billing_address_line'].required =",
"self.fields['billing_address_line'].required = True self.fields['billing_street'].required = True self.fields['billing_city'].required = True self.fields['billing_state'].required",
"Lead.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)).exclude(status='closed') self.fields[\"contacts\"].queryset = Contact.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user))",
"def __init__(self, *args, **kwargs): account_view = kwargs.pop('account', False) request_user =",
"Q(assigned_to__in=[request_user]) | Q(created_by=request_user)) if account_view: self.fields['billing_address_line'].required = True self.fields['billing_street'].required =",
"common.models import Comment, Attachments from leads.models import Lead from contacts.models",
"from leads.models import Lead from contacts.models import Contact from django.db.models",
"self.fields['billing_postcode'].widget.attrs.update({ 'placeholder': 'Postcode'}) self.fields[\"billing_country\"].choices = [ (\"\", \"--Country--\"), ] +",
"from .models import Account from common.models import Comment, Attachments from",
"self.fields.items(): if key == 'phone': value.widget.attrs['placeholder'] = \"+91-123-456-7890\" else: value.widget.attrs['placeholder']",
"'placeholder': 'Address Line'}) self.fields['billing_street'].widget.attrs.update({ 'placeholder': 'Street'}) self.fields['billing_city'].widget.attrs.update({ 'placeholder': 'City'}) self.fields['billing_state'].widget.attrs.update({",
"Account fields = ('name', 'phone', 'email', 'website', 'industry', 'description', 'status',",
"| Q(created_by=request_user)) if account_view: self.fields['billing_address_line'].required = True self.fields['billing_street'].required = True",
"self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs = {\"class\": \"form-control\"}",
"self.fields['status'].choices = [ (each[0], each[1]) for each in Account.ACCOUNT_STATUS_CHOICE] self.fields['status'].required",
"account_view: self.fields['billing_address_line'].required = True self.fields['billing_street'].required = True self.fields['billing_city'].required = True",
"= ('name', 'phone', 'email', 'website', 'industry', 'description', 'status', 'billing_address_line', 'billing_street',",
"self.fields[\"billing_country\"].choices = [ (\"\", \"--Country--\"), ] + list(self.fields[\"billing_country\"].choices)[1:] self.fields[\"lead\"].queryset =",
"self.fields['billing_street'].widget.attrs.update({ 'placeholder': 'Street'}) self.fields['billing_city'].widget.attrs.update({ 'placeholder': 'City'}) self.fields['billing_state'].widget.attrs.update({ 'placeholder': 'State'}) self.fields['billing_postcode'].widget.attrs.update({",
"{\"class\": \"form-control\"} self.fields['description'].widget.attrs.update({'rows': '8'}) self.fields['status'].choices = [ (each[0], each[1]) for",
"value.widget.attrs['placeholder'] = \"+91-123-456-7890\" else: value.widget.attrs['placeholder'] = value.label self.fields['billing_address_line'].widget.attrs.update({ 'placeholder': 'Address",
"False) request_user = kwargs.pop('request_user', None) super(AccountForm, self).__init__(*args, **kwargs) for field",
"\"--Country--\"), ] + list(self.fields[\"billing_country\"].choices)[1:] self.fields[\"lead\"].queryset = Lead.objects.all( ).exclude(status='closed') if request_user:",
"'billing_country', 'lead', 'contacts') class AccountCommentForm(forms.ModelForm): comment = forms.CharField(max_length=64, required=True) class",
"'billing_state', 'billing_postcode', 'billing_country', 'lead', 'contacts') class AccountCommentForm(forms.ModelForm): comment = forms.CharField(max_length=64,",
"class Meta: model = Account fields = ('name', 'phone', 'email',",
"= Lead.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)).exclude(status='closed') self.fields[\"contacts\"].queryset = Contact.objects.filter( Q(assigned_to__in=[request_user]) |",
"comment = forms.CharField(max_length=64, required=True) class Meta: model = Comment fields",
"'State'}) self.fields['billing_postcode'].widget.attrs.update({ 'placeholder': 'Postcode'}) self.fields[\"billing_country\"].choices = [ (\"\", \"--Country--\"), ]",
"'City'}) self.fields['billing_state'].widget.attrs.update({ 'placeholder': 'State'}) self.fields['billing_postcode'].widget.attrs.update({ 'placeholder': 'Postcode'}) self.fields[\"billing_country\"].choices = [",
"('comment', 'account', 'commented_by') class AccountAttachmentForm(forms.ModelForm): attachment = forms.FileField(max_length=1001, required=True) class",
"Q(assigned_to__in=[request_user]) | Q(created_by=request_user)).exclude(status='closed') self.fields[\"contacts\"].queryset = Contact.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)) if",
"Account from common.models import Comment, Attachments from leads.models import Lead",
"class AccountForm(forms.ModelForm): def __init__(self, *args, **kwargs): account_view = kwargs.pop('account', False)",
"= [ (each[0], each[1]) for each in Account.ACCOUNT_STATUS_CHOICE] self.fields['status'].required =",
"= kwargs.pop('account', False) request_user = kwargs.pop('request_user', None) super(AccountForm, self).__init__(*args, **kwargs)",
"'placeholder': 'Street'}) self.fields['billing_city'].widget.attrs.update({ 'placeholder': 'City'}) self.fields['billing_state'].widget.attrs.update({ 'placeholder': 'State'}) self.fields['billing_postcode'].widget.attrs.update({ 'placeholder':",
"import Account from common.models import Comment, Attachments from leads.models import",
"= {\"class\": \"form-control\"} self.fields['description'].widget.attrs.update({'rows': '8'}) self.fields['status'].choices = [ (each[0], each[1])",
"= value.label self.fields['billing_address_line'].widget.attrs.update({ 'placeholder': 'Address Line'}) self.fields['billing_street'].widget.attrs.update({ 'placeholder': 'Street'}) self.fields['billing_city'].widget.attrs.update({",
"= Lead.objects.all( ).exclude(status='closed') if request_user: self.fields[\"lead\"].queryset = Lead.objects.filter( Q(assigned_to__in=[request_user]) |",
"\"form-control\"} self.fields['description'].widget.attrs.update({'rows': '8'}) self.fields['status'].choices = [ (each[0], each[1]) for each",
"= Contact.objects.filter( Q(assigned_to__in=[request_user]) | Q(created_by=request_user)) if account_view: self.fields['billing_address_line'].required = True",
"'status', 'billing_address_line', 'billing_street', 'billing_city', 'billing_state', 'billing_postcode', 'billing_country', 'lead', 'contacts') class",
"'phone', 'email', 'website', 'industry', 'description', 'status', 'billing_address_line', 'billing_street', 'billing_city', 'billing_state',",
"in self.fields.values(): field.widget.attrs = {\"class\": \"form-control\"} self.fields['description'].widget.attrs.update({'rows': '8'}) self.fields['status'].choices =",
"'contacts') class AccountCommentForm(forms.ModelForm): comment = forms.CharField(max_length=64, required=True) class Meta: model",
"= forms.FileField(max_length=1001, required=True) class Meta: model = Attachments fields =",
"'Street'}) self.fields['billing_city'].widget.attrs.update({ 'placeholder': 'City'}) self.fields['billing_state'].widget.attrs.update({ 'placeholder': 'State'}) self.fields['billing_postcode'].widget.attrs.update({ 'placeholder': 'Postcode'})",
"False for key, value in self.fields.items(): if key == 'phone':",
"else: value.widget.attrs['placeholder'] = value.label self.fields['billing_address_line'].widget.attrs.update({ 'placeholder': 'Address Line'}) self.fields['billing_street'].widget.attrs.update({ 'placeholder':",
"for each in Account.ACCOUNT_STATUS_CHOICE] self.fields['status'].required = False for key, value",
"True self.fields['billing_city'].required = True self.fields['billing_state'].required = True self.fields['billing_postcode'].required = True",
"Line'}) self.fields['billing_street'].widget.attrs.update({ 'placeholder': 'Street'}) self.fields['billing_city'].widget.attrs.update({ 'placeholder': 'City'}) self.fields['billing_state'].widget.attrs.update({ 'placeholder': 'State'})"
] |
[
"# Runtime self.invocation_retry = retry_config['invocation_retry'] self.retry_sleeps = retry_config['retry_sleeps'] self.retries =",
"logging import random from pywren_ibm_cloud.cf_connector import CloudFunctions logger = logging.getLogger(__name__)",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"seconds'.format(exec_id, call_id, attempts, selected_sleep)) logger.debug(log_msg) time.sleep(selected_sleep) act_id = self.client.invoke(self.cf_action_name, payload)",
"# # 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,",
"import logging import random from pywren_ibm_cloud.cf_connector import CloudFunctions logger =",
"retry {} in {} seconds'.format(exec_id, call_id, attempts, selected_sleep)) logger.debug(log_msg) time.sleep(selected_sleep)",
"# limitations under the License. # import time import logging",
"act_id def config(self): \"\"\" Return config dict \"\"\" return {'cf_action_name':",
"Team # # Licensed under the Apache License, Version 2.0",
"= cf_config['endpoint'] self.cf_action_name = cf_config['action_name'] # Runtime self.invocation_retry = retry_config['invocation_retry']",
"and self.invocation_retry and attempts < self.retries: attempts += 1 selected_sleep",
"distributed under the License is distributed on an \"AS IS\"",
"config(self): \"\"\" Return config dict \"\"\" return {'cf_action_name': self.cf_action_name, 'cf_namespace':",
"exec_id = payload['executor_id'] call_id = payload['call_id'] log_msg = ('Executor ID",
"self.retries: attempts += 1 selected_sleep = random.choice(self.retry_sleeps) exec_id = payload['executor_id']",
"limitations under the License. # import time import logging import",
"Functions init for {}'.format(self.cf_action_name) logger.info(log_msg) if(logger.getEffectiveLevel() == logging.WARNING): print(log_msg) def",
"Invocation failed - retry {} in {} seconds'.format(exec_id, call_id, attempts,",
"# # Copyright 2018 PyWren Team # # Licensed under",
"= cf_config['namespace'] self.endpoint = cf_config['endpoint'] self.cf_action_name = cf_config['action_name'] # Runtime",
"the specific language governing permissions and # limitations under the",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"IBMCloudFunctionsInvoker: def __init__(self, cf_config, retry_config): self.namespace = cf_config['namespace'] self.endpoint =",
"return act_id def config(self): \"\"\" Return config dict \"\"\" return",
"self.endpoint = cf_config['endpoint'] self.cf_action_name = cf_config['action_name'] # Runtime self.invocation_retry =",
"express or implied. # See the License for the specific",
"applicable law or agreed to in writing, software # distributed",
"except in compliance with the License. # You may obtain",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"the License. # import time import logging import random from",
"pywren_ibm_cloud.cf_connector import CloudFunctions logger = logging.getLogger(__name__) class IBMCloudFunctionsInvoker: def __init__(self,",
"Invoke -- return information about this invocation \"\"\" act_id =",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"under the License. # import time import logging import random",
"selected_sleep)) logger.debug(log_msg) time.sleep(selected_sleep) act_id = self.client.invoke(self.cf_action_name, payload) return act_id def",
"logger = logging.getLogger(__name__) class IBMCloudFunctionsInvoker: def __init__(self, cf_config, retry_config): self.namespace",
"not use this file except in compliance with the License.",
"self.retries = retry_config['retries'] self.client = CloudFunctions(cf_config) log_msg = 'IBM Cloud",
"config dict \"\"\" return {'cf_action_name': self.cf_action_name, 'cf_namespace': self.namespace, 'cf_endpoint': self.endpoint}",
"cf_config, retry_config): self.namespace = cf_config['namespace'] self.endpoint = cf_config['endpoint'] self.cf_action_name =",
"'IBM Cloud Functions init for {}'.format(self.cf_action_name) logger.info(log_msg) if(logger.getEffectiveLevel() == logging.WARNING):",
"= self.client.invoke(self.cf_action_name, payload) return act_id def config(self): \"\"\" Return config",
"self.cf_action_name = cf_config['action_name'] # Runtime self.invocation_retry = retry_config['invocation_retry'] self.retry_sleeps =",
"writing, software # distributed under the License is distributed on",
"= self.client.invoke(self.cf_action_name, payload) attempts = 1 while not act_id and",
"in writing, software # distributed under the License is distributed",
"you may not use this file except in compliance with",
"random from pywren_ibm_cloud.cf_connector import CloudFunctions logger = logging.getLogger(__name__) class IBMCloudFunctionsInvoker:",
"about this invocation \"\"\" act_id = self.client.invoke(self.cf_action_name, payload) attempts =",
"self.client.invoke(self.cf_action_name, payload) attempts = 1 while not act_id and self.invocation_retry",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"attempts < self.retries: attempts += 1 selected_sleep = random.choice(self.retry_sleeps) exec_id",
"= 'IBM Cloud Functions init for {}'.format(self.cf_action_name) logger.info(log_msg) if(logger.getEffectiveLevel() ==",
"Copyright 2018 PyWren Team # # Licensed under the Apache",
"invocation \"\"\" act_id = self.client.invoke(self.cf_action_name, payload) attempts = 1 while",
"{}'.format(self.cf_action_name) logger.info(log_msg) if(logger.getEffectiveLevel() == logging.WARNING): print(log_msg) def invoke(self, payload): \"\"\"",
"logging.WARNING): print(log_msg) def invoke(self, payload): \"\"\" Invoke -- return information",
"cf_config['action_name'] # Runtime self.invocation_retry = retry_config['invocation_retry'] self.retry_sleeps = retry_config['retry_sleeps'] self.retries",
"Runtime self.invocation_retry = retry_config['invocation_retry'] self.retry_sleeps = retry_config['retry_sleeps'] self.retries = retry_config['retries']",
"__init__(self, cf_config, retry_config): self.namespace = cf_config['namespace'] self.endpoint = cf_config['endpoint'] self.cf_action_name",
"use this file except in compliance with the License. #",
"attempts = 1 while not act_id and self.invocation_retry and attempts",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"Return config dict \"\"\" return {'cf_action_name': self.cf_action_name, 'cf_namespace': self.namespace, 'cf_endpoint':",
"-- return information about this invocation \"\"\" act_id = self.client.invoke(self.cf_action_name,",
"while not act_id and self.invocation_retry and attempts < self.retries: attempts",
"and attempts < self.retries: attempts += 1 selected_sleep = random.choice(self.retry_sleeps)",
"logger.debug(log_msg) time.sleep(selected_sleep) act_id = self.client.invoke(self.cf_action_name, payload) return act_id def config(self):",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"failed - retry {} in {} seconds'.format(exec_id, call_id, attempts, selected_sleep))",
"logging.getLogger(__name__) class IBMCloudFunctionsInvoker: def __init__(self, cf_config, retry_config): self.namespace = cf_config['namespace']",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"selected_sleep = random.choice(self.retry_sleeps) exec_id = payload['executor_id'] call_id = payload['call_id'] log_msg",
"\"\"\" Invoke -- return information about this invocation \"\"\" act_id",
"or implied. # See the License for the specific language",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"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",
"attempts += 1 selected_sleep = random.choice(self.retry_sleeps) exec_id = payload['executor_id'] call_id",
"# 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.",
"= retry_config['retry_sleeps'] self.retries = retry_config['retries'] self.client = CloudFunctions(cf_config) log_msg =",
"= payload['executor_id'] call_id = payload['call_id'] log_msg = ('Executor ID {}",
"call_id = payload['call_id'] log_msg = ('Executor ID {} Function {}",
"def config(self): \"\"\" Return config dict \"\"\" return {'cf_action_name': self.cf_action_name,",
"under the License is distributed on an \"AS IS\" BASIS,",
"self.client.invoke(self.cf_action_name, payload) return act_id def config(self): \"\"\" Return config dict",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"- retry {} in {} seconds'.format(exec_id, call_id, attempts, selected_sleep)) logger.debug(log_msg)",
"License for the specific language governing permissions and # limitations",
"retry_config['invocation_retry'] self.retry_sleeps = retry_config['retry_sleeps'] self.retries = retry_config['retries'] self.client = CloudFunctions(cf_config)",
"1 selected_sleep = random.choice(self.retry_sleeps) exec_id = payload['executor_id'] call_id = payload['call_id']",
"in {} seconds'.format(exec_id, call_id, attempts, selected_sleep)) logger.debug(log_msg) time.sleep(selected_sleep) act_id =",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"information about this invocation \"\"\" act_id = self.client.invoke(self.cf_action_name, payload) attempts",
"= retry_config['retries'] self.client = CloudFunctions(cf_config) log_msg = 'IBM Cloud Functions",
"def invoke(self, payload): \"\"\" Invoke -- return information about this",
"< self.retries: attempts += 1 selected_sleep = random.choice(self.retry_sleeps) exec_id =",
"payload): \"\"\" Invoke -- return information about this invocation \"\"\"",
"and # limitations under the License. # import time import",
"call_id, attempts, selected_sleep)) logger.debug(log_msg) time.sleep(selected_sleep) act_id = self.client.invoke(self.cf_action_name, payload) return",
"def __init__(self, cf_config, retry_config): self.namespace = cf_config['namespace'] self.endpoint = cf_config['endpoint']",
"print(log_msg) def invoke(self, payload): \"\"\" Invoke -- return information about",
"cf_config['endpoint'] self.cf_action_name = cf_config['action_name'] # Runtime self.invocation_retry = retry_config['invocation_retry'] self.retry_sleeps",
"= ('Executor ID {} Function {} - Invocation failed -",
"act_id = self.client.invoke(self.cf_action_name, payload) attempts = 1 while not act_id",
"# import time import logging import random from pywren_ibm_cloud.cf_connector import",
"the License for the specific language governing permissions and #",
"(the \"License\"); # you may not use this file except",
"import time import logging import random from pywren_ibm_cloud.cf_connector import CloudFunctions",
"retry_config['retries'] self.client = CloudFunctions(cf_config) log_msg = 'IBM Cloud Functions init",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"# you may not use this file except in compliance",
"self.invocation_retry = retry_config['invocation_retry'] self.retry_sleeps = retry_config['retry_sleeps'] self.retries = retry_config['retries'] self.client",
"either express or implied. # See the License for the",
"self.namespace = cf_config['namespace'] self.endpoint = cf_config['endpoint'] self.cf_action_name = cf_config['action_name'] #",
"log_msg = 'IBM Cloud Functions init for {}'.format(self.cf_action_name) logger.info(log_msg) if(logger.getEffectiveLevel()",
"{} in {} seconds'.format(exec_id, call_id, attempts, selected_sleep)) logger.debug(log_msg) time.sleep(selected_sleep) act_id",
"CloudFunctions(cf_config) log_msg = 'IBM Cloud Functions init for {}'.format(self.cf_action_name) logger.info(log_msg)",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"= CloudFunctions(cf_config) log_msg = 'IBM Cloud Functions init for {}'.format(self.cf_action_name)",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"act_id and self.invocation_retry and attempts < self.retries: attempts += 1",
"random.choice(self.retry_sleeps) exec_id = payload['executor_id'] call_id = payload['call_id'] log_msg = ('Executor",
"the License is distributed on an \"AS IS\" BASIS, #",
"= retry_config['invocation_retry'] self.retry_sleeps = retry_config['retry_sleeps'] self.retries = retry_config['retries'] self.client =",
"= random.choice(self.retry_sleeps) exec_id = payload['executor_id'] call_id = payload['call_id'] log_msg =",
"2018 PyWren Team # # Licensed under the Apache License,",
"in compliance with the License. # You may obtain a",
"self.client = CloudFunctions(cf_config) log_msg = 'IBM Cloud Functions init for",
"- Invocation failed - retry {} in {} seconds'.format(exec_id, call_id,",
"software # distributed under the License is distributed on an",
"{} seconds'.format(exec_id, call_id, attempts, selected_sleep)) logger.debug(log_msg) time.sleep(selected_sleep) act_id = self.client.invoke(self.cf_action_name,",
"payload['call_id'] log_msg = ('Executor ID {} Function {} - Invocation",
"# # Unless required by applicable law or agreed to",
"import CloudFunctions logger = logging.getLogger(__name__) class IBMCloudFunctionsInvoker: def __init__(self, cf_config,",
"time import logging import random from pywren_ibm_cloud.cf_connector import CloudFunctions logger",
"init for {}'.format(self.cf_action_name) logger.info(log_msg) if(logger.getEffectiveLevel() == logging.WARNING): print(log_msg) def invoke(self,",
"= cf_config['action_name'] # Runtime self.invocation_retry = retry_config['invocation_retry'] self.retry_sleeps = retry_config['retry_sleeps']",
"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",
"payload) attempts = 1 while not act_id and self.invocation_retry and",
"attempts, selected_sleep)) logger.debug(log_msg) time.sleep(selected_sleep) act_id = self.client.invoke(self.cf_action_name, payload) return act_id",
"Version 2.0 (the \"License\"); # you may not use this",
"License. # import time import logging import random from pywren_ibm_cloud.cf_connector",
"cf_config['namespace'] self.endpoint = cf_config['endpoint'] self.cf_action_name = cf_config['action_name'] # Runtime self.invocation_retry",
"law or agreed to in writing, software # distributed under",
"from pywren_ibm_cloud.cf_connector import CloudFunctions logger = logging.getLogger(__name__) class IBMCloudFunctionsInvoker: def",
"governing permissions and # limitations under the License. # import",
"act_id = self.client.invoke(self.cf_action_name, payload) return act_id def config(self): \"\"\" Return",
"= 1 while not act_id and self.invocation_retry and attempts <",
"{} Function {} - Invocation failed - retry {} in",
"\"\"\" act_id = self.client.invoke(self.cf_action_name, payload) attempts = 1 while not",
"payload['executor_id'] call_id = payload['call_id'] log_msg = ('Executor ID {} Function",
"implied. # See the License for the specific language governing",
"1 while not act_id and self.invocation_retry and attempts < self.retries:",
"self.retry_sleeps = retry_config['retry_sleeps'] self.retries = retry_config['retries'] self.client = CloudFunctions(cf_config) log_msg",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"\"License\"); # you may not use this file except in",
"CloudFunctions logger = logging.getLogger(__name__) class IBMCloudFunctionsInvoker: def __init__(self, cf_config, retry_config):",
"\"\"\" Return config dict \"\"\" return {'cf_action_name': self.cf_action_name, 'cf_namespace': self.namespace,",
"import random from pywren_ibm_cloud.cf_connector import CloudFunctions logger = logging.getLogger(__name__) class",
"= payload['call_id'] log_msg = ('Executor ID {} Function {} -",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"for {}'.format(self.cf_action_name) logger.info(log_msg) if(logger.getEffectiveLevel() == logging.WARNING): print(log_msg) def invoke(self, payload):",
"this invocation \"\"\" act_id = self.client.invoke(self.cf_action_name, payload) attempts = 1",
"payload) return act_id def config(self): \"\"\" Return config dict \"\"\"",
"= logging.getLogger(__name__) class IBMCloudFunctionsInvoker: def __init__(self, cf_config, retry_config): self.namespace =",
"retry_config): self.namespace = cf_config['namespace'] self.endpoint = cf_config['endpoint'] self.cf_action_name = cf_config['action_name']",
"logger.info(log_msg) if(logger.getEffectiveLevel() == logging.WARNING): print(log_msg) def invoke(self, payload): \"\"\" Invoke",
"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.",
"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",
"ID {} Function {} - Invocation failed - retry {}",
"time.sleep(selected_sleep) act_id = self.client.invoke(self.cf_action_name, payload) return act_id def config(self): \"\"\"",
"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",
"invoke(self, payload): \"\"\" Invoke -- return information about this invocation",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"to in writing, software # distributed under the License is",
"retry_config['retry_sleeps'] self.retries = retry_config['retries'] self.client = CloudFunctions(cf_config) log_msg = 'IBM",
"== logging.WARNING): print(log_msg) def invoke(self, payload): \"\"\" Invoke -- return",
"log_msg = ('Executor ID {} Function {} - Invocation failed",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"# See the License for the specific language governing permissions",
"not act_id and self.invocation_retry and attempts < self.retries: attempts +=",
"return information about this invocation \"\"\" act_id = self.client.invoke(self.cf_action_name, payload)",
"self.invocation_retry and attempts < self.retries: attempts += 1 selected_sleep =",
"('Executor ID {} Function {} - Invocation failed - retry",
"You may obtain a copy of the License at #",
"+= 1 selected_sleep = random.choice(self.retry_sleeps) exec_id = payload['executor_id'] call_id =",
"language governing permissions and # limitations under the License. #",
"may not use this file except in compliance with the",
"or agreed to in writing, software # distributed under the",
"Cloud Functions init for {}'.format(self.cf_action_name) logger.info(log_msg) if(logger.getEffectiveLevel() == logging.WARNING): print(log_msg)",
"required by applicable law or agreed to in writing, software",
"class IBMCloudFunctionsInvoker: def __init__(self, cf_config, retry_config): self.namespace = cf_config['namespace'] self.endpoint",
"permissions and # limitations under the License. # import time",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# Copyright 2018 PyWren Team # # Licensed under the",
"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",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"if(logger.getEffectiveLevel() == logging.WARNING): print(log_msg) def invoke(self, payload): \"\"\" Invoke --",
"Function {} - Invocation failed - retry {} in {}",
"PyWren Team # # Licensed under the Apache License, Version",
"{} - Invocation failed - retry {} in {} seconds'.format(exec_id,"
] |
[
"= 0.4 FourAndAbove = 0.2 pickInside = 0.5 pickOutside =",
"\".\"): siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([]) for filename in os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName): if(filename[0] != \".\"):",
"\"./original\" outputDirectory = \"./processed\" #probability parameters TopLevel = 0.6 SecondLevel",
"and randomPick > TopLevel): selectedLevel = 2 if(randomPick <= TopLevel",
"FourAndAbove and randomPick > TopLevel + SecondLevel + ThirdLevel): if(len(siteLevel[selectedTopic])",
"= findPossibleIndex(currentLine) insertPosition = possibleIndexes[random.randint(0,len(possibleIndexes)-1)] selectedTopic = topicIndex if(randomPick<=pickOutside): while(selectedTopic",
"i<len(siteLevel[selectedTopic]): if siteLevel[selectedTopic][i] == str(selectedLevel)+\"grade\": found = True selectedLevel =",
"selectedLevel = 0 if(randomPick <= TopLevel): selectedLevel = 1 if(randomPick",
"SecondLevel + ThirdLevel + FourAndAbove and randomPick > TopLevel +",
"fileLink else: currentLine = currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:] outputFile += currentLine output.write(outputFile) return",
"= 0.5 ThirdLevel = 0.4 FourAndAbove = 0.2 pickInside =",
"if(filename[0] != \".\"): fileStructure[topicIndex][levelIndex].append(filename) levelIndex += 1 topicIndex += 1",
"!= \".\"): siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([]) for filename in os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName): if(filename[0] !=",
"+ SecondLevel + ThirdLevel): if(len(siteLevel[selectedTopic]) == 4): selectedLevel = 4",
"= 0.6 SecondLevel = 0.5 ThirdLevel = 0.4 FourAndAbove =",
"count topicIndex=0 for foldername in os.listdir(inputDirectory) : if(foldername[0] != \".\"):",
"ThirdLevel): if(len(siteLevel[selectedTopic]) == 4): selectedLevel = 4 else: selectedLevel =",
"= content.readline() randomPick = random.uniform(0.0,2.0) if randomPick <= pickInside+pickOutside :",
"= [] fileStructure = [] count = 0 def findPossibleIndex(toParse):",
"currentLine: currentLine = content.readline() randomPick = random.uniform(0.0,2.0) if randomPick <=",
"siteLevel.append([]) fileStructure.append([]) levelIndex=0 for categoryName in os.listdir(inputDirectory+\"/\"+foldername): if(categoryName[0] != \".\"):",
"siteLevel = [] fileStructure = [] count = 0 def",
"\"\" while currentLine: currentLine = content.readline() randomPick = random.uniform(0.0,2.0) if",
"== len(currentLine): currentLine += fileLink else: currentLine = currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:] outputFile",
"= random.randint(0,len(topics)-1) randomPick = random.uniform(0.0,4.0) if(randomPick <= TopLevel + SecondLevel",
"= filename while(fileLink == filename): fileLink = fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)] fileLink =",
"+ SecondLevel + ThirdLevel + FourAndAbove and randomPick > TopLevel",
"outputDirectory = \"./processed\" #probability parameters TopLevel = 0.6 SecondLevel =",
"= random.uniform(0.0,2.0) if randomPick <= pickInside+pickOutside : possibleIndexes = findPossibleIndex(currentLine)",
"random.uniform(0.0,4.0) if(randomPick <= TopLevel + SecondLevel + ThirdLevel + FourAndAbove):",
"> TopLevel): selectedLevel = 2 if(randomPick <= TopLevel + SecondLevel",
"for k in range(0,len(fileStructure[i][j])): count += manageFile(inputDirectory+\"/\"+topics[i]+\"/\"+siteLevel[i][j]+\"/\"+fileStructure[i][j][k],outputDirectory+\"/\"+fileStructure[i][j][k],i,j,fileStructure[i][j][k]) print(str(count)+\" liens créés\")",
"= [] for current in range(0,len(toParse)): if toParse[current] == \"",
"SecondLevel + ThirdLevel): if(len(siteLevel[selectedTopic]) == 4): selectedLevel = 4 else:",
"print(count) if insertPosition == len(currentLine): currentLine += fileLink else: currentLine",
"content.readline() outputFile = \"\" while currentLine: currentLine = content.readline() randomPick",
"= 0.25 topics = [] siteLevel = [] fileStructure =",
"= 1 if(randomPick <= TopLevel+ SecondLevel and randomPick > TopLevel):",
"fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)] fileLink = \" linkTo:\"+fileLink count += 1 print(count) if",
"for foldername in os.listdir(inputDirectory) : if(foldername[0] != \".\"): topics.append(foldername) siteLevel.append([])",
"i+=1 if(selectedLevel>=currentLevel): fileLink = filename while(fileLink == filename): fileLink =",
"os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName): if(filename[0] != \".\"): fileStructure[topicIndex][levelIndex].append(filename) levelIndex += 1 topicIndex +=",
"in range(0,len(toParse)): if toParse[current] == \" \": toReturn.append(current) toReturn.append(len(toParse)) return",
"== \" \": toReturn.append(current) toReturn.append(len(toParse)) return toReturn def manageFile(inputPath,outputPath,topicIndex,currentLevel,filename): count",
"+ ThirdLevel): if(len(siteLevel[selectedTopic]) == 4): selectedLevel = 4 else: selectedLevel",
"selectedLevel = random.randint(4,len(siteLevel[selectedTopic])) i = 0 found = False while",
"in os.listdir(inputDirectory) : if(foldername[0] != \".\"): topics.append(foldername) siteLevel.append([]) fileStructure.append([]) levelIndex=0",
"for categoryName in os.listdir(inputDirectory+\"/\"+foldername): if(categoryName[0] != \".\"): siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([]) for",
"#probability parameters TopLevel = 0.6 SecondLevel = 0.5 ThirdLevel =",
"SecondLevel = 0.5 ThirdLevel = 0.4 FourAndAbove = 0.2 pickInside",
"random.uniform(0.0,2.0) if randomPick <= pickInside+pickOutside : possibleIndexes = findPossibleIndex(currentLine) insertPosition",
"= possibleIndexes[random.randint(0,len(possibleIndexes)-1)] selectedTopic = topicIndex if(randomPick<=pickOutside): while(selectedTopic == topicIndex): selectedTopic",
"+ SecondLevel + ThirdLevel + FourAndAbove): selectedLevel = 0 if(randomPick",
"possibleIndexes[random.randint(0,len(possibleIndexes)-1)] selectedTopic = topicIndex if(randomPick<=pickOutside): while(selectedTopic == topicIndex): selectedTopic =",
"fileStructure = [] count = 0 def findPossibleIndex(toParse): toReturn =",
"SecondLevel + ThirdLevel and randomPick > TopLevel+ SecondLevel): selectedLevel =",
"TopLevel + SecondLevel + ThirdLevel + FourAndAbove): selectedLevel = 0",
"[] siteLevel = [] fileStructure = [] count = 0",
"0.6 SecondLevel = 0.5 ThirdLevel = 0.4 FourAndAbove = 0.2",
"random.randint(4,len(siteLevel[selectedTopic])) i = 0 found = False while i<len(siteLevel[selectedTopic]): if",
"currentLine = content.readline() outputFile = \"\" while currentLine: currentLine =",
"currentLine output.write(outputFile) return count topicIndex=0 for foldername in os.listdir(inputDirectory) :",
"+ FourAndAbove): selectedLevel = 0 if(randomPick <= TopLevel): selectedLevel =",
"= 0 found = False while i<len(siteLevel[selectedTopic]): if siteLevel[selectedTopic][i] ==",
"if(randomPick <= TopLevel + SecondLevel + ThirdLevel + FourAndAbove): selectedLevel",
"randomPick > TopLevel + SecondLevel + ThirdLevel): if(len(siteLevel[selectedTopic]) == 4):",
"toReturn def manageFile(inputPath,outputPath,topicIndex,currentLevel,filename): count = 0 content = open(inputPath ,",
"def findPossibleIndex(toParse): toReturn = [] for current in range(0,len(toParse)): if",
"<= TopLevel + SecondLevel + ThirdLevel + FourAndAbove): selectedLevel =",
"findPossibleIndex(toParse): toReturn = [] for current in range(0,len(toParse)): if toParse[current]",
"0.5 ThirdLevel = 0.4 FourAndAbove = 0.2 pickInside = 0.5",
"False while i<len(siteLevel[selectedTopic]): if siteLevel[selectedTopic][i] == str(selectedLevel)+\"grade\": found = True",
"<= TopLevel+ SecondLevel and randomPick > TopLevel): selectedLevel = 2",
"selectedTopic = random.randint(0,len(topics)-1) randomPick = random.uniform(0.0,4.0) if(randomPick <= TopLevel +",
"= 0 if(randomPick <= TopLevel): selectedLevel = 1 if(randomPick <=",
"if(selectedLevel>=currentLevel): fileLink = filename while(fileLink == filename): fileLink = fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)]",
"currentLine = currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:] outputFile += currentLine output.write(outputFile) return count topicIndex=0",
"outputFile += currentLine output.write(outputFile) return count topicIndex=0 for foldername in",
"else: currentLine = currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:] outputFile += currentLine output.write(outputFile) return count",
"\" \": toReturn.append(current) toReturn.append(len(toParse)) return toReturn def manageFile(inputPath,outputPath,topicIndex,currentLevel,filename): count =",
"in os.listdir(inputDirectory+\"/\"+foldername): if(categoryName[0] != \".\"): siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([]) for filename in",
"os.listdir(inputDirectory+\"/\"+foldername): if(categoryName[0] != \".\"): siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([]) for filename in os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName):",
"TopLevel + SecondLevel + ThirdLevel and randomPick > TopLevel+ SecondLevel):",
"= \"./processed\" #probability parameters TopLevel = 0.6 SecondLevel = 0.5",
"range(0,len(toParse)): if toParse[current] == \" \": toReturn.append(current) toReturn.append(len(toParse)) return toReturn",
"current in range(0,len(toParse)): if toParse[current] == \" \": toReturn.append(current) toReturn.append(len(toParse))",
"1 if(randomPick <= TopLevel+ SecondLevel and randomPick > TopLevel): selectedLevel",
"selectedLevel = 3 if(randomPick <= TopLevel + SecondLevel + ThirdLevel",
"0 found = False while i<len(siteLevel[selectedTopic]): if siteLevel[selectedTopic][i] == str(selectedLevel)+\"grade\":",
"[] for current in range(0,len(toParse)): if toParse[current] == \" \":",
"if toParse[current] == \" \": toReturn.append(current) toReturn.append(len(toParse)) return toReturn def",
"content.readline() randomPick = random.uniform(0.0,2.0) if randomPick <= pickInside+pickOutside : possibleIndexes",
"found = False while i<len(siteLevel[selectedTopic]): if siteLevel[selectedTopic][i] == str(selectedLevel)+\"grade\": found",
"levelIndex=0 for categoryName in os.listdir(inputDirectory+\"/\"+foldername): if(categoryName[0] != \".\"): siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([])",
"fileStructure[topicIndex][levelIndex].append(filename) levelIndex += 1 topicIndex += 1 for i in",
"= 0 content = open(inputPath , 'r') output = open(outputPath",
"toReturn = [] for current in range(0,len(toParse)): if toParse[current] ==",
"FourAndAbove = 0.2 pickInside = 0.5 pickOutside = 0.25 topics",
"open(inputPath , 'r') output = open(outputPath ,\"w\") currentLine = content.readline()",
"ThirdLevel = 0.4 FourAndAbove = 0.2 pickInside = 0.5 pickOutside",
"siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([]) for filename in os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName): if(filename[0] != \".\"): fileStructure[topicIndex][levelIndex].append(filename)",
"1 topicIndex += 1 for i in range(0,len(topics)): for j",
"toParse[current] == \" \": toReturn.append(current) toReturn.append(len(toParse)) return toReturn def manageFile(inputPath,outputPath,topicIndex,currentLevel,filename):",
"+ SecondLevel + ThirdLevel and randomPick > TopLevel+ SecondLevel): selectedLevel",
"filename): fileLink = fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)] fileLink = \" linkTo:\"+fileLink count +=",
"1 for i in range(0,len(topics)): for j in range(0,len(siteLevel[i])): for",
"j in range(0,len(siteLevel[i])): for k in range(0,len(fileStructure[i][j])): count += manageFile(inputDirectory+\"/\"+topics[i]+\"/\"+siteLevel[i][j]+\"/\"+fileStructure[i][j][k],outputDirectory+\"/\"+fileStructure[i][j][k],i,j,fileStructure[i][j][k])",
"[] fileStructure = [] count = 0 def findPossibleIndex(toParse): toReturn",
"import random inputDirectory = \"./original\" outputDirectory = \"./processed\" #probability parameters",
"FourAndAbove): selectedLevel = 0 if(randomPick <= TopLevel): selectedLevel = 1",
"= 3 if(randomPick <= TopLevel + SecondLevel + ThirdLevel +",
"+= 1 print(count) if insertPosition == len(currentLine): currentLine += fileLink",
"<= TopLevel + SecondLevel + ThirdLevel + FourAndAbove and randomPick",
"TopLevel+ SecondLevel and randomPick > TopLevel): selectedLevel = 2 if(randomPick",
"SecondLevel + ThirdLevel + FourAndAbove): selectedLevel = 0 if(randomPick <=",
"filename in os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName): if(filename[0] != \".\"): fileStructure[topicIndex][levelIndex].append(filename) levelIndex += 1",
"if(randomPick <= TopLevel+ SecondLevel and randomPick > TopLevel): selectedLevel =",
"filename while(fileLink == filename): fileLink = fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)] fileLink = \"",
"randomPick <= pickInside+pickOutside : possibleIndexes = findPossibleIndex(currentLine) insertPosition = possibleIndexes[random.randint(0,len(possibleIndexes)-1)]",
"randomPick > TopLevel+ SecondLevel): selectedLevel = 3 if(randomPick <= TopLevel",
"+ ThirdLevel + FourAndAbove): selectedLevel = 0 if(randomPick <= TopLevel):",
"3 if(randomPick <= TopLevel + SecondLevel + ThirdLevel + FourAndAbove",
"0.25 topics = [] siteLevel = [] fileStructure = []",
"<= TopLevel + SecondLevel + ThirdLevel and randomPick > TopLevel+",
"\" linkTo:\"+fileLink count += 1 print(count) if insertPosition == len(currentLine):",
"TopLevel+ SecondLevel): selectedLevel = 3 if(randomPick <= TopLevel + SecondLevel",
"[] count = 0 def findPossibleIndex(toParse): toReturn = [] for",
"found = True selectedLevel = i i+=1 if(selectedLevel>=currentLevel): fileLink =",
"while i<len(siteLevel[selectedTopic]): if siteLevel[selectedTopic][i] == str(selectedLevel)+\"grade\": found = True selectedLevel",
"parameters TopLevel = 0.6 SecondLevel = 0.5 ThirdLevel = 0.4",
"= \" linkTo:\"+fileLink count += 1 print(count) if insertPosition ==",
"!= \".\"): topics.append(foldername) siteLevel.append([]) fileStructure.append([]) levelIndex=0 for categoryName in os.listdir(inputDirectory+\"/\"+foldername):",
"True selectedLevel = i i+=1 if(selectedLevel>=currentLevel): fileLink = filename while(fileLink",
"if randomPick <= pickInside+pickOutside : possibleIndexes = findPossibleIndex(currentLine) insertPosition =",
"open(outputPath ,\"w\") currentLine = content.readline() outputFile = \"\" while currentLine:",
"else: selectedLevel = random.randint(4,len(siteLevel[selectedTopic])) i = 0 found = False",
"outputFile = \"\" while currentLine: currentLine = content.readline() randomPick =",
"str(selectedLevel)+\"grade\": found = True selectedLevel = i i+=1 if(selectedLevel>=currentLevel): fileLink",
"+= currentLine output.write(outputFile) return count topicIndex=0 for foldername in os.listdir(inputDirectory)",
"<= TopLevel): selectedLevel = 1 if(randomPick <= TopLevel+ SecondLevel and",
"os import random inputDirectory = \"./original\" outputDirectory = \"./processed\" #probability",
"insertPosition = possibleIndexes[random.randint(0,len(possibleIndexes)-1)] selectedTopic = topicIndex if(randomPick<=pickOutside): while(selectedTopic == topicIndex):",
"if(randomPick <= TopLevel): selectedLevel = 1 if(randomPick <= TopLevel+ SecondLevel",
"foldername in os.listdir(inputDirectory) : if(foldername[0] != \".\"): topics.append(foldername) siteLevel.append([]) fileStructure.append([])",
"!= \".\"): fileStructure[topicIndex][levelIndex].append(filename) levelIndex += 1 topicIndex += 1 for",
"currentLine += fileLink else: currentLine = currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:] outputFile += currentLine",
"and randomPick > TopLevel+ SecondLevel): selectedLevel = 3 if(randomPick <=",
"random inputDirectory = \"./original\" outputDirectory = \"./processed\" #probability parameters TopLevel",
"= i i+=1 if(selectedLevel>=currentLevel): fileLink = filename while(fileLink == filename):",
"+= fileLink else: currentLine = currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:] outputFile += currentLine output.write(outputFile)",
"fileLink = filename while(fileLink == filename): fileLink = fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)] fileLink",
"= 4 else: selectedLevel = random.randint(4,len(siteLevel[selectedTopic])) i = 0 found",
"+= 1 topicIndex += 1 for i in range(0,len(topics)): for",
"= random.randint(4,len(siteLevel[selectedTopic])) i = 0 found = False while i<len(siteLevel[selectedTopic]):",
"i in range(0,len(topics)): for j in range(0,len(siteLevel[i])): for k in",
"<= pickInside+pickOutside : possibleIndexes = findPossibleIndex(currentLine) insertPosition = possibleIndexes[random.randint(0,len(possibleIndexes)-1)] selectedTopic",
"in range(0,len(topics)): for j in range(0,len(siteLevel[i])): for k in range(0,len(fileStructure[i][j])):",
"count = 0 content = open(inputPath , 'r') output =",
"+ ThirdLevel and randomPick > TopLevel+ SecondLevel): selectedLevel = 3",
"for i in range(0,len(topics)): for j in range(0,len(siteLevel[i])): for k",
"for current in range(0,len(toParse)): if toParse[current] == \" \": toReturn.append(current)",
"\".\"): topics.append(foldername) siteLevel.append([]) fileStructure.append([]) levelIndex=0 for categoryName in os.listdir(inputDirectory+\"/\"+foldername): if(categoryName[0]",
"fileLink = fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)] fileLink = \" linkTo:\"+fileLink count += 1",
"toReturn.append(current) toReturn.append(len(toParse)) return toReturn def manageFile(inputPath,outputPath,topicIndex,currentLevel,filename): count = 0 content",
"1 print(count) if insertPosition == len(currentLine): currentLine += fileLink else:",
"0.2 pickInside = 0.5 pickOutside = 0.25 topics = []",
"for j in range(0,len(siteLevel[i])): for k in range(0,len(fileStructure[i][j])): count +=",
"pickInside+pickOutside : possibleIndexes = findPossibleIndex(currentLine) insertPosition = possibleIndexes[random.randint(0,len(possibleIndexes)-1)] selectedTopic =",
"= open(inputPath , 'r') output = open(outputPath ,\"w\") currentLine =",
"selectedLevel = 2 if(randomPick <= TopLevel + SecondLevel + ThirdLevel",
"in range(0,len(siteLevel[i])): for k in range(0,len(fileStructure[i][j])): count += manageFile(inputDirectory+\"/\"+topics[i]+\"/\"+siteLevel[i][j]+\"/\"+fileStructure[i][j][k],outputDirectory+\"/\"+fileStructure[i][j][k],i,j,fileStructure[i][j][k]) print(str(count)+\"",
"findPossibleIndex(currentLine) insertPosition = possibleIndexes[random.randint(0,len(possibleIndexes)-1)] selectedTopic = topicIndex if(randomPick<=pickOutside): while(selectedTopic ==",
"content = open(inputPath , 'r') output = open(outputPath ,\"w\") currentLine",
"selectedLevel = 1 if(randomPick <= TopLevel+ SecondLevel and randomPick >",
"+= 1 for i in range(0,len(topics)): for j in range(0,len(siteLevel[i])):",
"for filename in os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName): if(filename[0] != \".\"): fileStructure[topicIndex][levelIndex].append(filename) levelIndex +=",
"selectedLevel = i i+=1 if(selectedLevel>=currentLevel): fileLink = filename while(fileLink ==",
"TopLevel): selectedLevel = 1 if(randomPick <= TopLevel+ SecondLevel and randomPick",
"> TopLevel + SecondLevel + ThirdLevel): if(len(siteLevel[selectedTopic]) == 4): selectedLevel",
"= True selectedLevel = i i+=1 if(selectedLevel>=currentLevel): fileLink = filename",
"0.5 pickOutside = 0.25 topics = [] siteLevel = []",
"TopLevel + SecondLevel + ThirdLevel + FourAndAbove and randomPick >",
"if(randomPick <= TopLevel + SecondLevel + ThirdLevel and randomPick >",
"= False while i<len(siteLevel[selectedTopic]): if siteLevel[selectedTopic][i] == str(selectedLevel)+\"grade\": found =",
"categoryName in os.listdir(inputDirectory+\"/\"+foldername): if(categoryName[0] != \".\"): siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([]) for filename",
"range(0,len(siteLevel[i])): for k in range(0,len(fileStructure[i][j])): count += manageFile(inputDirectory+\"/\"+topics[i]+\"/\"+siteLevel[i][j]+\"/\"+fileStructure[i][j][k],outputDirectory+\"/\"+fileStructure[i][j][k],i,j,fileStructure[i][j][k]) print(str(count)+\" liens",
"while(selectedTopic == topicIndex): selectedTopic = random.randint(0,len(topics)-1) randomPick = random.uniform(0.0,4.0) if(randomPick",
"= 0 def findPossibleIndex(toParse): toReturn = [] for current in",
"topicIndex if(randomPick<=pickOutside): while(selectedTopic == topicIndex): selectedTopic = random.randint(0,len(topics)-1) randomPick =",
"import os import random inputDirectory = \"./original\" outputDirectory = \"./processed\"",
"+ FourAndAbove and randomPick > TopLevel + SecondLevel + ThirdLevel):",
"output.write(outputFile) return count topicIndex=0 for foldername in os.listdir(inputDirectory) : if(foldername[0]",
"TopLevel + SecondLevel + ThirdLevel): if(len(siteLevel[selectedTopic]) == 4): selectedLevel =",
"count += 1 print(count) if insertPosition == len(currentLine): currentLine +=",
"count = 0 def findPossibleIndex(toParse): toReturn = [] for current",
"os.listdir(inputDirectory) : if(foldername[0] != \".\"): topics.append(foldername) siteLevel.append([]) fileStructure.append([]) levelIndex=0 for",
"0 def findPossibleIndex(toParse): toReturn = [] for current in range(0,len(toParse)):",
"possibleIndexes = findPossibleIndex(currentLine) insertPosition = possibleIndexes[random.randint(0,len(possibleIndexes)-1)] selectedTopic = topicIndex if(randomPick<=pickOutside):",
"selectedLevel = 4 else: selectedLevel = random.randint(4,len(siteLevel[selectedTopic])) i = 0",
"ThirdLevel and randomPick > TopLevel+ SecondLevel): selectedLevel = 3 if(randomPick",
"'r') output = open(outputPath ,\"w\") currentLine = content.readline() outputFile =",
"= 0.5 pickOutside = 0.25 topics = [] siteLevel =",
"random.randint(0,len(topics)-1) randomPick = random.uniform(0.0,4.0) if(randomPick <= TopLevel + SecondLevel +",
"randomPick > TopLevel): selectedLevel = 2 if(randomPick <= TopLevel +",
"== filename): fileLink = fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)] fileLink = \" linkTo:\"+fileLink count",
"= random.uniform(0.0,4.0) if(randomPick <= TopLevel + SecondLevel + ThirdLevel +",
"= currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:] outputFile += currentLine output.write(outputFile) return count topicIndex=0 for",
"i = 0 found = False while i<len(siteLevel[selectedTopic]): if siteLevel[selectedTopic][i]",
"= \"\" while currentLine: currentLine = content.readline() randomPick = random.uniform(0.0,2.0)",
"<filename>Projet1/Dataset/addlinkRealExample.py import os import random inputDirectory = \"./original\" outputDirectory =",
"ThirdLevel + FourAndAbove and randomPick > TopLevel + SecondLevel +",
"len(currentLine): currentLine += fileLink else: currentLine = currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:] outputFile +=",
"if(foldername[0] != \".\"): topics.append(foldername) siteLevel.append([]) fileStructure.append([]) levelIndex=0 for categoryName in",
"if(len(siteLevel[selectedTopic]) == 4): selectedLevel = 4 else: selectedLevel = random.randint(4,len(siteLevel[selectedTopic]))",
"= [] siteLevel = [] fileStructure = [] count =",
"= topicIndex if(randomPick<=pickOutside): while(selectedTopic == topicIndex): selectedTopic = random.randint(0,len(topics)-1) randomPick",
"0 content = open(inputPath , 'r') output = open(outputPath ,\"w\")",
"topics.append(foldername) siteLevel.append([]) fileStructure.append([]) levelIndex=0 for categoryName in os.listdir(inputDirectory+\"/\"+foldername): if(categoryName[0] !=",
"= fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)] fileLink = \" linkTo:\"+fileLink count += 1 print(count)",
"if(categoryName[0] != \".\"): siteLevel[topicIndex].append(categoryName) fileStructure[topicIndex].append([]) for filename in os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName): if(filename[0]",
"selectedTopic = topicIndex if(randomPick<=pickOutside): while(selectedTopic == topicIndex): selectedTopic = random.randint(0,len(topics)-1)",
"manageFile(inputPath,outputPath,topicIndex,currentLevel,filename): count = 0 content = open(inputPath , 'r') output",
"return count topicIndex=0 for foldername in os.listdir(inputDirectory) : if(foldername[0] !=",
"in os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName): if(filename[0] != \".\"): fileStructure[topicIndex][levelIndex].append(filename) levelIndex += 1 topicIndex",
"if siteLevel[selectedTopic][i] == str(selectedLevel)+\"grade\": found = True selectedLevel = i",
"= content.readline() outputFile = \"\" while currentLine: currentLine = content.readline()",
"pickOutside = 0.25 topics = [] siteLevel = [] fileStructure",
"2 if(randomPick <= TopLevel + SecondLevel + ThirdLevel and randomPick",
", 'r') output = open(outputPath ,\"w\") currentLine = content.readline() outputFile",
"if insertPosition == len(currentLine): currentLine += fileLink else: currentLine =",
"\": toReturn.append(current) toReturn.append(len(toParse)) return toReturn def manageFile(inputPath,outputPath,topicIndex,currentLevel,filename): count = 0",
"TopLevel = 0.6 SecondLevel = 0.5 ThirdLevel = 0.4 FourAndAbove",
"0 if(randomPick <= TopLevel): selectedLevel = 1 if(randomPick <= TopLevel+",
"if(randomPick<=pickOutside): while(selectedTopic == topicIndex): selectedTopic = random.randint(0,len(topics)-1) randomPick = random.uniform(0.0,4.0)",
"randomPick = random.uniform(0.0,4.0) if(randomPick <= TopLevel + SecondLevel + ThirdLevel",
": possibleIndexes = findPossibleIndex(currentLine) insertPosition = possibleIndexes[random.randint(0,len(possibleIndexes)-1)] selectedTopic = topicIndex",
"currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:] outputFile += currentLine output.write(outputFile) return count topicIndex=0 for foldername",
"= [] count = 0 def findPossibleIndex(toParse): toReturn = []",
"output = open(outputPath ,\"w\") currentLine = content.readline() outputFile = \"\"",
"pickInside = 0.5 pickOutside = 0.25 topics = [] siteLevel",
"== topicIndex): selectedTopic = random.randint(0,len(topics)-1) randomPick = random.uniform(0.0,4.0) if(randomPick <=",
"topicIndex=0 for foldername in os.listdir(inputDirectory) : if(foldername[0] != \".\"): topics.append(foldername)",
"topicIndex += 1 for i in range(0,len(topics)): for j in",
"+ ThirdLevel + FourAndAbove and randomPick > TopLevel + SecondLevel",
"toReturn.append(len(toParse)) return toReturn def manageFile(inputPath,outputPath,topicIndex,currentLevel,filename): count = 0 content =",
"= \"./original\" outputDirectory = \"./processed\" #probability parameters TopLevel = 0.6",
"0.4 FourAndAbove = 0.2 pickInside = 0.5 pickOutside = 0.25",
"== 4): selectedLevel = 4 else: selectedLevel = random.randint(4,len(siteLevel[selectedTopic])) i",
"4): selectedLevel = 4 else: selectedLevel = random.randint(4,len(siteLevel[selectedTopic])) i =",
"range(0,len(topics)): for j in range(0,len(siteLevel[i])): for k in range(0,len(fileStructure[i][j])): count",
"and randomPick > TopLevel + SecondLevel + ThirdLevel): if(len(siteLevel[selectedTopic]) ==",
"linkTo:\"+fileLink count += 1 print(count) if insertPosition == len(currentLine): currentLine",
"topics = [] siteLevel = [] fileStructure = [] count",
"\"./processed\" #probability parameters TopLevel = 0.6 SecondLevel = 0.5 ThirdLevel",
"randomPick = random.uniform(0.0,2.0) if randomPick <= pickInside+pickOutside : possibleIndexes =",
"TopLevel): selectedLevel = 2 if(randomPick <= TopLevel + SecondLevel +",
"= 2 if(randomPick <= TopLevel + SecondLevel + ThirdLevel and",
"fileStructure.append([]) levelIndex=0 for categoryName in os.listdir(inputDirectory+\"/\"+foldername): if(categoryName[0] != \".\"): siteLevel[topicIndex].append(categoryName)",
"SecondLevel): selectedLevel = 3 if(randomPick <= TopLevel + SecondLevel +",
"== str(selectedLevel)+\"grade\": found = True selectedLevel = i i+=1 if(selectedLevel>=currentLevel):",
"> TopLevel+ SecondLevel): selectedLevel = 3 if(randomPick <= TopLevel +",
"i i+=1 if(selectedLevel>=currentLevel): fileLink = filename while(fileLink == filename): fileLink",
"while(fileLink == filename): fileLink = fileStructure[selectedTopic][selectedLevel][random.randint(0,len(fileStructure[selectedTopic][selectedLevel])-1)] fileLink = \" linkTo:\"+fileLink",
"while currentLine: currentLine = content.readline() randomPick = random.uniform(0.0,2.0) if randomPick",
"ThirdLevel + FourAndAbove): selectedLevel = 0 if(randomPick <= TopLevel): selectedLevel",
"4 else: selectedLevel = random.randint(4,len(siteLevel[selectedTopic])) i = 0 found =",
"\".\"): fileStructure[topicIndex][levelIndex].append(filename) levelIndex += 1 topicIndex += 1 for i",
"= open(outputPath ,\"w\") currentLine = content.readline() outputFile = \"\" while",
"if(randomPick <= TopLevel + SecondLevel + ThirdLevel + FourAndAbove and",
"inputDirectory = \"./original\" outputDirectory = \"./processed\" #probability parameters TopLevel =",
"def manageFile(inputPath,outputPath,topicIndex,currentLevel,filename): count = 0 content = open(inputPath , 'r')",
"= 0.2 pickInside = 0.5 pickOutside = 0.25 topics =",
"currentLine = content.readline() randomPick = random.uniform(0.0,2.0) if randomPick <= pickInside+pickOutside",
"siteLevel[selectedTopic][i] == str(selectedLevel)+\"grade\": found = True selectedLevel = i i+=1",
": if(foldername[0] != \".\"): topics.append(foldername) siteLevel.append([]) fileStructure.append([]) levelIndex=0 for categoryName",
"fileStructure[topicIndex].append([]) for filename in os.listdir(inputDirectory+\"/\"+foldername+\"/\"+categoryName): if(filename[0] != \".\"): fileStructure[topicIndex][levelIndex].append(filename) levelIndex",
",\"w\") currentLine = content.readline() outputFile = \"\" while currentLine: currentLine",
"fileLink = \" linkTo:\"+fileLink count += 1 print(count) if insertPosition",
"return toReturn def manageFile(inputPath,outputPath,topicIndex,currentLevel,filename): count = 0 content = open(inputPath",
"levelIndex += 1 topicIndex += 1 for i in range(0,len(topics)):",
"SecondLevel and randomPick > TopLevel): selectedLevel = 2 if(randomPick <=",
"insertPosition == len(currentLine): currentLine += fileLink else: currentLine = currentLine[0:insertPosition]+fileLink+currentLine[insertPosition:]",
"topicIndex): selectedTopic = random.randint(0,len(topics)-1) randomPick = random.uniform(0.0,4.0) if(randomPick <= TopLevel"
] |
[
"x^k terms for ni in numpy.where(orders>=0)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n",
"numpy array with columns consisting of the photon energy, the",
"to -3) piecewise-polynomial algorithm\") X1 = Energy[0:-1] X2 = Energy[1:]",
"Full_E temp_Im_spectrum = Imaginary_Spectrum[1:] count = 0 improved = 1",
"Im_error = abs((Im_values[new_points-1]+Im_values[new_points])/2. - Im_midpoints) Re_error = abs((Re_values[new_points-1]+Re_values[new_points])/2. - Re_midpoints)",
":]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3 = (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2, :]+Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E))))",
"be improved in pass number \"+str(count+1)+\".\") total_improved_points += numpy.sum(improved) #insert",
"Eval_Energy : numpy vector of `float` Set of photon energies",
"A_-2, A_-3 relativistic_correction : float The relativistic correction to the",
"add_background=False, fix_distortions=False, curve_tolerance=None, curve_recursion=50): \"\"\"Do all data loading and processing",
"that element. Returns ------- This function returns a ``float`` holding",
":]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2, :]-Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3 =",
"= numpy.any(hits, axis=1) X1 = Energy[E_hits[2:]] XE = Energy[E_hits[1:-1]] X2",
"Parameters ---------- Eval_Energy : numpy vector of `float` Set of",
"energy, the real and the imaginary parts of the scattering",
"data set. Returns ------- This function returns a numpy array",
"numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles = numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) # all N, ln(x+E) and ln(x-E)",
"Im, Relativistic_Correction) import matplotlib matplotlib.use('WXAgg') import pylab pylab.figure() pylab.plot(Output[:,0],Output[:,1],'xg-',Output[:,0],Output[:,2],'xb-') pylab.plot(ASF_E,ASF_Data2,'+r')",
"Integral = numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if numpy.any(orders<=-2): # N<=-2, ln(x) terms i",
":]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2, :]-Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3",
"[slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in range(n,0,-2): Integral +=",
"A_-1, A_-2, A_-3 relativistic_correction : float The relativistic correction to",
"the power terms indicated by 'order' orders : numpy vector",
"`numpy.array` of `float` The array consists of five columns of",
"= numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare for next loop temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points =",
"X1 = Energy[E_hits[2:]] XE = Energy[E_hits[1:-1]] X2 = Energy[E_hits[:-2]] C1",
"argparse here to get command line arguments #process arguments and",
"intervals for which each row of `imaginary_spectrum` is valid Real_Spectrum",
"transform using (n from 1 to -3) piecewise-polynomial algorithm\") X1",
"calculate the value using the `calc_relativistic_correction` function.) tolerance : float",
"error in linear extrapolation of data values to be allowed.",
"in numpy.where(orders<=-3)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k",
"relativistic_correction : float The relativistic correction to the Kramers-Kronig transform.",
"Returns ------- This function returns a numpy array with three",
"math.pi + relativistic_correction def KK_PP(Eval_Energy, Energy, imaginary_spectrum, relativistic_correction): \"\"\"Calculate Kramers-Kronig",
":]+Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B = numpy.sum(Symb_2 - Symb_1 - Symb_3,",
"0 improved = 1 total_improved_points = 0 while count<recursion and",
"#pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log') #pylab.show() logger.info(\"Improved data accuracy by inserting \"+str(total_improved_points)+\"",
"Relativistic_Correction = calc_relativistic_correction(Stoichiometry) ASF_E, ASF_Data = data.calculate_asf(Stoichiometry) ASF_Data3 = data.coeffs_to_linear(ASF_E,",
"Full_E, Imaginary_Spectrum = data.merge_spectra(NearEdge_Data, Full_E, Imaginary_Spectrum, merge_points=merge_points, add_background=add_background, fix_distortions=fix_distortions) Real_Spectrum",
"kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) #Output = kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs', input_data_type='NEXAFS',",
"chemical formula string consisting of element symbols, numbers and parentheses.",
"this section of code for initial testing #Output = kk_calculate_real('../../data/Xy_norm_bgsub.txt',",
"numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) # all N, ln(x+E) and ln(x-E) terms and poles",
"the photon energy, the real and the imaginary parts of",
"the scattering factors. \"\"\" Stoichiometry = data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction = calc_relativistic_correction(Stoichiometry)",
"indicated by 'order' orders : numpy vector of integers The",
"corresponding to the columns of imaginary_spectrum relativistic_correction : float The",
"ni in numpy.where(orders<=-3)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for",
"=numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points = numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0] new_points = numpy.vstack((new_points, new_points+1)).T.flatten() count",
"z, n in stoichiometry: correction += (z - (z/82.5)**2.37) *",
"numpy vector of `float` Set of photon energies describing points",
"# all N, ln(x+E) and ln(x-E) terms and poles Integral",
"= calc_relativistic_correction(Stoichiometry) ASF_E, ASF_Data = data.calculate_asf(Stoichiometry) ASF_Data3 = data.coeffs_to_linear(ASF_E, ASF_Data,",
"of the scattering factors evaluated at photon energies specified by",
"ASF_Data = data.calculate_asf(Stoichiometry) ASF_Data3 = data.coeffs_to_linear(ASF_E, ASF_Data, 0.1) ASF_Data2 =",
"of photon energies describing points at which to evaluate the",
"E = numpy.tile(Eval_Energy, (len(Energy)-1, 1)).T Full_coeffs = imaginary_spectrum.T Symb_1 =",
"- Symb_1 - Symb_3, axis=1) # Sum areas for approximate",
"def KK_PP(Eval_Energy, Energy, imaginary_spectrum, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with \"Piecewise",
"halved before giving up. Returns ------- This function returns a",
"= data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values = Im_values Re_values = Real_Spectrum E_values",
"in pass number \"+str(count+1)+\".\") total_improved_points += numpy.sum(improved) #insert new points",
"the near-edge and scattering factor data values are set equal",
"of `float` The real part of the spectrum corresponding to",
"`calc_relativistic_correction` function.) tolerance : float Level of error in linear",
"= calc_relativistic_correction(Stoichiometry) Full_E, Imaginary_Spectrum = data.calculate_asf(Stoichiometry) if NearEdgeDataFile is not",
"= data.merge_spectra(NearEdge_Data, Full_E, Imaginary_Spectrum, merge_points=merge_points, add_background=add_background, fix_distortions=fix_distortions) Real_Spectrum = KK_PP(Full_E,",
"data def calc_relativistic_correction(stoichiometry): \"\"\"Calculate the relativistic correction to the Kramers-Kronig",
"of the spectrum corresponding to magnitudes at photon energies in",
"curve_tolerance=0.05) Stoichiometry = data.ParseChemicalFormula('LaAlO3') #Stoichiometry = data.ParseChemicalFormula('GaAs') Relativistic_Correction = calc_relativistic_correction(Stoichiometry)",
"= (Output[1:,0]+Output[0:-1,0])*0.5 #Test_E = numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2 = KK_PP(Test_E, Output[:,0], Im,",
":]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1)) Symb_2 = ((-Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3,",
"orders : numpy vector of integers The vector represents the",
"import numpy import os import data def calc_relativistic_correction(stoichiometry): \"\"\"Calculate the",
"A_1, A_0, A_-1, A_-2, A_-3 relativistic_correction : float The relativistic",
"the imaginary spectrum. \"\"\" logger.debug(\"Improve data accuracy\") new_points = numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1",
"relativistic_correction def KK_PP(Eval_Energy, Energy, imaginary_spectrum, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with",
"This file is part of the Kramers-Kronig Calculator software package.",
"if numpy.any(orders>=0): # N>=0, x^k terms for ni in numpy.where(orders>=0)[0]:",
"X2 = Energy[E_hits[:-2]] C1 = Full_coeffs[:, E_hits[2:-1]] C2 = Full_coeffs[:,",
"#pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log') #pylab.show() logger.info(\"Improved data accuracy",
"This function returns a numpy array with columns consisting of",
"#I will abuse this section of code for initial testing",
"| (Re_error>tolerance) logger.debug(str(numpy.sum(improved))+\" points (out of \"+str(len(improved))+\") can be improved",
"# For details see LICENSE.txt \"\"\"This module implements the Kramers-Kronig",
"logger = logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout) import",
"build x-E-n arrays X = numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E = numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C",
"list or tuple pair of `float` values, or None The",
"each row of `imaginary_spectrum` is valid Real_Spectrum : numpy vector",
"(low, high) at which the near-edge and scattering factor data",
"consists of an atomic number and the relative proportion of",
"standard chemical formula string consisting of element symbols, numbers and",
"value using the `calc_relativistic_correction` function. Returns ------- This function returns",
"points so that a linear interpolation is more accurate. Parameters",
"at which the near-edge and scattering factor data values are",
"import data def calc_relativistic_correction(stoichiometry): \"\"\"Calculate the relativistic correction to the",
"Path to file containg near-edge data ChemicalFormula : string A",
"temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points = numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0] new_points = numpy.vstack((new_points, new_points+1)).T.flatten()",
"transform with \"Piecewise Polynomial\" algorithm plus the Biggs and Lighthill",
"for ni in numpy.where(orders<=-3)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni]",
"\"+str(count+1)+\".\") total_improved_points += numpy.sum(improved) #insert new points and values Im_values",
"curve_tolerance, curve_recursion) else: Imaginary_Spectrum_Values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data = numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T",
"Set of photon energies describing intervals for which each row",
"terms for ni in numpy.where(orders>=0)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n =",
"terms and poles Integral = numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if numpy.any(orders<=-2): # N<=-2,",
"number and the relative proportion of that element. Returns -------",
"power terms indicated by 'order' orders : numpy vector of",
"of `float` The array consists of five columns of polynomial",
"A_-3 relativistic_correction : float The relativistic correction to the Kramers-Kronig",
"= 0 while count<recursion and numpy.sum(improved)>0: #get E_midpoints midpoints =",
"data.calculate_asf(Stoichiometry) if NearEdgeDataFile is not None: NearEdge_Data = data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf')",
"Lighthill extended data. Parameters ---------- Eval_Energy : numpy vector of",
"if curve_tolerance is not None: output_data = improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction, curve_tolerance,",
": array of integer/float pairs Each pair in the list",
"up. Returns ------- This function returns a numpy array with",
"numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values = numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values = numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare for next",
"= [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in range(n,0,-2): Integral",
"energies specified by Eval_Energy. \"\"\" logger = logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig",
"#pylab.xscale('log') #pylab.show() logger.info(\"Improved data accuracy by inserting \"+str(total_improved_points)+\" extra points.\")",
"is valid imaginary_spectrum : two-dimensional `numpy.array` of `float` The array",
"This function returns a ``float`` holding the relativistic corection to",
"the list consists of an atomic number and the relative",
"and ln(x-E) terms and poles Integral = numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if numpy.any(orders<=-2):",
"Real_Spectrum : numpy vector of `float` The real part of",
"arguments #process arguments and pass to a pythonic function #I",
"relativistic correction to the Kramers-Kronig transform. (You can calculate the",
"numbers and parentheses. merge_points : list or tuple pair of",
"giving up. Returns ------- This function returns a numpy array",
"(z/82.5)**2.37) * n return correction def KK_General_PP(Eval_Energy, Energy, imaginary_spectrum, orders,",
"= abs((Im_values[new_points-1]+Im_values[new_points])/2. - Im_midpoints) Re_error = abs((Re_values[new_points-1]+Re_values[new_points])/2. - Re_midpoints) improved",
":]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) # Finish things off KK_Re = (Symb_B-Symb_singularities) / (math.pi*Eval_Energy)",
"the real spectrum and the imaginary spectrum. \"\"\" logger.debug(\"Improve data",
"element. Returns ------- This function returns a ``float`` holding the",
"Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1)) Symb_2 = ((-Full_coeffs[0,",
"= [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in range(n+2,0,2): Integral",
"terms i = [slice(None,None,None),slice(None,None,None),orders<=-2] Integral += numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if numpy.any(orders>=0): #",
"n in stoichiometry: correction += (z - (z/82.5)**2.37) * n",
"------- This function returns the real part of the scattering",
"Imaginary_Spectrum = data.calculate_asf(Stoichiometry) if NearEdgeDataFile is not None: NearEdge_Data =",
"data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values = Im_values Re_values = Real_Spectrum E_values =",
"vector of integers The vector represents the polynomial indices corresponding",
": integer Number of times an energy interval can be",
"calculate the kramers-Kronig transform. Parameters ---------- NearEdgeDataFile : string Path",
"k in range(n,0,-2): Integral += numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if numpy.any(orders <=-3): #",
"poles Integral = numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if numpy.any(orders<=-2): # N<=-2, ln(x) terms",
"accuracy\") new_points = numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values =",
"ni in numpy.where(orders>=0)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for",
"will abuse this section of code for initial testing #Output",
"points Im_midpoints = data.coeffs_to_ASF(midpoints, temp_Im_spectrum) Re_midpoints = KK_PP(midpoints, Full_E, Imaginary_Spectrum,",
"in Full_E Imaginary_Spectrum : two-dimensional `numpy.array` of `float` The array",
"logger.info(\"Calculate Kramers-Kronig transform using general piecewise-polynomial algorithm\") # Need to",
"function returns the real part of the scattering factors evaluated",
"`float` The array consists of columns of polynomial coefficients belonging",
"imaginary_spectrum.T Symb_1 = (( Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4,",
"data values to be allowed. recursion : integer Number of",
"high) at which the near-edge and scattering factor data values",
"Symb_singularities[Eval_hits] = (C2[0, :]*XE**2+C2[1, :]*XE+C2[2, :]+C2[3, :]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) # Finish",
"\"\"\" Stoichiometry = data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction = calc_relativistic_correction(Stoichiometry) Full_E, Imaginary_Spectrum =",
"polynomial indices corresponding to the columns of imaginary_spectrum relativistic_correction :",
"integer/float pairs Each pair in the list consists of an",
"energy interval can be halved before giving up. Returns -------",
"data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E = (Output[1:,0]+Output[0:-1,0])*0.5 #Test_E = numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2 =",
"Imaginary_Spectrum, relativistic_correction) #evaluate error levels Im_error = abs((Im_values[new_points-1]+Im_values[new_points])/2. - Im_midpoints)",
"Integral += numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if numpy.any(orders <=-3): # N<=-3, x^k terms",
"Output = kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) #Output = kk_calculate_real('../../data/GaAs/As.xmu.csv',",
"\"\"\" correction = 0 for z, n in stoichiometry: correction",
"can calculate the value using the `calc_relativistic_correction` function. Returns -------",
"new_points = numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values = Im_values",
"`float` Set of photon energies describing points at which to",
"logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using general piecewise-polynomial algorithm\") # Need",
"Relativistic_Correction, curve_tolerance, curve_recursion) else: Imaginary_Spectrum_Values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data =",
"Kramers-Kronig transform using (n from 1 to -3) piecewise-polynomial algorithm\")",
"numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return output_data if __name__ == '__main__': #use argparse here",
"and parentheses. merge_points : list or tuple pair of `float`",
"Symb_3 = (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2, :]+Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B =",
"with \"Piecewise Polynomial\" algorithm plus the Biggs and Lighthill extended",
"correction = 0 for z, n in stoichiometry: correction +=",
"(Re_error>tolerance) logger.debug(str(numpy.sum(improved))+\" points (out of \"+str(len(improved))+\") can be improved in",
"software package. # # Copyright (c) 2013 <NAME>, <NAME> #",
"of `imaginary_spectrum` is valid Real_Spectrum : numpy vector of `float`",
"Kramers-Kronig transform with \"Piecewise Polynomial\" algorithm plus the Biggs and",
"file containg near-edge data ChemicalFormula : string A standard chemical",
"ln(x) terms i = [slice(None,None,None),slice(None,None,None),orders<=-2] Integral += numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if numpy.any(orders>=0):",
"numpy import os import data def calc_relativistic_correction(stoichiometry): \"\"\"Calculate the relativistic",
"E_values = numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare for next loop temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points",
"the scattering factors evaluated at photon energies specified by Eval_Energy.",
"= kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) #Output = kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs',",
"extrapolation of data values to be allowed. recursion : integer",
"here to get command line arguments #process arguments and pass",
"the Kramers-Kronig transformation.\"\"\" import logging, sys logger = logging.getLogger(__name__) if",
"the `calc_relativistic_correction` function. Returns ------- This function returns the real",
"a ``float`` holding the relativistic corection to the Kramers-Kronig transform.",
"tolerance : float Level of error in linear extrapolation of",
"The array consists of columns of polynomial coefficients belonging to",
"relativistic correction to the Kramers-Kronig transform. Parameters: ----------- stoichiometry :",
"ASF_Data3 = data.coeffs_to_linear(ASF_E, ASF_Data, 0.1) ASF_Data2 = data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E",
"is valid Real_Spectrum : numpy vector of `float` The real",
"pass number \"+str(count+1)+\".\") total_improved_points += numpy.sum(improved) #insert new points and",
"ln(x-E) terms and poles Integral = numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if numpy.any(orders<=-2): #",
"i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in range(n+2,0,2):",
"two-dimensional `numpy.array` of `float` The array consists of columns of",
"parentheses. merge_points : list or tuple pair of `float` values,",
"Integral += numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if numpy.any(orders>=0): # N>=0, x^k terms for",
"axis=1) # Sum areas for approximate integral # Patch singularities",
"of `float` values, or None The photon energy values (low,",
"columns consisting of the photon energy, the real and the",
"Symb_1 = (( Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1))",
"improved = 1 total_improved_points = 0 while count<recursion and numpy.sum(improved)>0:",
"numpy.where(orders<=-3)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in",
"transform. You can calculate the value using the `calc_relativistic_correction` function.",
"(z - (z/82.5)**2.37) * n return correction def KK_General_PP(Eval_Energy, Energy,",
"specified by Eval_Energy. \"\"\" logger = logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform",
"terms of the zlib/libpng license. # For details see LICENSE.txt",
"general piecewise-polynomial algorithm\") # Need to build x-E-n arrays X",
"to magnitudes at photon energies in Full_E Imaginary_Spectrum : two-dimensional",
"data accuracy\") new_points = numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values",
"Full_coeffs = imaginary_spectrum.T Symb_1 = (( Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3,",
"abs((Im_values[new_points-1]+Im_values[new_points])/2. - Im_midpoints) Re_error = abs((Re_values[new_points-1]+Re_values[new_points])/2. - Re_midpoints) improved =",
"numpy.sum(improved) #insert new points and values Im_values = numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values",
"loading and processing and then calculate the kramers-Kronig transform. Parameters",
"i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in range(n,0,-2):",
"n return correction def KK_General_PP(Eval_Energy, Energy, imaginary_spectrum, orders, relativistic_correction): \"\"\"Calculate",
"next loop temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points = numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0] new_points =",
"photon energy values (low, high) at which the near-edge and",
"midpoints = (E_values[new_points-1]+E_values[new_points])/2. #evaluate at new points Im_midpoints = data.coeffs_to_ASF(midpoints,",
"count += 1 #import matplotlib #matplotlib.use('WXAgg') #import pylab #pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok')",
":]*E+Full_coeffs[2, :]-Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3 = (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2, :]+Full_coeffs[3,",
"spectrum. \"\"\" logger.debug(\"Improve data accuracy\") new_points = numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values =",
"logging, sys logger = logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG)",
"data.ParseChemicalFormula('GaAs') Relativistic_Correction = calc_relativistic_correction(Stoichiometry) ASF_E, ASF_Data = data.calculate_asf(Stoichiometry) ASF_Data3 =",
"data accuracy by inserting \"+str(total_improved_points)+\" extra points.\") return numpy.vstack((E_values,Re_values,Im_values)).T def",
"for z, n in stoichiometry: correction += (z - (z/82.5)**2.37)",
"float Level of error in linear extrapolation of data values",
"a numpy array with columns consisting of the photon energy,",
"of the zlib/libpng license. # For details see LICENSE.txt \"\"\"This",
"= data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction = calc_relativistic_correction(Stoichiometry) Full_E, Imaginary_Spectrum = data.calculate_asf(Stoichiometry) if",
"real spectrum Energy : numpy vector of `float` Set of",
"the real spectrum Energy : numpy vector of `float` Set",
"package. # # Copyright (c) 2013 <NAME>, <NAME> # #",
"numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C = numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N = numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles = numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders))))",
"C = numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N = numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles = numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) #",
"\"\"\" logger = logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using general piecewise-polynomial",
"\"+str(total_improved_points)+\" extra points.\") return numpy.vstack((E_values,Re_values,Im_values)).T def kk_calculate_real(NearEdgeDataFile, ChemicalFormula, load_options=None, input_data_type=None,",
"for which each row of `imaginary_spectrum` is valid imaginary_spectrum :",
"Full_E, Imaginary_Spectrum, merge_points=merge_points, add_background=add_background, fix_distortions=fix_distortions) Real_Spectrum = KK_PP(Full_E, Full_E, Imaginary_Spectrum,",
"Energy, imaginary_spectrum, orders, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with \"Piecewise Polynomial\"",
"* n return correction def KK_General_PP(Eval_Energy, Energy, imaginary_spectrum, orders, relativistic_correction):",
"Energy : numpy vector of `float` Set of photon energies",
"Parameters: ----------- stoichiometry : array of integer/float pairs Each pair",
"the spectrum corresponding to magnitudes at photon energies in Full_E",
"= 0 for z, n in stoichiometry: correction += (z",
"else: Imaginary_Spectrum_Values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data = numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return output_data",
"be allowed. recursion : integer Number of times an energy",
"of the scattering factors. \"\"\" Stoichiometry = data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction =",
"linear interpolation is more accurate. Parameters ---------- Full_E : numpy",
"to the Kramers-Kronig transform. (You can calculate the value using",
"merge_points=None, add_background=False, fix_distortions=False, curve_tolerance=None, curve_recursion=50): \"\"\"Do all data loading and",
"pairs Each pair in the list consists of an atomic",
"the real and the imaginary parts of the scattering factors.",
"``float`` holding the relativistic corection to the Kramers-Kronig transform. \"\"\"",
"ASF_E, ASF_Data = data.calculate_asf(Stoichiometry) ASF_Data3 = data.coeffs_to_linear(ASF_E, ASF_Data, 0.1) ASF_Data2",
"piecewise-polynomial algorithm\") X1 = Energy[0:-1] X2 = Energy[1:] E =",
"to file containg near-edge data ChemicalFormula : string A standard",
"numpy.where(orders>=0)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in",
"is part of the Kramers-Kronig Calculator software package. # #",
"if __name__ == '__main__': #use argparse here to get command",
"= numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C = numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N = numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles =",
": float The relativistic correction to the Kramers-Kronig transform. (You",
"count<recursion and numpy.sum(improved)>0: #get E_midpoints midpoints = (E_values[new_points-1]+E_values[new_points])/2. #evaluate at",
"1 total_improved_points = 0 while count<recursion and numpy.sum(improved)>0: #get E_midpoints",
"Sum areas for approximate integral # Patch singularities hits =",
"= numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles = numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) # all N, ln(x+E) and",
"of that element. Returns ------- This function returns a ``float``",
"= numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if numpy.any(orders<=-2): # N<=-2, ln(x) terms i =",
"logger = logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using (n from 1",
"which the near-edge and scattering factor data values are set",
"= Energy[E_hits[2:]] XE = Energy[E_hits[1:-1]] X2 = Energy[E_hits[:-2]] C1 =",
"Energy, imaginary_spectrum, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with \"Piecewise Polynomial\" algorithm",
"#Test_E = numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2 = KK_PP(Test_E, Output[:,0], Im, Relativistic_Correction) import",
"+= 1 #import matplotlib #matplotlib.use('WXAgg') #import pylab #pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og')",
"`imaginary_spectrum` is valid Real_Spectrum : numpy vector of `float` The",
"KK_Re def improve_accuracy(Full_E, Real_Spectrum, Imaginary_Spectrum, relativistic_correction, tolerance, recursion=50): \"\"\"Calculate extra",
": two-dimensional `numpy.array` of `float` The array consists of columns",
"#prepare for next loop temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points = numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0]",
"values (low, high) at which the near-edge and scattering factor",
"input_data_type='NEXAFS') Output = kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) #Output =",
"array consists of columns of polynomial coefficients belonging to the",
"numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0] new_points = numpy.vstack((new_points, new_points+1)).T.flatten() count += 1 #import",
"1)).T Full_coeffs = imaginary_spectrum.T Symb_1 = (( Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0,",
"vector of `float` The real part of the spectrum corresponding",
"three columns respectively representing photon energy, the real spectrum and",
"set equal so as to ensure continuity of the merged",
"part of the Kramers-Kronig Calculator software package. # # Copyright",
"function. Returns ------- This function returns the real part of",
"+= numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if numpy.any(orders>=0): # N>=0, x^k terms for ni",
"= Full_coeffs[:, E_hits[2:-1]] C2 = Full_coeffs[:, E_hits[1:-2]] Symb_singularities = numpy.zeros(len(Eval_Energy))",
"None: NearEdge_Data = data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf') Full_E, Imaginary_Spectrum = data.merge_spectra(NearEdge_Data, Full_E,",
"if numpy.any(orders<=-2): # N<=-2, ln(x) terms i = [slice(None,None,None),slice(None,None,None),orders<=-2] Integral",
"linear extrapolation of data values to be allowed. recursion :",
"details see LICENSE.txt \"\"\"This module implements the Kramers-Kronig transformation.\"\"\" import",
"real spectrum and the imaginary spectrum. \"\"\" logger.debug(\"Improve data accuracy\")",
"matplotlib matplotlib.use('WXAgg') import pylab pylab.figure() pylab.plot(Output[:,0],Output[:,1],'xg-',Output[:,0],Output[:,2],'xb-') pylab.plot(ASF_E,ASF_Data2,'+r') #pylab.plot(ASF_E,ASF_Data22,'xr') pylab.plot(ASF_Data3[0],ASF_Data3[1],'r-') #pylab.plot(Test_E,Real_Spectrum2,'*y')",
"row of `imaginary_spectrum` is valid imaginary_spectrum : two-dimensional `numpy.array` of",
"software is licensed under the terms of the zlib/libpng license.",
"using (n from 1 to -3) piecewise-polynomial algorithm\") X1 =",
"Patch singularities hits = Energy[1:-1]==E[:,0:-1] E_hits = numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False]) Eval_hits",
"integral # Patch singularities hits = Energy[1:-1]==E[:,0:-1] E_hits = numpy.append(numpy.insert(numpy.any(hits,",
"of five columns of polynomial coefficients: A_1, A_0, A_-1, A_-2,",
"approximate integral # Patch singularities hits = Energy[1:-1]==E[:,0:-1] E_hits =",
"You can calculate the value using the `calc_relativistic_correction` function. Returns",
"Returns ------- This function returns the real part of the",
"Imaginary_Spectrum[1:] count = 0 improved = 1 total_improved_points = 0",
"# Finish things off KK_Re = (Symb_B-Symb_singularities) / (math.pi*Eval_Energy) +",
"# # The software is licensed under the terms of",
"which each row of `imaginary_spectrum` is valid imaginary_spectrum : two-dimensional",
"the Kramers-Kronig transform. You can calculate the value using the",
"columns respectively representing photon energy, the real spectrum and the",
"array with three columns respectively representing photon energy, the real",
"= numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False]) Eval_hits = numpy.any(hits, axis=1) X1 = Energy[E_hits[2:]]",
"two-dimensional `numpy.array` of `float` The array consists of five columns",
"Calculator software package. # # Copyright (c) 2013 <NAME>, <NAME>",
"E_values = Full_E temp_Im_spectrum = Imaginary_Spectrum[1:] count = 0 improved",
"numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare for next loop temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points = numpy.where(numpy.insert(numpy.zeros(Im_values.shape,",
"numpy vector of `float` Set of photon energies describing intervals",
": string A standard chemical formula string consisting of element",
"input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) Stoichiometry = data.ParseChemicalFormula('LaAlO3') #Stoichiometry = data.ParseChemicalFormula('GaAs') Relativistic_Correction",
"numpy.tile(Eval_Energy, (len(Energy)-1, 1)).T Full_coeffs = imaginary_spectrum.T Symb_1 = (( Full_coeffs[0,",
"using the `calc_relativistic_correction` function. Returns ------- This function returns the",
"1 to -3) piecewise-polynomial algorithm\") X1 = Energy[0:-1] X2 =",
":]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3 = (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2, :]+Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B",
"The relativistic correction to the Kramers-Kronig transform. (You can calculate",
"testing #Output = kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14', input_data_type='NEXAFS') Output = kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3',",
"numpy.any(hits, axis=1) X1 = Energy[E_hits[2:]] XE = Energy[E_hits[1:-1]] X2 =",
"0 while count<recursion and numpy.sum(improved)>0: #get E_midpoints midpoints = (E_values[new_points-1]+E_values[new_points])/2.",
"logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using (n from 1 to -3)",
"vector of `float` Set of photon energies describing intervals for",
"KK_PP(midpoints, Full_E, Imaginary_Spectrum, relativistic_correction) #evaluate error levels Im_error = abs((Im_values[new_points-1]+Im_values[new_points])/2.",
"Eval_Energy. \"\"\" logger = logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using (n",
"data ChemicalFormula : string A standard chemical formula string consisting",
"def calc_relativistic_correction(stoichiometry): \"\"\"Calculate the relativistic correction to the Kramers-Kronig transform.",
"(Output[1:,0]+Output[0:-1,0])*0.5 #Test_E = numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2 = KK_PP(Test_E, Output[:,0], Im, Relativistic_Correction)",
"the value using the `calc_relativistic_correction` function. Returns ------- This function",
"array consists of five columns of polynomial coefficients: A_1, A_0,",
"evaluate the real spectrum Energy : numpy vector of `float`",
"0 for z, n in stoichiometry: correction += (z -",
"+ relativistic_correction def KK_PP(Eval_Energy, Energy, imaginary_spectrum, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform",
"= Im_values Re_values = Real_Spectrum E_values = Full_E temp_Im_spectrum =",
"to get command line arguments #process arguments and pass to",
":]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2, :]-Full_coeffs[3, :]*E**-1+Full_coeffs[4,",
"of the photon energy, the real and the imaginary parts",
"Relativistic_Correction) if curve_tolerance is not None: output_data = improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction,",
"numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E = numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C = numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N = numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1))",
":]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B = numpy.sum(Symb_2 - Symb_1 - Symb_3, axis=1)",
": numpy vector of `float` Set of photon energies describing",
"logger.debug(\"Improve data accuracy\") new_points = numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1])))",
"#pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log') #pylab.show() logger.info(\"Improved data accuracy by inserting \"+str(total_improved_points)+\" extra",
"all data loading and processing and then calculate the kramers-Kronig",
"For details see LICENSE.txt \"\"\"This module implements the Kramers-Kronig transformation.\"\"\"",
"= data.ParseChemicalFormula('LaAlO3') #Stoichiometry = data.ParseChemicalFormula('GaAs') Relativistic_Correction = calc_relativistic_correction(Stoichiometry) ASF_E, ASF_Data",
"'order' orders : numpy vector of integers The vector represents",
"processing and then calculate the kramers-Kronig transform. Parameters ---------- NearEdgeDataFile",
"calc_relativistic_correction(stoichiometry): \"\"\"Calculate the relativistic correction to the Kramers-Kronig transform. Parameters:",
":]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B = numpy.sum(Symb_2 - Symb_1 - Symb_3, axis=1) #",
"transform. Parameters: ----------- stoichiometry : array of integer/float pairs Each",
"the relativistic corection to the Kramers-Kronig transform. \"\"\" correction =",
"The photon energy values (low, high) at which the near-edge",
"and the imaginary parts of the scattering factors. \"\"\" Stoichiometry",
"return correction def KK_General_PP(Eval_Energy, Energy, imaginary_spectrum, orders, relativistic_correction): \"\"\"Calculate Kramers-Kronig",
"`float` The real part of the spectrum corresponding to magnitudes",
"Set of photon energies describing points at which to evaluate",
"values to be allowed. recursion : integer Number of times",
"Copyright (c) 2013 <NAME>, <NAME> # # The software is",
"recursion : integer Number of times an energy interval can",
"Re_error = abs((Re_values[new_points-1]+Re_values[new_points])/2. - Re_midpoints) improved = (Im_error>tolerance) | (Re_error>tolerance)",
"'LaAlO3', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) #Output = kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs', input_data_type='NEXAFS', fix_distortions=True,",
"= logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout) import math",
"can be improved in pass number \"+str(count+1)+\".\") total_improved_points += numpy.sum(improved)",
"to the columns of imaginary_spectrum relativistic_correction : float The relativistic",
"= Energy[1:-1]==E[:,0:-1] E_hits = numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False]) Eval_hits = numpy.any(hits, axis=1)",
"numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False]) Eval_hits = numpy.any(hits, axis=1) X1 = Energy[E_hits[2:]] XE",
"correction to the Kramers-Kronig transform. You can calculate the value",
"#matplotlib.use('WXAgg') #import pylab #pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-')",
"real part of the spectrum corresponding to magnitudes at photon",
"= numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return output_data if __name__ == '__main__': #use argparse",
"pythonic function #I will abuse this section of code for",
"#Output = kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14', input_data_type='NEXAFS') Output = kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3', input_data_type='NEXAFS',",
"of `float` Set of photon energies describing points at which",
"Kramers-Kronig transform. You can calculate the value using the `calc_relativistic_correction`",
"(1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2, :]+Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B = numpy.sum(Symb_2 -",
"belonging to the power terms indicated by 'order' orders :",
"in range(n+2,0,2): Integral += numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug(\"Done!\") return Integral / math.pi",
"#Real_Spectrum2 = KK_PP(Test_E, Output[:,0], Im, Relativistic_Correction) import matplotlib matplotlib.use('WXAgg') import",
"import pylab pylab.figure() pylab.plot(Output[:,0],Output[:,1],'xg-',Output[:,0],Output[:,2],'xb-') pylab.plot(ASF_E,ASF_Data2,'+r') #pylab.plot(ASF_E,ASF_Data22,'xr') pylab.plot(ASF_Data3[0],ASF_Data3[1],'r-') #pylab.plot(Test_E,Real_Spectrum2,'*y') pylab.xscale('log') pylab.show()",
"axis=0),[0,0],False),[False,False]) Eval_hits = numpy.any(hits, axis=1) X1 = Energy[E_hits[2:]] XE =",
"transform. \"\"\" correction = 0 for z, n in stoichiometry:",
"---------- Eval_Energy : numpy vector of `float` Set of photon",
"`float` The array consists of five columns of polynomial coefficients:",
"coding: utf-8 -*- # This file is part of the",
"atomic number and the relative proportion of that element. Returns",
"with columns consisting of the photon energy, the real and",
"[slice(None,None,None),slice(None,None,None),orders<=-2] Integral += numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if numpy.any(orders>=0): # N>=0, x^k terms",
"integer Number of times an energy interval can be halved",
"-3) piecewise-polynomial algorithm\") X1 = Energy[0:-1] X2 = Energy[1:] E",
"Imaginary_Spectrum, Relativistic_Correction) if curve_tolerance is not None: output_data = improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum,",
"Re_midpoints) improved = (Im_error>tolerance) | (Re_error>tolerance) logger.debug(str(numpy.sum(improved))+\" points (out of",
"transform. Parameters ---------- NearEdgeDataFile : string Path to file containg",
": list or tuple pair of `float` values, or None",
"Re_values = Real_Spectrum E_values = Full_E temp_Im_spectrum = Imaginary_Spectrum[1:] count",
"<reponame>benajamin/kkcalc<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- # This",
"relative proportion of that element. Returns ------- This function returns",
"if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout) import math import numpy",
"license. # For details see LICENSE.txt \"\"\"This module implements the",
"\"Piecewise Polynomial\" algorithm plus the Biggs and Lighthill extended data.",
"(n from 1 to -3) piecewise-polynomial algorithm\") X1 = Energy[0:-1]",
"tolerance, recursion=50): \"\"\"Calculate extra data points so that a linear",
"= abs((Re_values[new_points-1]+Re_values[new_points])/2. - Re_midpoints) improved = (Im_error>tolerance) | (Re_error>tolerance) logger.debug(str(numpy.sum(improved))+\"",
"ChemicalFormula, load_options=None, input_data_type=None, merge_points=None, add_background=False, fix_distortions=False, curve_tolerance=None, curve_recursion=50): \"\"\"Do all",
"Full_E, Imaginary_Spectrum, Relativistic_Correction) if curve_tolerance is not None: output_data =",
"or tuple pair of `float` values, or None The photon",
"Real_Spectrum = KK_PP(Full_E, Full_E, Imaginary_Spectrum, Relativistic_Correction) if curve_tolerance is not",
"NearEdge_Data = data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf') Full_E, Imaginary_Spectrum = data.merge_spectra(NearEdge_Data, Full_E, Imaginary_Spectrum,",
"temp_Im_spectrum) Re_midpoints = KK_PP(midpoints, Full_E, Imaginary_Spectrum, relativistic_correction) #evaluate error levels",
"- (z/82.5)**2.37) * n return correction def KK_General_PP(Eval_Energy, Energy, imaginary_spectrum,",
"is not None: output_data = improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction, curve_tolerance, curve_recursion) else:",
"E_midpoints midpoints = (E_values[new_points-1]+E_values[new_points])/2. #evaluate at new points Im_midpoints =",
"relativistic_correction, tolerance, recursion=50): \"\"\"Calculate extra data points so that a",
"string Path to file containg near-edge data ChemicalFormula : string",
"merge_points : list or tuple pair of `float` values, or",
"transformation.\"\"\" import logging, sys logger = logging.getLogger(__name__) if __name__ ==",
"N<=-2, ln(x) terms i = [slice(None,None,None),slice(None,None,None),orders<=-2] Integral += numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if",
"Re_values = numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values = numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare for next loop",
"axis=1) X1 = Energy[E_hits[2:]] XE = Energy[E_hits[1:-1]] X2 = Energy[E_hits[:-2]]",
"correction def KK_General_PP(Eval_Energy, Energy, imaginary_spectrum, orders, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform",
"and the relative proportion of that element. Returns ------- This",
"numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if numpy.any(orders <=-3): # N<=-3, x^k terms for ni",
"relativistic corection to the Kramers-Kronig transform. \"\"\" correction = 0",
"sys logger = logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout)",
"curve_tolerance is not None: output_data = improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction, curve_tolerance, curve_recursion)",
":]-Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3 = (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2, :]+Full_coeffs[3, :]*E**-1+Full_coeffs[4,",
"= numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values = numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare for next loop temp_Im_spectrum",
"describing intervals for which each row of `imaginary_spectrum` is valid",
"Finish things off KK_Re = (Symb_B-Symb_singularities) / (math.pi*Eval_Energy) + relativistic_correction",
"in linear extrapolation of data values to be allowed. recursion",
"and numpy.sum(improved)>0: #get E_midpoints midpoints = (E_values[new_points-1]+E_values[new_points])/2. #evaluate at new",
"curve_recursion=50): \"\"\"Do all data loading and processing and then calculate",
"== '__main__': logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout) import math import numpy import os",
"Level of error in linear extrapolation of data values to",
"of photon energies describing intervals for which each row of",
"Eval_Energy. \"\"\" logger = logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using general",
"of times an energy interval can be halved before giving",
"extra points.\") return numpy.vstack((E_values,Re_values,Im_values)).T def kk_calculate_real(NearEdgeDataFile, ChemicalFormula, load_options=None, input_data_type=None, merge_points=None,",
"E_hits[2:-1]] C2 = Full_coeffs[:, E_hits[1:-2]] Symb_singularities = numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits] =",
"abuse this section of code for initial testing #Output =",
"N>=0, x^k terms for ni in numpy.where(orders>=0)[0]: i = [slice(None,None,None),slice(None,None,None),ni]",
"\"\"\"Calculate Kramers-Kronig transform with \"Piecewise Polynomial\" algorithm plus the Biggs",
"near-edge data ChemicalFormula : string A standard chemical formula string",
"(out of \"+str(len(improved))+\") can be improved in pass number \"+str(count+1)+\".\")",
"containg near-edge data ChemicalFormula : string A standard chemical formula",
"#Test_E = (Output[1:,0]+Output[0:-1,0])*0.5 #Test_E = numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2 = KK_PP(Test_E, Output[:,0],",
"= numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values = numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values = numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare for",
"Parameters ---------- Full_E : numpy vector of `float` Set of",
"stoichiometry: correction += (z - (z/82.5)**2.37) * n return correction",
"columns of polynomial coefficients belonging to the power terms indicated",
"#insert new points and values Im_values = numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values =",
"function returns a numpy array with columns consisting of the",
"points (out of \"+str(len(improved))+\") can be improved in pass number",
"arguments and pass to a pythonic function #I will abuse",
"= (Symb_B-Symb_singularities) / (math.pi*Eval_Energy) + relativistic_correction logger.debug(\"Done!\") return KK_Re def",
"and the imaginary spectrum. \"\"\" logger.debug(\"Improve data accuracy\") new_points =",
"numpy vector of `float` The real part of the spectrum",
"logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout) import math import",
"of data values to be allowed. recursion : integer Number",
"indices corresponding to the columns of imaginary_spectrum relativistic_correction : float",
"magnitudes at photon energies in Full_E Imaginary_Spectrum : two-dimensional `numpy.array`",
"correction to the Kramers-Kronig transform. Parameters: ----------- stoichiometry : array",
"things off KK_Re = (Symb_B-Symb_singularities) / (math.pi*Eval_Energy) + relativistic_correction logger.debug(\"Done!\")",
"count = 0 improved = 1 total_improved_points = 0 while",
"to the Kramers-Kronig transform. Parameters: ----------- stoichiometry : array of",
"numpy array with three columns respectively representing photon energy, the",
"#use argparse here to get command line arguments #process arguments",
"real part of the scattering factors evaluated at photon energies",
":]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2, :]+Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B = numpy.sum(Symb_2 - Symb_1",
"the polynomial indices corresponding to the columns of imaginary_spectrum relativistic_correction",
"n = orders[ni] for k in range(n+2,0,2): Integral += numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0)",
"numpy.sum(Symb_2 - Symb_1 - Symb_3, axis=1) # Sum areas for",
"areas for approximate integral # Patch singularities hits = Energy[1:-1]==E[:,0:-1]",
"data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction = calc_relativistic_correction(Stoichiometry) Full_E, Imaginary_Spectrum = data.calculate_asf(Stoichiometry) if NearEdgeDataFile",
"/ (math.pi*Eval_Energy) + relativistic_correction logger.debug(\"Done!\") return KK_Re def improve_accuracy(Full_E, Real_Spectrum,",
"logger.info(\"Improved data accuracy by inserting \"+str(total_improved_points)+\" extra points.\") return numpy.vstack((E_values,Re_values,Im_values)).T",
"times an energy interval can be halved before giving up.",
"output_data = numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return output_data if __name__ == '__main__': #use",
"#!/usr/bin/env python # -*- coding: utf-8 -*- # This file",
"-*- # This file is part of the Kramers-Kronig Calculator",
"math import numpy import os import data def calc_relativistic_correction(stoichiometry): \"\"\"Calculate",
"imaginary_spectrum : two-dimensional `numpy.array` of `float` The array consists of",
"#get E_midpoints midpoints = (E_values[new_points-1]+E_values[new_points])/2. #evaluate at new points Im_midpoints",
"by Eval_Energy. \"\"\" logger = logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using",
"merged data set. Returns ------- This function returns a numpy",
"of columns of polynomial coefficients belonging to the power terms",
"= numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N = numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles = numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) # all",
"polynomial coefficients: A_1, A_0, A_-1, A_-2, A_-3 relativistic_correction : float",
"Energy[E_hits[2:]] XE = Energy[E_hits[1:-1]] X2 = Energy[E_hits[:-2]] C1 = Full_coeffs[:,",
"a pythonic function #I will abuse this section of code",
"Integral += numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug(\"Done!\") return Integral / math.pi + relativistic_correction",
"#import pylab #pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-')",
"(len(Energy)-1, 1)).T Full_coeffs = imaginary_spectrum.T Symb_1 = (( Full_coeffs[0, :]*E+Full_coeffs[1,",
"the zlib/libpng license. # For details see LICENSE.txt \"\"\"This module",
"for k in range(n+2,0,2): Integral += numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug(\"Done!\") return Integral",
"N, ln(x+E) and ln(x-E) terms and poles Integral = numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2))",
"get command line arguments #process arguments and pass to a",
"# Need to build x-E-n arrays X = numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E",
"in range(n,0,-2): Integral += numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if numpy.any(orders <=-3): # N<=-3,",
"describing points at which to evaluate the real spectrum Energy",
"Symb_singularities = numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits] = (C2[0, :]*XE**2+C2[1, :]*XE+C2[2, :]+C2[3, :]*XE**-1+C2[4,",
": numpy vector of integers The vector represents the polynomial",
"for which each row of `imaginary_spectrum` is valid Real_Spectrum :",
"allowed. recursion : integer Number of times an energy interval",
"correction += (z - (z/82.5)**2.37) * n return correction def",
"Energy[E_hits[1:-1]] X2 = Energy[E_hits[:-2]] C1 = Full_coeffs[:, E_hits[2:-1]] C2 =",
"__name__ == '__main__': logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout) import math import numpy import",
"= Energy[E_hits[1:-1]] X2 = Energy[E_hits[:-2]] C1 = Full_coeffs[:, E_hits[2:-1]] C2",
"interpolation is more accurate. Parameters ---------- Full_E : numpy vector",
": float The relativistic correction to the Kramers-Kronig transform. You",
"valid Real_Spectrum : numpy vector of `float` The real part",
"(C2[0, :]*XE**2+C2[1, :]*XE+C2[2, :]+C2[3, :]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) # Finish things off",
"input_data_type=None, merge_points=None, add_background=False, fix_distortions=False, curve_tolerance=None, curve_recursion=50): \"\"\"Do all data loading",
"Integral / math.pi + relativistic_correction def KK_PP(Eval_Energy, Energy, imaginary_spectrum, relativistic_correction):",
"NearEdgeDataFile : string Path to file containg near-edge data ChemicalFormula",
"N = numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles = numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) # all N, ln(x+E)",
"logger.debug(\"Done!\") return KK_Re def improve_accuracy(Full_E, Real_Spectrum, Imaginary_Spectrum, relativistic_correction, tolerance, recursion=50):",
"Im_midpoints) Re_error = abs((Re_values[new_points-1]+Re_values[new_points])/2. - Re_midpoints) improved = (Im_error>tolerance) |",
"kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14', input_data_type='NEXAFS') Output = kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05)",
"X2 = Energy[1:] E = numpy.tile(Eval_Energy, (len(Energy)-1, 1)).T Full_coeffs =",
"singularities hits = Energy[1:-1]==E[:,0:-1] E_hits = numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False]) Eval_hits =",
"= data.coeffs_to_ASF(midpoints, temp_Im_spectrum) Re_midpoints = KK_PP(midpoints, Full_E, Imaginary_Spectrum, relativistic_correction) #evaluate",
"terms indicated by 'order' orders : numpy vector of integers",
"(E_values[new_points-1]+E_values[new_points])/2. #evaluate at new points Im_midpoints = data.coeffs_to_ASF(midpoints, temp_Im_spectrum) Re_midpoints",
"correction to the Kramers-Kronig transform. (You can calculate the value",
"the Kramers-Kronig transform. (You can calculate the value using the",
"integers The vector represents the polynomial indices corresponding to the",
"temp_Im_spectrum = Imaginary_Spectrum[1:] count = 0 improved = 1 total_improved_points",
"function.) tolerance : float Level of error in linear extrapolation",
"to build x-E-n arrays X = numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E = numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders)))",
"+= numpy.sum(improved) #insert new points and values Im_values = numpy.insert(Im_values,new_points[improved],Im_midpoints[improved])",
"Real_Spectrum E_values = Full_E temp_Im_spectrum = Imaginary_Spectrum[1:] count = 0",
"The software is licensed under the terms of the zlib/libpng",
"curve_tolerance=None, curve_recursion=50): \"\"\"Do all data loading and processing and then",
"output_data = improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction, curve_tolerance, curve_recursion) else: Imaginary_Spectrum_Values = data.coeffs_to_ASF(Full_E,",
"= (C2[0, :]*XE**2+C2[1, :]*XE+C2[2, :]+C2[3, :]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) # Finish things",
"Im_values Re_values = Real_Spectrum E_values = Full_E temp_Im_spectrum = Imaginary_Spectrum[1:]",
"numpy.vstack((E_values,Re_values,Im_values)).T def kk_calculate_real(NearEdgeDataFile, ChemicalFormula, load_options=None, input_data_type=None, merge_points=None, add_background=False, fix_distortions=False, curve_tolerance=None,",
"representing photon energy, the real spectrum and the imaginary spectrum.",
"`float` values, or None The photon energy values (low, high)",
"the Kramers-Kronig Calculator software package. # # Copyright (c) 2013",
"\"\"\"Calculate extra data points so that a linear interpolation is",
"is not None: NearEdge_Data = data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf') Full_E, Imaginary_Spectrum =",
"'GaAs', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) Stoichiometry = data.ParseChemicalFormula('LaAlO3') #Stoichiometry = data.ParseChemicalFormula('GaAs')",
"consists of columns of polynomial coefficients belonging to the power",
"by inserting \"+str(total_improved_points)+\" extra points.\") return numpy.vstack((E_values,Re_values,Im_values)).T def kk_calculate_real(NearEdgeDataFile, ChemicalFormula,",
"improved = (Im_error>tolerance) | (Re_error>tolerance) logger.debug(str(numpy.sum(improved))+\" points (out of \"+str(len(improved))+\")",
"= logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using general piecewise-polynomial algorithm\") #",
"a linear interpolation is more accurate. Parameters ---------- Full_E :",
"five columns of polynomial coefficients: A_1, A_0, A_-1, A_-2, A_-3",
"\"\"\" logger.debug(\"Improve data accuracy\") new_points = numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values = data.coeffs_to_ASF(Full_E,",
"of \"+str(len(improved))+\") can be improved in pass number \"+str(count+1)+\".\") total_improved_points",
"None The photon energy values (low, high) at which the",
"pylab #pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-')",
"def improve_accuracy(Full_E, Real_Spectrum, Imaginary_Spectrum, relativistic_correction, tolerance, recursion=50): \"\"\"Calculate extra data",
"improve_accuracy(Full_E, Real_Spectrum, Imaginary_Spectrum, relativistic_correction, tolerance, recursion=50): \"\"\"Calculate extra data points",
"+ relativistic_correction logger.debug(\"Done!\") return KK_Re def improve_accuracy(Full_E, Real_Spectrum, Imaginary_Spectrum, relativistic_correction,",
"with three columns respectively representing photon energy, the real spectrum",
"KK_PP(Test_E, Output[:,0], Im, Relativistic_Correction) import matplotlib matplotlib.use('WXAgg') import pylab pylab.figure()",
"# Patch singularities hits = Energy[1:-1]==E[:,0:-1] E_hits = numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False])",
"((-Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2, :]-Full_coeffs[3,",
"X1 = Energy[0:-1] X2 = Energy[1:] E = numpy.tile(Eval_Energy, (len(Energy)-1,",
"data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf') Full_E, Imaginary_Spectrum = data.merge_spectra(NearEdge_Data, Full_E, Imaginary_Spectrum, merge_points=merge_points, add_background=add_background,",
"Stoichiometry = data.ParseChemicalFormula('LaAlO3') #Stoichiometry = data.ParseChemicalFormula('GaAs') Relativistic_Correction = calc_relativistic_correction(Stoichiometry) ASF_E,",
"kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) Stoichiometry = data.ParseChemicalFormula('LaAlO3') #Stoichiometry =",
"energies describing intervals for which each row of `imaginary_spectrum` is",
"of imaginary_spectrum relativistic_correction : float The relativistic correction to the",
"`imaginary_spectrum` is valid imaginary_spectrum : two-dimensional `numpy.array` of `float` The",
"= orders[ni] for k in range(n,0,-2): Integral += numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if",
"can be halved before giving up. Returns ------- This function",
"to the Kramers-Kronig transform. You can calculate the value using",
"#pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log') #pylab.show()",
"file is part of the Kramers-Kronig Calculator software package. #",
"function #I will abuse this section of code for initial",
"Energy[1:] E = numpy.tile(Eval_Energy, (len(Energy)-1, 1)).T Full_coeffs = imaginary_spectrum.T Symb_1",
"data points so that a linear interpolation is more accurate.",
"= (Im_error>tolerance) | (Re_error>tolerance) logger.debug(str(numpy.sum(improved))+\" points (out of \"+str(len(improved))+\") can",
"import os import data def calc_relativistic_correction(stoichiometry): \"\"\"Calculate the relativistic correction",
"poles = numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) # all N, ln(x+E) and ln(x-E) terms",
"Returns ------- This function returns a numpy array with columns",
"numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug(\"Done!\") return Integral / math.pi + relativistic_correction def KK_PP(Eval_Energy,",
"Biggs and Lighthill extended data. Parameters ---------- Eval_Energy : numpy",
"This function returns a numpy array with three columns respectively",
"numpy.vstack((new_points, new_points+1)).T.flatten() count += 1 #import matplotlib #matplotlib.use('WXAgg') #import pylab",
"values Im_values = numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values = numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values = numpy.insert(E_values,new_points[improved],midpoints[improved])",
"data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data = numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return output_data if __name__ ==",
"relativistic_correction) #evaluate error levels Im_error = abs((Im_values[new_points-1]+Im_values[new_points])/2. - Im_midpoints) Re_error",
"implements the Kramers-Kronig transformation.\"\"\" import logging, sys logger = logging.getLogger(__name__)",
"imaginary_spectrum relativistic_correction : float The relativistic correction to the Kramers-Kronig",
"#plot_Im_values = Im_values Re_values = Real_Spectrum E_values = Full_E temp_Im_spectrum",
"= data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data = numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return output_data if __name__",
"corection to the Kramers-Kronig transform. \"\"\" correction = 0 for",
"and Lighthill extended data. Parameters ---------- Eval_Energy : numpy vector",
"Need to build x-E-n arrays X = numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E =",
"more accurate. Parameters ---------- Full_E : numpy vector of `float`",
"and processing and then calculate the kramers-Kronig transform. Parameters ----------",
"A_0, A_-1, A_-2, A_-3 relativistic_correction : float The relativistic correction",
"Symb_3, axis=1) # Sum areas for approximate integral # Patch",
"E_hits[1:-2]] Symb_singularities = numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits] = (C2[0, :]*XE**2+C2[1, :]*XE+C2[2, :]+C2[3,",
"#pylab.show() logger.info(\"Improved data accuracy by inserting \"+str(total_improved_points)+\" extra points.\") return",
"a numpy array with three columns respectively representing photon energy,",
"under the terms of the zlib/libpng license. # For details",
"= imaginary_spectrum.T Symb_1 = (( Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4,",
"licensed under the terms of the zlib/libpng license. # For",
"if numpy.any(orders <=-3): # N<=-3, x^k terms for ni in",
"number \"+str(count+1)+\".\") total_improved_points += numpy.sum(improved) #insert new points and values",
"\"+str(len(improved))+\") can be improved in pass number \"+str(count+1)+\".\") total_improved_points +=",
"curve_recursion) else: Imaginary_Spectrum_Values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data = numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return",
"X = numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E = numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C = numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N",
"polynomial coefficients belonging to the power terms indicated by 'order'",
"logger.debug(str(numpy.sum(improved))+\" points (out of \"+str(len(improved))+\") can be improved in pass",
"= Full_E temp_Im_spectrum = Imaginary_Spectrum[1:] count = 0 improved =",
"piecewise-polynomial algorithm\") # Need to build x-E-n arrays X =",
"Real_Spectrum, Imaginary_Spectrum, relativistic_correction, tolerance, recursion=50): \"\"\"Calculate extra data points so",
"value using the `calc_relativistic_correction` function.) tolerance : float Level of",
"Parameters ---------- NearEdgeDataFile : string Path to file containg near-edge",
"= numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0] new_points = numpy.vstack((new_points, new_points+1)).T.flatten() count += 1",
"= improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction, curve_tolerance, curve_recursion) else: Imaginary_Spectrum_Values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1])))",
"to a pythonic function #I will abuse this section of",
"from 1 to -3) piecewise-polynomial algorithm\") X1 = Energy[0:-1] X2",
"so as to ensure continuity of the merged data set.",
"Full_E, Imaginary_Spectrum = data.calculate_asf(Stoichiometry) if NearEdgeDataFile is not None: NearEdge_Data",
"string consisting of element symbols, numbers and parentheses. merge_points :",
"= Full_coeffs[:, E_hits[1:-2]] Symb_singularities = numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits] = (C2[0, :]*XE**2+C2[1,",
"energy, the real spectrum and the imaginary spectrum. \"\"\" logger.debug(\"Improve",
"scattering factor data values are set equal so as to",
"return output_data if __name__ == '__main__': #use argparse here to",
"------- This function returns a numpy array with columns consisting",
"[slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k in range(n+2,0,2): Integral +=",
"= kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14', input_data_type='NEXAFS') Output = kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3', input_data_type='NEXAFS', fix_distortions=True,",
"= numpy.vstack((new_points, new_points+1)).T.flatten() count += 1 #import matplotlib #matplotlib.use('WXAgg') #import",
": numpy vector of `float` The real part of the",
"1 #import matplotlib #matplotlib.use('WXAgg') #import pylab #pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b')",
"`float` Set of photon energies describing intervals for which each",
"numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if numpy.any(orders>=0): # N>=0, x^k terms for ni in",
"imaginary_spectrum, orders, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with \"Piecewise Polynomial\" algorithm",
"input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) #Output = kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05)",
"to ensure continuity of the merged data set. Returns -------",
"of integers The vector represents the polynomial indices corresponding to",
"orders, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with \"Piecewise Polynomial\" algorithm plus",
"return numpy.vstack((E_values,Re_values,Im_values)).T def kk_calculate_real(NearEdgeDataFile, ChemicalFormula, load_options=None, input_data_type=None, merge_points=None, add_background=False, fix_distortions=False,",
"of code for initial testing #Output = kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14', input_data_type='NEXAFS')",
"calc_relativistic_correction(Stoichiometry) ASF_E, ASF_Data = data.calculate_asf(Stoichiometry) ASF_Data3 = data.coeffs_to_linear(ASF_E, ASF_Data, 0.1)",
"photon energy, the real spectrum and the imaginary spectrum. \"\"\"",
"#evaluate error levels Im_error = abs((Im_values[new_points-1]+Im_values[new_points])/2. - Im_midpoints) Re_error =",
"error levels Im_error = abs((Im_values[new_points-1]+Im_values[new_points])/2. - Im_midpoints) Re_error = abs((Re_values[new_points-1]+Re_values[new_points])/2.",
"relativistic correction to the Kramers-Kronig transform. You can calculate the",
"coefficients: A_1, A_0, A_-1, A_-2, A_-3 relativistic_correction : float The",
"represents the polynomial indices corresponding to the columns of imaginary_spectrum",
"energies in Full_E Imaginary_Spectrum : two-dimensional `numpy.array` of `float` The",
"module implements the Kramers-Kronig transformation.\"\"\" import logging, sys logger =",
"new_points = numpy.vstack((new_points, new_points+1)).T.flatten() count += 1 #import matplotlib #matplotlib.use('WXAgg')",
"= numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) # all N, ln(x+E) and ln(x-E) terms and",
"Imaginary_Spectrum, relativistic_correction, tolerance, recursion=50): \"\"\"Calculate extra data points so that",
"for initial testing #Output = kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14', input_data_type='NEXAFS') Output =",
"respectively representing photon energy, the real spectrum and the imaginary",
"Im_values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values = Im_values Re_values = Real_Spectrum",
"loop temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points = numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0] new_points = numpy.vstack((new_points,",
"and then calculate the kramers-Kronig transform. Parameters ---------- NearEdgeDataFile :",
"algorithm\") X1 = Energy[0:-1] X2 = Energy[1:] E = numpy.tile(Eval_Energy,",
"plus the Biggs and Lighthill extended data. Parameters ---------- Eval_Energy",
"def KK_General_PP(Eval_Energy, Energy, imaginary_spectrum, orders, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with",
"(Symb_B-Symb_singularities) / (math.pi*Eval_Energy) + relativistic_correction logger.debug(\"Done!\") return KK_Re def improve_accuracy(Full_E,",
"using the `calc_relativistic_correction` function.) tolerance : float Level of error",
"`numpy.array` of `float` The array consists of columns of polynomial",
"ASF_Data, 0.1) ASF_Data2 = data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E = (Output[1:,0]+Output[0:-1,0])*0.5 #Test_E",
"= numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E = numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C = numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N =",
"C2 = Full_coeffs[:, E_hits[1:-2]] Symb_singularities = numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits] = (C2[0,",
"numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits] = (C2[0, :]*XE**2+C2[1, :]*XE+C2[2, :]+C2[3, :]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) #",
"Imaginary_Spectrum_Values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data = numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return output_data if",
"import logging, sys logger = logging.getLogger(__name__) if __name__ == '__main__':",
"= numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2 = KK_PP(Test_E, Output[:,0], Im, Relativistic_Correction) import matplotlib",
"return Integral / math.pi + relativistic_correction def KK_PP(Eval_Energy, Energy, imaginary_spectrum,",
": two-dimensional `numpy.array` of `float` The array consists of five",
"matplotlib #matplotlib.use('WXAgg') #import pylab #pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-')",
"not None: NearEdge_Data = data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf') Full_E, Imaginary_Spectrum = data.merge_spectra(NearEdge_Data,",
"Imaginary_Spectrum = data.merge_spectra(NearEdge_Data, Full_E, Imaginary_Spectrum, merge_points=merge_points, add_background=add_background, fix_distortions=fix_distortions) Real_Spectrum =",
"to be allowed. recursion : integer Number of times an",
"Output[:,0], Im, Relativistic_Correction) import matplotlib matplotlib.use('WXAgg') import pylab pylab.figure() pylab.plot(Output[:,0],Output[:,1],'xg-',Output[:,0],Output[:,2],'xb-')",
"that a linear interpolation is more accurate. Parameters ---------- Full_E",
"are set equal so as to ensure continuity of the",
"holding the relativistic corection to the Kramers-Kronig transform. \"\"\" correction",
":]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2, :]-Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3 = (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2,",
"energies describing points at which to evaluate the real spectrum",
"array with columns consisting of the photon energy, the real",
"= data.ParseChemicalFormula('GaAs') Relativistic_Correction = calc_relativistic_correction(Stoichiometry) ASF_E, ASF_Data = data.calculate_asf(Stoichiometry) ASF_Data3",
"an energy interval can be halved before giving up. Returns",
"returns a ``float`` holding the relativistic corection to the Kramers-Kronig",
"total_improved_points = 0 while count<recursion and numpy.sum(improved)>0: #get E_midpoints midpoints",
"see LICENSE.txt \"\"\"This module implements the Kramers-Kronig transformation.\"\"\" import logging,",
"at photon energies specified by Eval_Energy. \"\"\" logger = logging.getLogger(__name__)",
"the Kramers-Kronig transform. Parameters: ----------- stoichiometry : array of integer/float",
"# N<=-3, x^k terms for ni in numpy.where(orders<=-3)[0]: i =",
"E_hits = numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False]) Eval_hits = numpy.any(hits, axis=1) X1 =",
"(You can calculate the value using the `calc_relativistic_correction` function.) tolerance",
"Stoichiometry = data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction = calc_relativistic_correction(Stoichiometry) Full_E, Imaginary_Spectrum = data.calculate_asf(Stoichiometry)",
"= Imaginary_Spectrum[1:] count = 0 improved = 1 total_improved_points =",
"= (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1, :]*E+Full_coeffs[2, :]+Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B = numpy.sum(Symb_2",
"Im_values = numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values = numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values = numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare",
"photon energies describing points at which to evaluate the real",
"Energy[1:-1]==E[:,0:-1] E_hits = numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False]) Eval_hits = numpy.any(hits, axis=1) X1",
"consists of five columns of polynomial coefficients: A_1, A_0, A_-1,",
"numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E = (Output[1:,0]+Output[0:-1,0])*0.5 #Test_E = numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2 = KK_PP(Test_E,",
"command line arguments #process arguments and pass to a pythonic",
"new_points = numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0] new_points = numpy.vstack((new_points, new_points+1)).T.flatten() count +=",
"interval can be halved before giving up. Returns ------- This",
"# # Copyright (c) 2013 <NAME>, <NAME> # # The",
"(( Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1)) Symb_2 =",
"energy values (low, high) at which the near-edge and scattering",
"== '__main__': #use argparse here to get command line arguments",
"not None: output_data = improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction, curve_tolerance, curve_recursion) else: Imaginary_Spectrum_Values",
"Kramers-Kronig transform using general piecewise-polynomial algorithm\") # Need to build",
"the imaginary parts of the scattering factors. \"\"\" Stoichiometry =",
"total_improved_points += numpy.sum(improved) #insert new points and values Im_values =",
"improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction, curve_tolerance, curve_recursion) else: Imaginary_Spectrum_Values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data",
"code for initial testing #Output = kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14', input_data_type='NEXAFS') Output",
"This function returns the real part of the scattering factors",
"# This file is part of the Kramers-Kronig Calculator software",
"scattering factors evaluated at photon energies specified by Eval_Energy. \"\"\"",
"= ((-Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2,",
"N<=-3, x^k terms for ni in numpy.where(orders<=-3)[0]: i = [slice(None,None,None),slice(None,None,None),ni]",
"'__main__': #use argparse here to get command line arguments #process",
"#pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log') #pylab.show() logger.info(\"Improved data accuracy by",
"logger = logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using general piecewise-polynomial algorithm\")",
"data.coeffs_to_linear(ASF_E, ASF_Data, 0.1) ASF_Data2 = data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E = (Output[1:,0]+Output[0:-1,0])*0.5",
"for next loop temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0) new_points = numpy.where(numpy.insert(numpy.zeros(Im_values.shape, dtype=numpy.bool),new_points[improved],True))[0] new_points",
"Energy[E_hits[:-2]] C1 = Full_coeffs[:, E_hits[2:-1]] C2 = Full_coeffs[:, E_hits[1:-2]] Symb_singularities",
"numpy.sum(improved)>0: #get E_midpoints midpoints = (E_values[new_points-1]+E_values[new_points])/2. #evaluate at new points",
"Number of times an energy interval can be halved before",
"= data.calculate_asf(Stoichiometry) if NearEdgeDataFile is not None: NearEdge_Data = data.convert_data(data.load_data(NearEdgeDataFile,",
"= logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using (n from 1 to",
"Relativistic_Correction = calc_relativistic_correction(Stoichiometry) Full_E, Imaginary_Spectrum = data.calculate_asf(Stoichiometry) if NearEdgeDataFile is",
"array of integer/float pairs Each pair in the list consists",
"near-edge and scattering factor data values are set equal so",
"# -*- coding: utf-8 -*- # This file is part",
"data. Parameters ---------- Eval_Energy : numpy vector of `float` Set",
"utf-8 -*- # This file is part of the Kramers-Kronig",
"factors. \"\"\" Stoichiometry = data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction = calc_relativistic_correction(Stoichiometry) Full_E, Imaginary_Spectrum",
"Each pair in the list consists of an atomic number",
"which each row of `imaginary_spectrum` is valid Real_Spectrum : numpy",
"to evaluate the real spectrum Energy : numpy vector of",
": float Level of error in linear extrapolation of data",
"of `float` Set of photon energies describing intervals for which",
"and poles Integral = numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if numpy.any(orders<=-2): # N<=-2, ln(x)",
"fix_distortions=True, curve_tolerance=0.05) #Output = kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) Stoichiometry",
"# N>=0, x^k terms for ni in numpy.where(orders>=0)[0]: i =",
"of `float` The array consists of columns of polynomial coefficients",
"+= numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug(\"Done!\") return Integral / math.pi + relativistic_correction def",
"spectrum and the imaginary spectrum. \"\"\" logger.debug(\"Improve data accuracy\") new_points",
"an atomic number and the relative proportion of that element.",
"Kramers-Kronig transform. (You can calculate the value using the `calc_relativistic_correction`",
"<=-3): # N<=-3, x^k terms for ni in numpy.where(orders<=-3)[0]: i",
"kramers-Kronig transform. Parameters ---------- NearEdgeDataFile : string Path to file",
"numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values = Im_values Re_values =",
":]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1)) Symb_2 = ((-Full_coeffs[0, :]*E+Full_coeffs[1,",
"is more accurate. Parameters ---------- Full_E : numpy vector of",
"numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if numpy.any(orders<=-2): # N<=-2, ln(x) terms i = [slice(None,None,None),slice(None,None,None),orders<=-2]",
"load_options=None, input_data_type=None, merge_points=None, add_background=False, fix_distortions=False, curve_tolerance=None, curve_recursion=50): \"\"\"Do all data",
"the merged data set. Returns ------- This function returns a",
"and values Im_values = numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values = numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values =",
"Full_E : numpy vector of `float` Set of photon energies",
"points and values Im_values = numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values = numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values",
"arrays X = numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E = numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C = numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1))",
"XE = Energy[E_hits[1:-1]] X2 = Energy[E_hits[:-2]] C1 = Full_coeffs[:, E_hits[2:-1]]",
"= numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values = data.coeffs_to_ASF(Full_E, numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values = Im_values Re_values",
"A standard chemical formula string consisting of element symbols, numbers",
"returns a numpy array with columns consisting of the photon",
"section of code for initial testing #Output = kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14',",
"python # -*- coding: utf-8 -*- # This file is",
"photon energies describing intervals for which each row of `imaginary_spectrum`",
"`calc_relativistic_correction` function. Returns ------- This function returns the real part",
"#pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log') #pylab.show() logger.info(\"Improved data accuracy by inserting",
"coefficients belonging to the power terms indicated by 'order' orders",
"os import data def calc_relativistic_correction(stoichiometry): \"\"\"Calculate the relativistic correction to",
"numpy.any(orders>=0): # N>=0, x^k terms for ni in numpy.where(orders>=0)[0]: i",
"Full_E, Imaginary_Spectrum, relativistic_correction) #evaluate error levels Im_error = abs((Im_values[new_points-1]+Im_values[new_points])/2. -",
"transform using general piecewise-polynomial algorithm\") # Need to build x-E-n",
"range(n+2,0,2): Integral += numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug(\"Done!\") return Integral / math.pi +",
"= (E_values[new_points-1]+E_values[new_points])/2. #evaluate at new points Im_midpoints = data.coeffs_to_ASF(midpoints, temp_Im_spectrum)",
"2013 <NAME>, <NAME> # # The software is licensed under",
"logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout) import math import numpy import os import data",
"\"\"\" logger = logging.getLogger(__name__) logger.info(\"Calculate Kramers-Kronig transform using (n from",
"at photon energies in Full_E Imaginary_Spectrum : two-dimensional `numpy.array` of",
"levels Im_error = abs((Im_values[new_points-1]+Im_values[new_points])/2. - Im_midpoints) Re_error = abs((Re_values[new_points-1]+Re_values[new_points])/2. -",
"E = numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C = numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N = numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles",
"= kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) Stoichiometry = data.ParseChemicalFormula('LaAlO3') #Stoichiometry",
":]/E*(X2**-1-X1**-1)) Symb_2 = ((-Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0,",
"new_points+1)).T.flatten() count += 1 #import matplotlib #matplotlib.use('WXAgg') #import pylab #pylab.figure()",
"add_background=add_background, fix_distortions=fix_distortions) Real_Spectrum = KK_PP(Full_E, Full_E, Imaginary_Spectrum, Relativistic_Correction) if curve_tolerance",
"= data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E = (Output[1:,0]+Output[0:-1,0])*0.5 #Test_E = numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2",
"hits = Energy[1:-1]==E[:,0:-1] E_hits = numpy.append(numpy.insert(numpy.any(hits, axis=0),[0,0],False),[False,False]) Eval_hits = numpy.any(hits,",
"= Energy[1:] E = numpy.tile(Eval_Energy, (len(Energy)-1, 1)).T Full_coeffs = imaginary_spectrum.T",
"= Energy[E_hits[:-2]] C1 = Full_coeffs[:, E_hits[2:-1]] C2 = Full_coeffs[:, E_hits[1:-2]]",
"n = orders[ni] for k in range(n,0,-2): Integral += numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0)",
"element symbols, numbers and parentheses. merge_points : list or tuple",
"numpy.any(orders<=-2): # N<=-2, ln(x) terms i = [slice(None,None,None),slice(None,None,None),orders<=-2] Integral +=",
"equal so as to ensure continuity of the merged data",
"relativistic_correction logger.debug(\"Done!\") return KK_Re def improve_accuracy(Full_E, Real_Spectrum, Imaginary_Spectrum, relativistic_correction, tolerance,",
"#process arguments and pass to a pythonic function #I will",
"(math.pi*Eval_Energy) + relativistic_correction logger.debug(\"Done!\") return KK_Re def improve_accuracy(Full_E, Real_Spectrum, Imaginary_Spectrum,",
"in the list consists of an atomic number and the",
"= KK_PP(Test_E, Output[:,0], Im, Relativistic_Correction) import matplotlib matplotlib.use('WXAgg') import pylab",
"of an atomic number and the relative proportion of that",
"by 'order' orders : numpy vector of integers The vector",
"<NAME>, <NAME> # # The software is licensed under the",
"pair in the list consists of an atomic number and",
"in stoichiometry: correction += (z - (z/82.5)**2.37) * n return",
"#Output = kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) Stoichiometry = data.ParseChemicalFormula('LaAlO3')",
"the columns of imaginary_spectrum relativistic_correction : float The relativistic correction",
":]+C2[3, :]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) # Finish things off KK_Re = (Symb_B-Symb_singularities)",
"Re_midpoints = KK_PP(midpoints, Full_E, Imaginary_Spectrum, relativistic_correction) #evaluate error levels Im_error",
"photon energies in Full_E Imaginary_Spectrum : two-dimensional `numpy.array` of `float`",
"tuple pair of `float` values, or None The photon energy",
"function returns a numpy array with three columns respectively representing",
"- Re_midpoints) improved = (Im_error>tolerance) | (Re_error>tolerance) logger.debug(str(numpy.sum(improved))+\" points (out",
"= numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits] = (C2[0, :]*XE**2+C2[1, :]*XE+C2[2, :]+C2[3, :]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE)))",
"merge_points=merge_points, add_background=add_background, fix_distortions=fix_distortions) Real_Spectrum = KK_PP(Full_E, Full_E, Imaginary_Spectrum, Relativistic_Correction) if",
"load_options),FromType=input_data_type,ToType='asf') Full_E, Imaginary_Spectrum = data.merge_spectra(NearEdge_Data, Full_E, Imaginary_Spectrum, merge_points=merge_points, add_background=add_background, fix_distortions=fix_distortions)",
"+= numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if numpy.any(orders <=-3): # N<=-3, x^k terms for",
"vector represents the polynomial indices corresponding to the columns of",
"The vector represents the polynomial indices corresponding to the columns",
"Imaginary_Spectrum, merge_points=merge_points, add_background=add_background, fix_distortions=fix_distortions) Real_Spectrum = KK_PP(Full_E, Full_E, Imaginary_Spectrum, Relativistic_Correction)",
"as to ensure continuity of the merged data set. Returns",
"= (( Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1)) Symb_2",
"NearEdgeDataFile is not None: NearEdge_Data = data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf') Full_E, Imaginary_Spectrum",
"Polynomial\" algorithm plus the Biggs and Lighthill extended data. Parameters",
"x-E-n arrays X = numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders))) E = numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy)-1,1,len(orders))) C =",
"range(n,0,-2): Integral += numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if numpy.any(orders <=-3): # N<=-3, x^k",
"/ math.pi + relativistic_correction def KK_PP(Eval_Energy, Energy, imaginary_spectrum, relativistic_correction): \"\"\"Calculate",
"= KK_PP(Full_E, Full_E, Imaginary_Spectrum, Relativistic_Correction) if curve_tolerance is not None:",
"\"\"\"This module implements the Kramers-Kronig transformation.\"\"\" import logging, sys logger",
"proportion of that element. Returns ------- This function returns a",
"- Symb_3, axis=1) # Sum areas for approximate integral #",
"corresponding to magnitudes at photon energies in Full_E Imaginary_Spectrum :",
"= KK_PP(midpoints, Full_E, Imaginary_Spectrum, relativistic_correction) #evaluate error levels Im_error =",
"of polynomial coefficients: A_1, A_0, A_-1, A_-2, A_-3 relativistic_correction :",
"the relativistic correction to the Kramers-Kronig transform. Parameters: ----------- stoichiometry",
"set. Returns ------- This function returns a numpy array with",
"evaluated at photon energies specified by Eval_Energy. \"\"\" logger =",
"= data.calculate_asf(Stoichiometry) ASF_Data3 = data.coeffs_to_linear(ASF_E, ASF_Data, 0.1) ASF_Data2 = data.coeffs_to_ASF(ASF_E,",
"= 1 total_improved_points = 0 while count<recursion and numpy.sum(improved)>0: #get",
"curve_tolerance=0.05) #Output = kk_calculate_real('../../data/GaAs/As.xmu.csv', 'GaAs', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) Stoichiometry =",
"abs((Re_values[new_points-1]+Re_values[new_points])/2. - Re_midpoints) improved = (Im_error>tolerance) | (Re_error>tolerance) logger.debug(str(numpy.sum(improved))+\" points",
"factor data values are set equal so as to ensure",
"def kk_calculate_real(NearEdgeDataFile, ChemicalFormula, load_options=None, input_data_type=None, merge_points=None, add_background=False, fix_distortions=False, curve_tolerance=None, curve_recursion=50):",
"using general piecewise-polynomial algorithm\") # Need to build x-E-n arrays",
"factors evaluated at photon energies specified by Eval_Energy. \"\"\" logger",
"for k in range(n,0,-2): Integral += numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if numpy.any(orders <=-3):",
"# Copyright (c) 2013 <NAME>, <NAME> # # The software",
"i = [slice(None,None,None),slice(None,None,None),orders<=-2] Integral += numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if numpy.any(orders>=0): # N>=0,",
"data loading and processing and then calculate the kramers-Kronig transform.",
": string Path to file containg near-edge data ChemicalFormula :",
"Symb_B = numpy.sum(Symb_2 - Symb_1 - Symb_3, axis=1) # Sum",
"continuity of the merged data set. Returns ------- This function",
"- Im_midpoints) Re_error = abs((Re_values[new_points-1]+Re_values[new_points])/2. - Re_midpoints) improved = (Im_error>tolerance)",
"can calculate the value using the `calc_relativistic_correction` function.) tolerance :",
"output_data if __name__ == '__main__': #use argparse here to get",
"(Im_error>tolerance) | (Re_error>tolerance) logger.debug(str(numpy.sum(improved))+\" points (out of \"+str(len(improved))+\") can be",
":]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2, :]-Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3 = (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0, :]*E**2+Full_coeffs[1,",
"parts of the scattering factors. \"\"\" Stoichiometry = data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction",
"spectrum corresponding to magnitudes at photon energies in Full_E Imaginary_Spectrum",
"logging.StreamHandler(stream=sys.stdout) import math import numpy import os import data def",
"data.coeffs_to_ASF(midpoints, temp_Im_spectrum) Re_midpoints = KK_PP(midpoints, Full_E, Imaginary_Spectrum, relativistic_correction) #evaluate error",
"points.\") return numpy.vstack((E_values,Re_values,Im_values)).T def kk_calculate_real(NearEdgeDataFile, ChemicalFormula, load_options=None, input_data_type=None, merge_points=None, add_background=False,",
"kk_calculate_real(NearEdgeDataFile, ChemicalFormula, load_options=None, input_data_type=None, merge_points=None, add_background=False, fix_distortions=False, curve_tolerance=None, curve_recursion=50): \"\"\"Do",
"return KK_Re def improve_accuracy(Full_E, Real_Spectrum, Imaginary_Spectrum, relativistic_correction, tolerance, recursion=50): \"\"\"Calculate",
"algorithm plus the Biggs and Lighthill extended data. Parameters ----------",
"terms for ni in numpy.where(orders<=-3)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n =",
":])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)-(Full_coeffs[3, :]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1)) Symb_2 = ((-Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0,",
"new points Im_midpoints = data.coeffs_to_ASF(midpoints, temp_Im_spectrum) Re_midpoints = KK_PP(midpoints, Full_E,",
"ASF_Data2 = data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E = (Output[1:,0]+Output[0:-1,0])*0.5 #Test_E = numpy.linspace(41257.87,41259.87,num=21)",
"calculate the value using the `calc_relativistic_correction` function. Returns ------- This",
"columns of imaginary_spectrum relativistic_correction : float The relativistic correction to",
"Symb_1 - Symb_3, axis=1) # Sum areas for approximate integral",
"all N, ln(x+E) and ln(x-E) terms and poles Integral =",
"import matplotlib matplotlib.use('WXAgg') import pylab pylab.figure() pylab.plot(Output[:,0],Output[:,1],'xg-',Output[:,0],Output[:,2],'xb-') pylab.plot(ASF_E,ASF_Data2,'+r') #pylab.plot(ASF_E,ASF_Data22,'xr') pylab.plot(ASF_Data3[0],ASF_Data3[1],'r-')",
"and pass to a pythonic function #I will abuse this",
"each row of `imaginary_spectrum` is valid imaginary_spectrum : two-dimensional `numpy.array`",
"while count<recursion and numpy.sum(improved)>0: #get E_midpoints midpoints = (E_values[new_points-1]+E_values[new_points])/2. #evaluate",
"returns the real part of the scattering factors evaluated at",
"dtype=numpy.bool),new_points[improved],True))[0] new_points = numpy.vstack((new_points, new_points+1)).T.flatten() count += 1 #import matplotlib",
"#pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log')",
"------- This function returns a numpy array with three columns",
"data.merge_spectra(NearEdge_Data, Full_E, Imaginary_Spectrum, merge_points=merge_points, add_background=add_background, fix_distortions=fix_distortions) Real_Spectrum = KK_PP(Full_E, Full_E,",
"of `imaginary_spectrum` is valid imaginary_spectrum : two-dimensional `numpy.array` of `float`",
"#Stoichiometry = data.ParseChemicalFormula('GaAs') Relativistic_Correction = calc_relativistic_correction(Stoichiometry) ASF_E, ASF_Data = data.calculate_asf(Stoichiometry)",
"logger.info(\"Calculate Kramers-Kronig transform using (n from 1 to -3) piecewise-polynomial",
":])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2, :]-Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E)))",
"logger.debug(\"Done!\") return Integral / math.pi + relativistic_correction def KK_PP(Eval_Energy, Energy,",
"photon energy, the real and the imaginary parts of the",
"if NearEdgeDataFile is not None: NearEdge_Data = data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf') Full_E,",
"or None The photon energy values (low, high) at which",
"KK_PP(Full_E, Full_E, Imaginary_Spectrum, Relativistic_Correction) if curve_tolerance is not None: output_data",
"accurate. Parameters ---------- Full_E : numpy vector of `float` Set",
"Kramers-Kronig transform. Parameters: ----------- stoichiometry : array of integer/float pairs",
"the kramers-Kronig transform. Parameters ---------- NearEdgeDataFile : string Path to",
"transform. (You can calculate the value using the `calc_relativistic_correction` function.)",
"improved in pass number \"+str(count+1)+\".\") total_improved_points += numpy.sum(improved) #insert new",
"new points and values Im_values = numpy.insert(Im_values,new_points[improved],Im_midpoints[improved]) Re_values = numpy.insert(Re_values,new_points[improved],Re_midpoints[improved])",
"KK_General_PP(Eval_Energy, Energy, imaginary_spectrum, orders, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with \"Piecewise",
"formula string consisting of element symbols, numbers and parentheses. merge_points",
"stoichiometry : array of integer/float pairs Each pair in the",
"float The relativistic correction to the Kramers-Kronig transform. (You can",
"__name__ == '__main__': #use argparse here to get command line",
"\"\"\"Calculate the relativistic correction to the Kramers-Kronig transform. Parameters: -----------",
"Symb_2 = ((-Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1,",
"---------- Full_E : numpy vector of `float` Set of photon",
"#pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log') #pylab.show() logger.info(\"Improved data",
"extra data points so that a linear interpolation is more",
"is licensed under the terms of the zlib/libpng license. #",
"'C10SH14', input_data_type='NEXAFS') Output = kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv', 'LaAlO3', input_data_type='NEXAFS', fix_distortions=True, curve_tolerance=0.05) #Output",
"extended data. Parameters ---------- Eval_Energy : numpy vector of `float`",
"points at which to evaluate the real spectrum Energy :",
"columns of polynomial coefficients: A_1, A_0, A_-1, A_-2, A_-3 relativistic_correction",
":]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) # Finish things off KK_Re = (Symb_B-Symb_singularities) /",
"calc_relativistic_correction(Stoichiometry) Full_E, Imaginary_Spectrum = data.calculate_asf(Stoichiometry) if NearEdgeDataFile is not None:",
"numpy.linspace(41257.87,41259.87,num=21) #Real_Spectrum2 = KK_PP(Test_E, Output[:,0], Im, Relativistic_Correction) import matplotlib matplotlib.use('WXAgg')",
"to the Kramers-Kronig transform. \"\"\" correction = 0 for z,",
"Energy[0:-1] X2 = Energy[1:] E = numpy.tile(Eval_Energy, (len(Energy)-1, 1)).T Full_coeffs",
"numpy.tile(imaginary_spectrum[:,numpy.newaxis,:],(1,len(Eval_Energy),1)) N = numpy.tile(orders[numpy.newaxis,numpy.newaxis,:],(len(Energy)-1,len(Eval_Energy),1)) poles = numpy.equal(X,numpy.tile(Eval_Energy[numpy.newaxis,:,numpy.newaxis],(len(Energy),1,len(orders)))) # all N,",
"algorithm\") # Need to build x-E-n arrays X = numpy.tile(Energy[:,numpy.newaxis,numpy.newaxis],(1,len(Eval_Energy),len(orders)))",
"function returns a ``float`` holding the relativistic corection to the",
"The real part of the spectrum corresponding to magnitudes at",
"imaginary parts of the scattering factors. \"\"\" Stoichiometry = data.ParseChemicalFormula(ChemicalFormula)",
"Full_coeffs[:, E_hits[2:-1]] C2 = Full_coeffs[:, E_hits[1:-2]] Symb_singularities = numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits]",
"---------- NearEdgeDataFile : string Path to file containg near-edge data",
"numpy vector of integers The vector represents the polynomial indices",
"LICENSE.txt \"\"\"This module implements the Kramers-Kronig transformation.\"\"\" import logging, sys",
"and scattering factor data values are set equal so as",
"x^k terms for ni in numpy.where(orders<=-3)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n",
"fix_distortions=False, curve_tolerance=None, curve_recursion=50): \"\"\"Do all data loading and processing and",
"ensure continuity of the merged data set. Returns ------- This",
"numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) output_data = numpy.vstack((Full_E,Real_Spectrum,Imaginary_Spectrum_Values)).T return output_data if __name__ == '__main__':",
"# N<=-2, ln(x) terms i = [slice(None,None,None),slice(None,None,None),orders<=-2] Integral += numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2))",
"numpy.insert(Re_values,new_points[improved],Re_midpoints[improved]) E_values = numpy.insert(E_values,new_points[improved],midpoints[improved]) #prepare for next loop temp_Im_spectrum =numpy.repeat(temp_Im_spectrum[improved],2,axis=0)",
"part of the scattering factors evaluated at photon energies specified",
"Relativistic_Correction) import matplotlib matplotlib.use('WXAgg') import pylab pylab.figure() pylab.plot(Output[:,0],Output[:,1],'xg-',Output[:,0],Output[:,2],'xb-') pylab.plot(ASF_E,ASF_Data2,'+r') #pylab.plot(ASF_E,ASF_Data22,'xr')",
"The relativistic correction to the Kramers-Kronig transform. You can calculate",
"which to evaluate the real spectrum Energy : numpy vector",
"+= (z - (z/82.5)**2.37) * n return correction def KK_General_PP(Eval_Energy,",
"of element symbols, numbers and parentheses. merge_points : list or",
"returns a numpy array with three columns respectively representing photon",
"float The relativistic correction to the Kramers-Kronig transform. You can",
"orders[ni] for k in range(n+2,0,2): Integral += numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug(\"Done!\") return",
"string A standard chemical formula string consisting of element symbols,",
"relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with \"Piecewise Polynomial\" algorithm plus the",
"at new points Im_midpoints = data.coeffs_to_ASF(midpoints, temp_Im_spectrum) Re_midpoints = KK_PP(midpoints,",
"data values are set equal so as to ensure continuity",
"values are set equal so as to ensure continuity of",
"numpy.any(orders <=-3): # N<=-3, x^k terms for ni in numpy.where(orders<=-3)[0]:",
"recursion=50): \"\"\"Calculate extra data points so that a linear interpolation",
"the value using the `calc_relativistic_correction` function.) tolerance : float Level",
"for approximate integral # Patch singularities hits = Energy[1:-1]==E[:,0:-1] E_hits",
"of integer/float pairs Each pair in the list consists of",
"of error in linear extrapolation of data values to be",
"ChemicalFormula : string A standard chemical formula string consisting of",
"initial testing #Output = kk_calculate_real('../../data/Xy_norm_bgsub.txt', 'C10SH14', input_data_type='NEXAFS') Output = kk_calculate_real('../../data/LaAlO3/LaAlO3_Exp.csv',",
"None: output_data = improve_accuracy(Full_E,Real_Spectrum,Imaginary_Spectrum, Relativistic_Correction, curve_tolerance, curve_recursion) else: Imaginary_Spectrum_Values =",
"the relative proportion of that element. Returns ------- This function",
"pass to a pythonic function #I will abuse this section",
"at which to evaluate the real spectrum Energy : numpy",
"valid imaginary_spectrum : two-dimensional `numpy.array` of `float` The array consists",
"fix_distortions=True, curve_tolerance=0.05) Stoichiometry = data.ParseChemicalFormula('LaAlO3') #Stoichiometry = data.ParseChemicalFormula('GaAs') Relativistic_Correction =",
"C1 = Full_coeffs[:, E_hits[2:-1]] C2 = Full_coeffs[:, E_hits[1:-2]] Symb_singularities =",
"values, or None The photon energy values (low, high) at",
":]/E+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1)) Symb_2 = ((-Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4,",
"accuracy by inserting \"+str(total_improved_points)+\" extra points.\") return numpy.vstack((E_values,Re_values,Im_values)).T def kk_calculate_real(NearEdgeDataFile,",
"intervals for which each row of `imaginary_spectrum` is valid imaginary_spectrum",
"inserting \"+str(total_improved_points)+\" extra points.\") return numpy.vstack((E_values,Re_values,Im_values)).T def kk_calculate_real(NearEdgeDataFile, ChemicalFormula, load_options=None,",
"orders[ni] for k in range(n,0,-2): Integral += numpy.sum(C[i]/float(-k)*2*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) if numpy.any(orders",
"Full_E Imaginary_Spectrum : two-dimensional `numpy.array` of `float` The array consists",
"symbols, numbers and parentheses. merge_points : list or tuple pair",
"= data.coeffs_to_linear(ASF_E, ASF_Data, 0.1) ASF_Data2 = data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E =",
"= 0 improved = 1 total_improved_points = 0 while count<recursion",
"consisting of element symbols, numbers and parentheses. merge_points : list",
"pair of `float` values, or None The photon energy values",
"'__main__': logging.basicConfig(level=logging.DEBUG) logging.StreamHandler(stream=sys.stdout) import math import numpy import os import",
"data.calculate_asf(Stoichiometry) ASF_Data3 = data.coeffs_to_linear(ASF_E, ASF_Data, 0.1) ASF_Data2 = data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1])))",
"# The software is licensed under the terms of the",
"row of `imaginary_spectrum` is valid Real_Spectrum : numpy vector of",
"Kramers-Kronig Calculator software package. # # Copyright (c) 2013 <NAME>,",
"The array consists of five columns of polynomial coefficients: A_1,",
"#pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r') #pylab.plot(E_values,Im_values,'b-') #pylab.plot(E_values,Re_values,'r-') #pylab.plot(midpoints,Im_error,'b-') #pylab.plot(midpoints,Re_error,'r-') #pylab.xscale('log') #pylab.show() logger.info(\"Improved",
"Returns ------- This function returns a ``float`` holding the relativistic",
"----------- stoichiometry : array of integer/float pairs Each pair in",
"= data.convert_data(data.load_data(NearEdgeDataFile, load_options),FromType=input_data_type,ToType='asf') Full_E, Imaginary_Spectrum = data.merge_spectra(NearEdge_Data, Full_E, Imaginary_Spectrum, merge_points=merge_points,",
"Kramers-Kronig transform. \"\"\" correction = 0 for z, n in",
"of the merged data set. Returns ------- This function returns",
"data.ParseChemicalFormula('LaAlO3') #Stoichiometry = data.ParseChemicalFormula('GaAs') Relativistic_Correction = calc_relativistic_correction(Stoichiometry) ASF_E, ASF_Data =",
"the real part of the scattering factors evaluated at photon",
"(c) 2013 <NAME>, <NAME> # # The software is licensed",
"list consists of an atomic number and the relative proportion",
"to the power terms indicated by 'order' orders : numpy",
"the Kramers-Kronig transform. \"\"\" correction = 0 for z, n",
"# Sum areas for approximate integral # Patch singularities hits",
"-*- coding: utf-8 -*- # This file is part of",
"Imaginary_Spectrum : two-dimensional `numpy.array` of `float` The array consists of",
"matplotlib.use('WXAgg') import pylab pylab.figure() pylab.plot(Output[:,0],Output[:,1],'xg-',Output[:,0],Output[:,2],'xb-') pylab.plot(ASF_E,ASF_Data2,'+r') #pylab.plot(ASF_E,ASF_Data22,'xr') pylab.plot(ASF_Data3[0],ASF_Data3[1],'r-') #pylab.plot(Test_E,Real_Spectrum2,'*y') pylab.xscale('log')",
"imaginary_spectrum, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with \"Piecewise Polynomial\" algorithm plus",
"= numpy.sum(Symb_2 - Symb_1 - Symb_3, axis=1) # Sum areas",
"\"\"\"Do all data loading and processing and then calculate the",
"Im_midpoints = data.coeffs_to_ASF(midpoints, temp_Im_spectrum) Re_midpoints = KK_PP(midpoints, Full_E, Imaginary_Spectrum, relativistic_correction)",
"fix_distortions=fix_distortions) Real_Spectrum = KK_PP(Full_E, Full_E, Imaginary_Spectrum, Relativistic_Correction) if curve_tolerance is",
":]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4, :]/E*(X2**-1-X1**-1))+(Full_coeffs[0, :]*E**2-Full_coeffs[1, :]*E+Full_coeffs[2, :]-Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2+E)/(X1+E))) Symb_3 = (1-1*((X2==E)|(X1==E)))*(Full_coeffs[0,",
"<NAME> # # The software is licensed under the terms",
"the `calc_relativistic_correction` function.) tolerance : float Level of error in",
":]*E+Full_coeffs[2, :]+Full_coeffs[3, :]*E**-1+Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute((X2-E+1*(X2==E))/(X1-E+1*(X1==E)))) Symb_B = numpy.sum(Symb_2 - Symb_1 -",
"line arguments #process arguments and pass to a pythonic function",
"= Real_Spectrum E_values = Full_E temp_Im_spectrum = Imaginary_Spectrum[1:] count =",
"real and the imaginary parts of the scattering factors. \"\"\"",
":]*E**-2)*numpy.log(numpy.absolute(X2/X1))+Full_coeffs[4, :]/E*(X2**-1-X1**-1)) Symb_2 = ((-Full_coeffs[0, :]*E+Full_coeffs[1, :])*(X2-X1)+0.5*Full_coeffs[0, :]*(X2**2-X1**2)+(Full_coeffs[3, :]/E-Full_coeffs[4, :]*E**-2)*numpy.log(numpy.absolute(X2/X1))-Full_coeffs[4,",
"in numpy.where(orders>=0)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni] for k",
"then calculate the kramers-Kronig transform. Parameters ---------- NearEdgeDataFile : string",
"of polynomial coefficients belonging to the power terms indicated by",
"= Energy[0:-1] X2 = Energy[1:] E = numpy.tile(Eval_Energy, (len(Energy)-1, 1)).T",
"scattering factors. \"\"\" Stoichiometry = data.ParseChemicalFormula(ChemicalFormula) Relativistic_Correction = calc_relativistic_correction(Stoichiometry) Full_E,",
"of the Kramers-Kronig Calculator software package. # # Copyright (c)",
"import math import numpy import os import data def calc_relativistic_correction(stoichiometry):",
"= orders[ni] for k in range(n+2,0,2): Integral += numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug(\"Done!\")",
"#evaluate at new points Im_midpoints = data.coeffs_to_ASF(midpoints, temp_Im_spectrum) Re_midpoints =",
"Eval_hits = numpy.any(hits, axis=1) X1 = Energy[E_hits[2:]] XE = Energy[E_hits[1:-1]]",
"be halved before giving up. Returns ------- This function returns",
"KK_PP(Eval_Energy, Energy, imaginary_spectrum, relativistic_correction): \"\"\"Calculate Kramers-Kronig transform with \"Piecewise Polynomial\"",
"the Biggs and Lighthill extended data. Parameters ---------- Eval_Energy :",
"= numpy.tile(Eval_Energy, (len(Energy)-1, 1)).T Full_coeffs = imaginary_spectrum.T Symb_1 = ((",
"0.1) ASF_Data2 = data.coeffs_to_ASF(ASF_E, numpy.vstack((ASF_Data,ASF_Data[-1]))) #Test_E = (Output[1:,0]+Output[0:-1,0])*0.5 #Test_E =",
"off KK_Re = (Symb_B-Symb_singularities) / (math.pi*Eval_Energy) + relativistic_correction logger.debug(\"Done!\") return",
"= [slice(None,None,None),slice(None,None,None),orders<=-2] Integral += numpy.sum(C[i]*((-E[i])**N[i]+E[i]**N[i])*numpy.log(numpy.absolute((X[1:,:,orders<=-2])/(X[:-1,:,orders<=-2]))),axis=(0,2)) if numpy.any(orders>=0): # N>=0, x^k",
"------- This function returns a ``float`` holding the relativistic corection",
"vector of `float` Set of photon energies describing points at",
"KK_Re = (Symb_B-Symb_singularities) / (math.pi*Eval_Energy) + relativistic_correction logger.debug(\"Done!\") return KK_Re",
"so that a linear interpolation is more accurate. Parameters ----------",
"Kramers-Kronig transformation.\"\"\" import logging, sys logger = logging.getLogger(__name__) if __name__",
"for ni in numpy.where(orders>=0)[0]: i = [slice(None,None,None),slice(None,None,None),ni] n = orders[ni]",
"photon energies specified by Eval_Energy. \"\"\" logger = logging.getLogger(__name__) logger.info(\"Calculate",
"ln(x+E) and ln(x-E) terms and poles Integral = numpy.sum(-C*(-E)**N*numpy.log(numpy.absolute((X[1:,:,:]+E)/(X[:-1,:,:]+E)))-C*E**N*(1-poles[1:,:,:])*numpy.log(numpy.absolute((X[1:,:,:]-E+poles[1:,:,:])/((1-poles[:-1,:,:])*X[:-1,:,:]+poles[:-1,:,:]*X[[0]+list(range(len(Energy)-2)),:,:]-E))),axis=(0,2)) if",
"#import matplotlib #matplotlib.use('WXAgg') #import pylab #pylab.figure() #pylab.plot(Full_E,plot_Im_values,'ok') #pylab.plot(Full_E,Real_Spectrum,'og') #pylab.plot(midpoints,Im_midpoints,'+b') #pylab.plot(midpoints,Re_midpoints,'+r')",
"before giving up. Returns ------- This function returns a numpy",
"Full_coeffs[:, E_hits[1:-2]] Symb_singularities = numpy.zeros(len(Eval_Energy)) Symb_singularities[Eval_hits] = (C2[0, :]*XE**2+C2[1, :]*XE+C2[2,",
"k in range(n+2,0,2): Integral += numpy.sum(C[i]/float(k)*((-1)**(n-k)+1)*E[i]**(n-k)*(X[1:,:,ni]**k-X[:-1,:,ni]**k),axis=0) logger.debug(\"Done!\") return Integral /",
":]*XE+C2[2, :]+C2[3, :]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) # Finish things off KK_Re =",
":]*XE**2+C2[1, :]*XE+C2[2, :]+C2[3, :]*XE**-1+C2[4, :]*XE**-2)*numpy.log(numpy.absolute((X2-XE)/(X1-XE))) # Finish things off KK_Re",
"spectrum Energy : numpy vector of `float` Set of photon",
"the terms of the zlib/libpng license. # For details see",
"zlib/libpng license. # For details see LICENSE.txt \"\"\"This module implements",
"part of the spectrum corresponding to magnitudes at photon energies",
"imaginary spectrum. \"\"\" logger.debug(\"Improve data accuracy\") new_points = numpy.cumsum(numpy.ones((len(Full_E)-2,1),dtype=numpy.int8))+1 Im_values",
"consisting of the photon energy, the real and the imaginary",
"numpy.vstack((Imaginary_Spectrum,Imaginary_Spectrum[-1]))) #plot_Im_values = Im_values Re_values = Real_Spectrum E_values = Full_E"
] |
[
"== 8 else 0, # 1 if a.index(i) & 16",
"else 0, # 1 if a.index(i) & 2 == 2",
"0, # )) # sys.exit(0) WHITE=(255,255,255) PINK=(217,154,197) BLUE=(103,170,249) BLACK=(0,0,0) img",
"PIL import ImageDraw, Image from math import cos,sin,radians from random",
"8 else PINK) id.polygon(hex((ox+s*2,oy),s), fill=BLUE if c & 16 ==",
"1 if a.index(i) & 2 == 2 else 0, #",
"ImageDraw.Draw(img) def hex(offset, size): points = [] x,y = offset",
"== 32 else PINK) id.polygon(hex((ox+s,oy+s*2),s), fill=BLUE if c & 64",
"& 8 == 8 else 0, # 1 if a.index(i)",
"id.polygon(hex((ox-s,oy+s*2),s), fill=BLUE if c & 32 == 32 else PINK)",
"from math import cos,sin,radians from random import randint import sys",
"64 else 0, # )) # sys.exit(0) WHITE=(255,255,255) PINK=(217,154,197) BLUE=(103,170,249)",
"0, # 1 if a.index(i) & 32 == 32 else",
"size): points = [] x,y = offset for angle in",
"= [] x,y = offset for angle in range(0, 360,",
"Y z Z\" if len(a) > 128: print(\"TOO MANY CHARACTERS\")",
"id = ImageDraw.Draw(img) def hex(offset, size): points = [] x,y",
"= offset for angle in range(0, 360, 60): x +=",
"else 0, # 1 if a.index(i) & 32 == 32",
"= sy - sin(radians(120)) * s id.polygon(hex((ox-s,oy-s*2),s), fill=BLUE if c",
"PINK) id.polygon(hex((ox+s*2,oy),s), fill=BLUE if c & 16 == 16 else",
"sin(radians(120)) * s id.polygon(hex((ox-s,oy-s*2),s), fill=BLUE if c & 1 ==",
"> 128: print(\"TOO MANY CHARACTERS\") sys.exit(1) # for i in",
"c & 1 == 1 else PINK) id.polygon(hex((ox+s,oy-s*2),s), fill=BLUE if",
"# for i in a: # print(\"%s -> %d %d",
"%d %d %d %d \"%(i, # 1 if a.index(i) &",
"4 == 4 else 0, # 1 if a.index(i) &",
"# )) # sys.exit(0) WHITE=(255,255,255) PINK=(217,154,197) BLUE=(103,170,249) BLACK=(0,0,0) img =",
"range(0, 360, 60): x += cos(radians(angle)) * size y +=",
"randint import sys a = \"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W x X",
"%d \"%(i, # 1 if a.index(i) & 1 == 1",
"ox = sx - cos(radians(120)) * s oy = sy",
"64 else PINK) q = \"\"\"This is a test 0123456789%\"\"\"",
"= \"\"\"This is a test 0123456789%\"\"\" s = 10 cutOff",
"s id.polygon(hex((ox-s,oy-s*2),s), fill=BLUE if c & 1 == 1 else",
"& 1 == 1 else PINK) id.polygon(hex((ox+s,oy-s*2),s), fill=BLUE if c",
"& 8 == 8 else PINK) id.polygon(hex((ox+s*2,oy),s), fill=BLUE if c",
"a test 0123456789%\"\"\" s = 10 cutOff = int(2560/(s*7)) print",
"from PIL import ImageDraw, Image from math import cos,sin,radians from",
"a.index(i) & 32 == 32 else 0, # 1 if",
"y += sin(radians(angle)) * size points.append((x, y)) return points def",
"+ x*s*7, s*3 + y*s*7, s, a.index(c)) x+=1 if x",
"4 else PINK) id.polygon(hex((ox,oy),s), fill=BLUE if c & 8 ==",
"def drawHex(id, sx,sy,s,c): ox = sx - cos(radians(120)) * s",
"img = Image.new('RGB', (2560,1600), BLACK) id = ImageDraw.Draw(img) def hex(offset,",
"= int(2560/(s*7)) print (cutOff) x,y = 0,0 for c in",
"1 else 0, # 1 if a.index(i) & 2 ==",
"def hex(offset, size): points = [] x,y = offset for",
"10 cutOff = int(2560/(s*7)) print (cutOff) x,y = 0,0 for",
"# sys.exit(0) WHITE=(255,255,255) PINK=(217,154,197) BLUE=(103,170,249) BLACK=(0,0,0) img = Image.new('RGB', (2560,1600),",
"CHARACTERS\") sys.exit(1) # for i in a: # print(\"%s ->",
"8 == 8 else 0, # 1 if a.index(i) &",
"hex(offset, size): points = [] x,y = offset for angle",
"points def drawHex(id, sx,sy,s,c): ox = sx - cos(radians(120)) *",
"sx - cos(radians(120)) * s oy = sy - sin(radians(120))",
"int(2560/(s*7)) print (cutOff) x,y = 0,0 for c in q:",
"(cutOff) x,y = 0,0 for c in q: drawHex(id, s*2",
"* size points.append((x, y)) return points def drawHex(id, sx,sy,s,c): ox",
"sys.exit(1) # for i in a: # print(\"%s -> %d",
"PINK) id.polygon(hex((ox+s,oy+s*2),s), fill=BLUE if c & 64 == 64 else",
"if a.index(i) & 1 == 1 else 0, # 1",
"# 1 if a.index(i) & 4 == 4 else 0,",
"& 2 == 2 else PINK) id.polygon(hex((ox-s*2,oy),s), fill=BLUE if c",
"a.index(i) & 16 == 16 else 0, # 1 if",
"y Y z Z\" if len(a) > 128: print(\"TOO MANY",
"BLACK=(0,0,0) img = Image.new('RGB', (2560,1600), BLACK) id = ImageDraw.Draw(img) def",
"- sin(radians(120)) * s id.polygon(hex((ox-s,oy-s*2),s), fill=BLUE if c & 1",
"8 else 0, # 1 if a.index(i) & 16 ==",
"== 4 else PINK) id.polygon(hex((ox,oy),s), fill=BLUE if c & 8",
"1 if a.index(i) & 32 == 32 else 0, #",
"+ y*s*7, s, a.index(c)) x+=1 if x >= cutOff or",
"x X y Y z Z\" if len(a) > 128:",
"\"\"\"This is a test 0123456789%\"\"\" s = 10 cutOff =",
"# 1 if a.index(i) & 32 == 32 else 0,",
"else PINK) id.polygon(hex((ox,oy),s), fill=BLUE if c & 8 == 8",
"%d %d \"%(i, # 1 if a.index(i) & 1 ==",
"& 64 == 64 else PINK) q = \"\"\"This is",
"# print(\"%s -> %d %d %d %d %d %d %d",
"== 2 else 0, # 1 if a.index(i) & 4",
"= 0,0 for c in q: drawHex(id, s*2 + x*s*7,",
"y*s*7, s, a.index(c)) x+=1 if x >= cutOff or c",
"PINK) id.polygon(hex((ox,oy),s), fill=BLUE if c & 8 == 8 else",
"x += cos(radians(angle)) * size y += sin(radians(angle)) * size",
"id.polygon(hex((ox-s,oy-s*2),s), fill=BLUE if c & 1 == 1 else PINK)",
"fill=BLUE if c & 1 == 1 else PINK) id.polygon(hex((ox+s,oy-s*2),s),",
"print(\"%s -> %d %d %d %d %d %d %d \"%(i,",
"%d %d %d %d %d %d \"%(i, # 1 if",
"= Image.new('RGB', (2560,1600), BLACK) id = ImageDraw.Draw(img) def hex(offset, size):",
"if a.index(i) & 16 == 16 else 0, # 1",
"1 == 1 else PINK) id.polygon(hex((ox+s,oy-s*2),s), fill=BLUE if c &",
"32 else 0, # 1 if a.index(i) & 64 ==",
"else PINK) id.polygon(hex((ox-s*2,oy),s), fill=BLUE if c & 4 == 4",
"if x >= cutOff or c == \"\\n\": x,y =",
"id.polygon(hex((ox+s,oy-s*2),s), fill=BLUE if c & 2 == 2 else PINK)",
"else 0, # )) # sys.exit(0) WHITE=(255,255,255) PINK=(217,154,197) BLUE=(103,170,249) BLACK=(0,0,0)",
"if c & 8 == 8 else PINK) id.polygon(hex((ox+s*2,oy),s), fill=BLUE",
"sy - sin(radians(120)) * s id.polygon(hex((ox-s,oy-s*2),s), fill=BLUE if c &",
"== 32 else 0, # 1 if a.index(i) & 64",
"else 0, # 1 if a.index(i) & 4 == 4",
"4 == 4 else PINK) id.polygon(hex((ox,oy),s), fill=BLUE if c &",
"2 else PINK) id.polygon(hex((ox-s*2,oy),s), fill=BLUE if c & 4 ==",
"\"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W x X y Y z Z\" if",
"<reponame>dominicschaff/random from PIL import ImageDraw, Image from math import cos,sin,radians",
"X y Y z Z\" if len(a) > 128: print(\"TOO",
"+= cos(radians(angle)) * size y += sin(radians(angle)) * size points.append((x,",
"if len(a) > 128: print(\"TOO MANY CHARACTERS\") sys.exit(1) # for",
"16 == 16 else PINK) id.polygon(hex((ox-s,oy+s*2),s), fill=BLUE if c &",
"print (cutOff) x,y = 0,0 for c in q: drawHex(id,",
"math import cos,sin,radians from random import randint import sys a",
"Image from math import cos,sin,radians from random import randint import",
"[] x,y = offset for angle in range(0, 360, 60):",
"+= sin(radians(angle)) * size points.append((x, y)) return points def drawHex(id,",
"1 if a.index(i) & 16 == 16 else 0, #",
"points.append((x, y)) return points def drawHex(id, sx,sy,s,c): ox = sx",
"sx,sy,s,c): ox = sx - cos(radians(120)) * s oy =",
"c & 2 == 2 else PINK) id.polygon(hex((ox-s*2,oy),s), fill=BLUE if",
"== 16 else 0, # 1 if a.index(i) & 32",
"x*s*7, s*3 + y*s*7, s, a.index(c)) x+=1 if x >=",
"fill=BLUE if c & 2 == 2 else PINK) id.polygon(hex((ox-s*2,oy),s),",
"print(\"TOO MANY CHARACTERS\") sys.exit(1) # for i in a: #",
"# 1 if a.index(i) & 64 == 64 else 0,",
"0, # 1 if a.index(i) & 16 == 16 else",
"== 2 else PINK) id.polygon(hex((ox-s*2,oy),s), fill=BLUE if c & 4",
"1 if a.index(i) & 8 == 8 else 0, #",
"c & 64 == 64 else PINK) q = \"\"\"This",
"64 == 64 else 0, # )) # sys.exit(0) WHITE=(255,255,255)",
"# 1 if a.index(i) & 16 == 16 else 0,",
"1 if a.index(i) & 1 == 1 else 0, #",
"size y += sin(radians(angle)) * size points.append((x, y)) return points",
"16 else PINK) id.polygon(hex((ox-s,oy+s*2),s), fill=BLUE if c & 32 ==",
"-> %d %d %d %d %d %d %d \"%(i, #",
"sin(radians(angle)) * size points.append((x, y)) return points def drawHex(id, sx,sy,s,c):",
"== 1 else PINK) id.polygon(hex((ox+s,oy-s*2),s), fill=BLUE if c & 2",
"fill=BLUE if c & 64 == 64 else PINK) q",
"if c & 64 == 64 else PINK) q =",
"cos(radians(angle)) * size y += sin(radians(angle)) * size points.append((x, y))",
"PINK) id.polygon(hex((ox+s,oy-s*2),s), fill=BLUE if c & 2 == 2 else",
"# 1 if a.index(i) & 8 == 8 else 0,",
"id.polygon(hex((ox-s*2,oy),s), fill=BLUE if c & 4 == 4 else PINK)",
"s*2 + x*s*7, s*3 + y*s*7, s, a.index(c)) x+=1 if",
"W x X y Y z Z\" if len(a) >",
"a.index(i) & 4 == 4 else 0, # 1 if",
"else 0, # 1 if a.index(i) & 16 == 16",
"16 else 0, # 1 if a.index(i) & 32 ==",
"in q: drawHex(id, s*2 + x*s*7, s*3 + y*s*7, s,",
"M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W x X y Y z Z\" if len(a)",
"a: # print(\"%s -> %d %d %d %d %d %d",
"%d %d %d %d %d \"%(i, # 1 if a.index(i)",
"test 0123456789%\"\"\" s = 10 cutOff = int(2560/(s*7)) print (cutOff)",
"import randint import sys a = \"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W x",
"random import randint import sys a = \"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W",
"== 64 else 0, # )) # sys.exit(0) WHITE=(255,255,255) PINK=(217,154,197)",
"128: print(\"TOO MANY CHARACTERS\") sys.exit(1) # for i in a:",
"s, a.index(c)) x+=1 if x >= cutOff or c ==",
"fill=BLUE if c & 8 == 8 else PINK) id.polygon(hex((ox+s*2,oy),s),",
">= cutOff or c == \"\\n\": x,y = 0,y+1 img.show()",
"import cos,sin,radians from random import randint import sys a =",
"a.index(i) & 2 == 2 else 0, # 1 if",
"if a.index(i) & 32 == 32 else 0, # 1",
"if a.index(i) & 64 == 64 else 0, # ))",
"PINK=(217,154,197) BLUE=(103,170,249) BLACK=(0,0,0) img = Image.new('RGB', (2560,1600), BLACK) id =",
"1 == 1 else 0, # 1 if a.index(i) &",
"8 == 8 else PINK) id.polygon(hex((ox+s*2,oy),s), fill=BLUE if c &",
"32 == 32 else PINK) id.polygon(hex((ox+s,oy+s*2),s), fill=BLUE if c &",
"= ImageDraw.Draw(img) def hex(offset, size): points = [] x,y =",
"BLACK) id = ImageDraw.Draw(img) def hex(offset, size): points = []",
"points = [] x,y = offset for angle in range(0,",
"a.index(c)) x+=1 if x >= cutOff or c == \"\\n\":",
"* size y += sin(radians(angle)) * size points.append((x, y)) return",
"cos(radians(120)) * s oy = sy - sin(radians(120)) * s",
"ImageDraw, Image from math import cos,sin,radians from random import randint",
"60): x += cos(radians(angle)) * size y += sin(radians(angle)) *",
"- cos(radians(120)) * s oy = sy - sin(radians(120)) *",
"PINK) id.polygon(hex((ox-s*2,oy),s), fill=BLUE if c & 4 == 4 else",
"== 16 else PINK) id.polygon(hex((ox-s,oy+s*2),s), fill=BLUE if c & 32",
"a = \"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W x X y Y z",
"# 1 if a.index(i) & 1 == 1 else 0,",
"if a.index(i) & 4 == 4 else 0, # 1",
"# 1 if a.index(i) & 2 == 2 else 0,",
"16 == 16 else 0, # 1 if a.index(i) &",
"angle in range(0, 360, 60): x += cos(radians(angle)) * size",
"== 4 else 0, # 1 if a.index(i) & 8",
"if c & 1 == 1 else PINK) id.polygon(hex((ox+s,oy-s*2),s), fill=BLUE",
"drawHex(id, sx,sy,s,c): ox = sx - cos(radians(120)) * s oy",
"== 1 else 0, # 1 if a.index(i) & 2",
"360, 60): x += cos(radians(angle)) * size y += sin(radians(angle))",
"if c & 16 == 16 else PINK) id.polygon(hex((ox-s,oy+s*2),s), fill=BLUE",
"* s oy = sy - sin(radians(120)) * s id.polygon(hex((ox-s,oy-s*2),s),",
"PINK) q = \"\"\"This is a test 0123456789%\"\"\" s =",
"%d %d %d %d %d %d %d \"%(i, # 1",
"s = 10 cutOff = int(2560/(s*7)) print (cutOff) x,y =",
"= 10 cutOff = int(2560/(s*7)) print (cutOff) x,y = 0,0",
")) # sys.exit(0) WHITE=(255,255,255) PINK=(217,154,197) BLUE=(103,170,249) BLACK=(0,0,0) img = Image.new('RGB',",
"id.polygon(hex((ox,oy),s), fill=BLUE if c & 8 == 8 else PINK)",
"0123456789%\"\"\" s = 10 cutOff = int(2560/(s*7)) print (cutOff) x,y",
"2 else 0, # 1 if a.index(i) & 4 ==",
"size points.append((x, y)) return points def drawHex(id, sx,sy,s,c): ox =",
"c & 32 == 32 else PINK) id.polygon(hex((ox+s,oy+s*2),s), fill=BLUE if",
"x,y = 0,0 for c in q: drawHex(id, s*2 +",
"& 2 == 2 else 0, # 1 if a.index(i)",
"i in a: # print(\"%s -> %d %d %d %d",
"fill=BLUE if c & 16 == 16 else PINK) id.polygon(hex((ox-s,oy+s*2),s),",
"x+=1 if x >= cutOff or c == \"\\n\": x,y",
"2 == 2 else 0, # 1 if a.index(i) &",
"& 4 == 4 else 0, # 1 if a.index(i)",
"if a.index(i) & 8 == 8 else 0, # 1",
"& 32 == 32 else 0, # 1 if a.index(i)",
"= sx - cos(radians(120)) * s oy = sy -",
"len(a) > 128: print(\"TOO MANY CHARACTERS\") sys.exit(1) # for i",
"else PINK) id.polygon(hex((ox+s*2,oy),s), fill=BLUE if c & 16 == 16",
"\"%(i, # 1 if a.index(i) & 1 == 1 else",
"2 == 2 else PINK) id.polygon(hex((ox-s*2,oy),s), fill=BLUE if c &",
"c & 8 == 8 else PINK) id.polygon(hex((ox+s*2,oy),s), fill=BLUE if",
"else 0, # 1 if a.index(i) & 8 == 8",
"id.polygon(hex((ox+s*2,oy),s), fill=BLUE if c & 16 == 16 else PINK)",
"sys.exit(0) WHITE=(255,255,255) PINK=(217,154,197) BLUE=(103,170,249) BLACK=(0,0,0) img = Image.new('RGB', (2560,1600), BLACK)",
"32 else PINK) id.polygon(hex((ox+s,oy+s*2),s), fill=BLUE if c & 64 ==",
"for c in q: drawHex(id, s*2 + x*s*7, s*3 +",
"64 == 64 else PINK) q = \"\"\"This is a",
"z Z\" if len(a) > 128: print(\"TOO MANY CHARACTERS\") sys.exit(1)",
"& 4 == 4 else PINK) id.polygon(hex((ox,oy),s), fill=BLUE if c",
"else PINK) q = \"\"\"This is a test 0123456789%\"\"\" s",
"= \"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W x X y Y z Z\"",
"%d %d %d \"%(i, # 1 if a.index(i) & 1",
"q = \"\"\"This is a test 0123456789%\"\"\" s = 10",
"s*3 + y*s*7, s, a.index(c)) x+=1 if x >= cutOff",
"if c & 2 == 2 else PINK) id.polygon(hex((ox-s*2,oy),s), fill=BLUE",
"if c & 4 == 4 else PINK) id.polygon(hex((ox,oy),s), fill=BLUE",
"WHITE=(255,255,255) PINK=(217,154,197) BLUE=(103,170,249) BLACK=(0,0,0) img = Image.new('RGB', (2560,1600), BLACK) id",
"import ImageDraw, Image from math import cos,sin,radians from random import",
"(2560,1600), BLACK) id = ImageDraw.Draw(img) def hex(offset, size): points =",
"== 8 else PINK) id.polygon(hex((ox+s*2,oy),s), fill=BLUE if c & 16",
"a.index(i) & 64 == 64 else 0, # )) #",
"c & 4 == 4 else PINK) id.polygon(hex((ox,oy),s), fill=BLUE if",
"if c & 32 == 32 else PINK) id.polygon(hex((ox+s,oy+s*2),s), fill=BLUE",
"* s id.polygon(hex((ox-s,oy-s*2),s), fill=BLUE if c & 1 == 1",
"return points def drawHex(id, sx,sy,s,c): ox = sx - cos(radians(120))",
"Z\" if len(a) > 128: print(\"TOO MANY CHARACTERS\") sys.exit(1) #",
"& 32 == 32 else PINK) id.polygon(hex((ox+s,oy+s*2),s), fill=BLUE if c",
"else PINK) id.polygon(hex((ox+s,oy+s*2),s), fill=BLUE if c & 64 == 64",
"sys a = \"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W x X y Y",
"Image.new('RGB', (2560,1600), BLACK) id = ImageDraw.Draw(img) def hex(offset, size): points",
"offset for angle in range(0, 360, 60): x += cos(radians(angle))",
"for angle in range(0, 360, 60): x += cos(radians(angle)) *",
"a.index(i) & 8 == 8 else 0, # 1 if",
"0, # 1 if a.index(i) & 64 == 64 else",
"s oy = sy - sin(radians(120)) * s id.polygon(hex((ox-s,oy-s*2),s), fill=BLUE",
"id.polygon(hex((ox+s,oy+s*2),s), fill=BLUE if c & 64 == 64 else PINK)",
"1 if a.index(i) & 64 == 64 else 0, #",
"0,0 for c in q: drawHex(id, s*2 + x*s*7, s*3",
"x,y = offset for angle in range(0, 360, 60): x",
"c in q: drawHex(id, s*2 + x*s*7, s*3 + y*s*7,",
"import sys a = \"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w W x X y",
"oy = sy - sin(radians(120)) * s id.polygon(hex((ox-s,oy-s*2),s), fill=BLUE if",
"0, # 1 if a.index(i) & 2 == 2 else",
"x >= cutOff or c == \"\\n\": x,y = 0,y+1",
"for i in a: # print(\"%s -> %d %d %d",
"in a: # print(\"%s -> %d %d %d %d %d",
"& 16 == 16 else 0, # 1 if a.index(i)",
"fill=BLUE if c & 4 == 4 else PINK) id.polygon(hex((ox,oy),s),",
"1 else PINK) id.polygon(hex((ox+s,oy-s*2),s), fill=BLUE if c & 2 ==",
"0, # 1 if a.index(i) & 4 == 4 else",
"else PINK) id.polygon(hex((ox-s,oy+s*2),s), fill=BLUE if c & 32 == 32",
"y)) return points def drawHex(id, sx,sy,s,c): ox = sx -",
"cos,sin,radians from random import randint import sys a = \"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m",
"if a.index(i) & 2 == 2 else 0, # 1",
"PINK) id.polygon(hex((ox-s,oy+s*2),s), fill=BLUE if c & 32 == 32 else",
"a.index(i) & 1 == 1 else 0, # 1 if",
"q: drawHex(id, s*2 + x*s*7, s*3 + y*s*7, s, a.index(c))",
"in range(0, 360, 60): x += cos(radians(angle)) * size y",
"4 else 0, # 1 if a.index(i) & 8 ==",
"& 64 == 64 else 0, # )) # sys.exit(0)",
"1 if a.index(i) & 4 == 4 else 0, #",
"32 == 32 else 0, # 1 if a.index(i) &",
"else PINK) id.polygon(hex((ox+s,oy-s*2),s), fill=BLUE if c & 2 == 2",
"else 0, # 1 if a.index(i) & 64 == 64",
"MANY CHARACTERS\") sys.exit(1) # for i in a: # print(\"%s",
"BLUE=(103,170,249) BLACK=(0,0,0) img = Image.new('RGB', (2560,1600), BLACK) id = ImageDraw.Draw(img)",
"is a test 0123456789%\"\"\" s = 10 cutOff = int(2560/(s*7))",
"== 64 else PINK) q = \"\"\"This is a test",
"cutOff = int(2560/(s*7)) print (cutOff) x,y = 0,0 for c",
"drawHex(id, s*2 + x*s*7, s*3 + y*s*7, s, a.index(c)) x+=1",
"& 16 == 16 else PINK) id.polygon(hex((ox-s,oy+s*2),s), fill=BLUE if c",
"from random import randint import sys a = \"a0A1b2B3c4C5d6D7e8E9f!F,g.G/h?H<i>I:j;J'k\\\"K\\\\l|L/m M\\nn\\tN@o#O$p%P^q&Q*r(R)s_S-t+T=u{U}v[V]w",
"0, # 1 if a.index(i) & 8 == 8 else",
"& 1 == 1 else 0, # 1 if a.index(i)",
"c & 16 == 16 else PINK) id.polygon(hex((ox-s,oy+s*2),s), fill=BLUE if",
"fill=BLUE if c & 32 == 32 else PINK) id.polygon(hex((ox+s,oy+s*2),s),"
] |
[
"spec_rand = on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\") @spec_rand.handle() async def _(bot: Bot, event: Event,",
"get_driver().config.superusers if m['role'] != 'owner' and m['role'] != 'admin' and",
"2 s = f\"今日人品值:{rp}\\n\" for i in range(11): if wm_value[i]",
"brk = int(chart['notes'][-1]) total_score = 500 * tap + slide",
"or (len(ans) >= 5 and ans.lower() in guess.music['title'].lower()): guess.is_end =",
"f\"{file}\" } }, { \"type\": \"text\", \"data\": { \"text\": msg",
"group_members = await bot.get_group_member_list(group_id=event.group_id) for m in group_members: if m['user_id']",
"from nonebot import on_command, on_message, on_notice, on_regex, get_driver from nonebot.log",
"query_chart.send(f'''{music['title']} {level_labels2[level_index]} 分数线 {line}% 允许的最多 TAP GREAT 数量为 {(total_score *",
"Dict[Tuple[str, str], GuessObject] = {} guess_cd_dict: Dict[Tuple[str, str], float] =",
"\"\": music_aliases[arr[i].lower()].append(arr[0]) find_song = on_regex(r\".+是什么歌\") @find_song.handle() async def _(bot: Bot,",
"= '\\n'.join(result_set) await find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{ s }\") query_score = on_command('分数线') query_score_text",
"Event, state: T_State): await mr.finish(song_txt(total_list.random())) search_music = on_regex(r\"^查歌.+\") @search_music.handle() async",
"{music.title}\\n\" } }, { \"type\": \"image\", \"data\": { \"file\": f\"https://www.diving-fish.com/covers/{music.id}.jpg\"",
"else: await disable_guess_music.finish(\"请输入 猜歌设置 启用/禁用\") await db.commit() await disable_guess_music.finish(\"设置成功\") guess_dict:",
"['绿', '黄', '红', '紫', '白'] if groups[0] != \"\": try:",
"'''此功能为查找某首歌分数线设计。 命令格式:分数线 <难度+歌曲id> <分数线> 例如:分数线 白337 100 命令将返回分数线允许的 TAP GREAT",
"def _(bot: Bot, event: Event, state: T_State): qq = int(event.get_user_id())",
"username == \"\": payload = {'qq': str(event.get_user_id())} else: payload =",
"5: await guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\") return if k in guess_cd_dict and time.time()",
"== 3: s += f'宜 {wm_list[i]}\\n' elif wm_value[i] == 0:",
"= groups[1] music = total_list.by_id(name) try: file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" await",
"== \"dx\": tp = [\"DX\"] elif res.groups()[0] == \"sd\" or",
"= ('查看舞萌相关功能', \"\"\"桜千雪です、よろしく。 可用命令如下: 今日舞萌 查看今天的舞萌运势 XXXmaimaiXXX什么 随机一首歌 随个[dx/标准][绿黄红紫白]<难度> 随机一首指定条件的乐曲",
"from src.libraries.image import * from src.libraries.maimai_best_40 import generate import requests",
"state: T_State): regex = \"([绿黄红紫白]?)id([0-9]+)\" groups = re.match(regex, str(event.get_message())).groups() level_labels",
"Message([ { \"type\": \"text\", \"data\": { \"text\": f\"{music.id}. {music.title}\\n\" }",
"await query_chart.send(\"未找到该乐曲\") wm_list = ['拼机', '推分', '越级', '下埋', '夜勤', '练底力',",
"= \"\" for elem in result_set: s += f\"{elem[0]}. {elem[1]}",
"m['role'] != 'admin' and str(m['user_id']) not in su: await disable_guess_music.finish(\"只有管理员可以设置猜歌\")",
"MessageSegment.text(\"答案将在 30 秒后揭晓\") ]))) asyncio.create_task(give_answer(bot, event, state)) return state[\"cycle\"] +=",
"\"\": return res = total_list.filter(title_search=name) await search_music.finish(Message([ {\"type\": \"text\", \"data\":",
"'Exp', 'Mst', 'ReM'] if ds2 is not None: music_data =",
"str(event.get_message()).lower()) try: if res.groups()[0] == \"dx\": tp = [\"DX\"] elif",
"\"type\": \"image\", \"data\": { \"file\": f\"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}\" } }]) @query_score.handle()",
"谱师: {chart['charter']} ''' else: msg = f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]}",
"_(bot: Bot, event: Event, state: T_State): regex = \"查歌(.+)\" name",
"/ total_score * 100:.4f}%)''') except Exception: await query_chart.send(\"格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息\") best_40_pic",
"json import random import time import re from urllib import",
"username} img, success = await generate(payload) if success == 400:",
"T_State): qq = int(event.get_user_id()) h2 = hash(qq) h = h2",
"'黄', '红', '紫', '白'] regex = \"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\" res = re.match(regex,",
"str(event.get_message())).groups() level_labels = ['绿', '黄', '红', '紫', '白'] if groups[0]",
"elif wm_value[i] == 0: s += f'忌 {wm_list[i]}\\n' s +=",
"res = total_list.filter(title_search=name) await search_music.finish(Message([ {\"type\": \"text\", \"data\": { \"text\":",
"= int(chart['notes'][1]) touch = int(chart['notes'][3]) if len(chart['notes']) == 5 else",
"\"sd\" or res.groups()[0] == \"标准\": tp = [\"SD\"] else: tp",
"elif len(argv) == 2: try: grp = re.match(r, argv[0]).groups() level_labels",
"{level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} BREAK: {chart['notes'][3]} 谱师:",
"200 秒则自动结束上一次 del guess_dict[k] else: await guess_music.send(\"当前已有正在进行的猜歌\") return whitelists =",
"k in guess_cd_dict and time.time() < guess_cd_dict[k]: await guess_music.finish(f\"已经猜过啦,下次猜歌会在 {time.strftime('%H:%M',",
"guess_dict[k] # await guess_music_solve.send(ans + \"|\" + guess.music['id']) if ans",
"容错以及 BREAK 50落等价的 TAP GREAT 数。 以下为 TAP GREAT 的对应表:",
"\"image\", \"data\": { \"file\": f\"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}\" } }]) @query_score.handle() async",
"event.message_type k = (mt, event.user_id if mt == \"private\" else",
"Bot, event: Event, state: T_State): regex = \"([绿黄红紫白]?)id([0-9]+)\" groups =",
"'收歌'] jrwm = on_command('今日舞萌', aliases={'今日mai'}) @jrwm.handle() async def _(bot: Bot,",
"raise ValueError await query_chart.send(f'''{music['title']} {level_labels2[level_index]} 分数线 {line}% 允许的最多 TAP GREAT",
"} }, { \"type\": \"text\", \"data\": { \"text\": msg }",
"{ \"type\": \"image\", \"data\": { \"file\": f\"https://www.diving-fish.com/covers/{music.id}.jpg\" } }, {",
"def _(bot: Bot, event: Event, state: T_State): regex = \"(.+)是什么歌\"",
"2500 break_bonus = 0.01 / brk break_50_reduce = total_score *",
"def song_txt(music: Music): return Message([ { \"type\": \"text\", \"data\": {",
"101 - line if reduce <= 0 or reduce >=",
"await bot.get_group_member_list(group_id=event.group_id) for m in group_members: if m['user_id'] == event.user_id:",
"f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")]))) del guess_dict[state[\"k\"]] @guess_music.handle() async def _(bot: Bot,",
"0 brk = int(chart['notes'][-1]) total_score = 500 * tap +",
"\"data\": { \"text\": f\"{music.id}. {music.title}\\n\" } }, { \"type\": \"image\",",
"music['title'], music['ds'][i], diff_label[i], music['level'][i])) return result_set inner_level = on_command('inner_level ',",
"whitelists = get_driver().config.whitelists if not (mt == \"group\" and gid",
"Exception as e: print(e) await spec_rand.finish(\"随机命令错误,请检查语法\") mr = on_regex(r\".*maimai.*什么\") @mr.handle()",
"set enabled=0 where group_id={event.group_id}') else: await disable_guess_music.finish(\"请输入 猜歌设置 启用/禁用\") await",
"get_driver from nonebot.log import logger from nonebot.permission import Permission from",
"TAP GREAT(-{break_50_reduce / total_score * 100:.4f}%)''') except Exception: await query_chart.send(\"格式错误或未找到乐曲,输入“分数线",
"inner_level = on_command('inner_level ', aliases={'定数查歌 '}) @inner_level.handle() async def _(bot:",
"= {} guess_cd_dict: Dict[Tuple[str, str], float] = {} guess_music =",
"aliases={'今日mai'}) @jrwm.handle() async def _(bot: Bot, event: Event, state: T_State):",
"username = str(event.get_message()).strip() print(event.message_id) if username == \"\": payload =",
"ValueError await query_chart.send(f'''{music['title']} {level_labels2[level_index]} 分数线 {line}% 允许的最多 TAP GREAT 数量为",
"[] diff_label = ['Bas', 'Adv', 'Exp', 'Mst', 'ReM'] if ds2",
"async def _(bot: Bot, event: Event, state: T_State): qq =",
"100:.4f}%)''') except Exception: await query_chart.send(\"格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息\") best_40_pic = on_command('b40') @best_40_pic.handle()",
"6: asyncio.create_task(bot.send(event, f\"{cycle + 1}/7 这首歌\" + guess.guess_options[cycle])) else: asyncio.create_task(bot.send(event,",
"name = re.match(regex, str(event.get_message())).groups()[0].strip() if name == \"\": return res",
"= total_list.by_title(result_set[0]) await find_song.finish(Message([{\"type\": \"text\", \"data\": {\"text\": \"您要找的是不是\"}}] + song_txt(music)))",
"Event, state: T_State): regex = \"([绿黄红紫白]?)id([0-9]+)\" groups = re.match(regex, str(event.get_message())).groups()",
"}, { \"type\": \"image\", \"data\": { \"file\": f\"{file}\" } },",
"== 403: await best_40_pic.send(\"该用户禁止了其他人获取数据。\") else: await best_40_pic.send(Message([ MessageSegment.reply(event.message_id), MessageSegment.image(f\"base64://{str(image_to_base64(img), encoding='utf-8')}\")",
"import re from urllib import parse driver = get_driver() @driver.on_startup",
"= f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" if len(chart['notes']) == 4: msg = f'''{level_name[level_index]} {level}({ds})",
"else: name = groups[1] music = total_list.by_id(name) try: file =",
"HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} BREAK: {chart['notes'][3]} 谱师: {chart['charter']} ''' else:",
"return if len(argv) == 1: result_set = inner_level_q(float(argv[0])) else: result_set",
"Exception: await query_chart.send(\"未找到该乐曲\") wm_list = ['拼机', '推分', '越级', '下埋', '夜勤',",
"name = groups[1] music = total_list.by_id(name) try: file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\"",
"Bot, event: Event, state: T_State): r = \"([绿黄红紫白])(?:id)?([0-9]+)\" argv =",
"c.execute(f\"select * from guess_table where group_id={gid}\") data = await c.fetchone()",
"guess_music.send(\"本群已禁用猜歌\") return if k in guess_dict: if k in guess_cd_dict",
"<难度+歌曲id> <分数线> 例如:分数线 白337 100 命令将返回分数线允许的 TAP GREAT 容错以及 BREAK",
"f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" if len(chart['notes']) == 4: msg = f'''{level_name[level_index]} {level}({ds}) TAP:",
"i in range(len(arr)): if arr[i] != \"\": music_aliases[arr[i].lower()].append(arr[0]) find_song =",
"src.libraries.image import * from src.libraries.maimai_best_40 import generate import requests import",
"collections import defaultdict from typing import List, Dict, Any from",
"import requests import json import random import time import re",
"{guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")]))) del guess_dict[state[\"k\"]] @guess_music.handle() async def _(bot: Bot, event:",
"for i in music.diff: result_set.append((music['id'], music['title'], music['ds'][i], diff_label[i], music['level'][i])) return",
"if len(result_set) == 1: music = total_list.by_title(result_set[0]) await find_song.finish(Message([{\"type\": \"text\",",
"event: Event, state: T_State): qq = int(event.get_user_id()) h2 = hash(qq)",
"50 条,请尝试缩小查询范围\") return s = \"\" for elem in result_set:",
"total_list.by_title(result_set[0]) await find_song.finish(Message([{\"type\": \"text\", \"data\": {\"text\": \"您要找的是不是\"}}] + song_txt(music))) else:",
"['绿', '黄', '红', '紫', '白'] regex = \"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\" res =",
"spec_rand.send(song_txt(music_data.random())) except Exception as e: print(e) await spec_rand.finish(\"随机命令错误,请检查语法\") mr =",
"{\"text\": \"您要找的是不是\"}}] + song_txt(music))) else: s = '\\n'.join(result_set) await find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{",
"event, state)) return state[\"cycle\"] += 1 asyncio.create_task(guess_music_loop(bot, event, state)) async",
"< guess_cd_dict[k]: await guess_music.finish(f\"已经猜过啦,下次猜歌会在 {time.strftime('%H:%M', time.localtime(guess_cd_dict[k]))} 可用噢\") return guess =",
"f\"{music.id}. {music.title}\\n\" } }, { \"type\": \"image\", \"data\": { \"file\":",
"if m['user_id'] == event.user_id: break su = get_driver().config.superusers if m['role']",
"if data is None: await c.execute(f'insert into guess_table values ({gid},",
"generate import requests import json import random import time import",
"group_id={event.group_id}') else: await disable_guess_music.finish(\"请输入 猜歌设置 启用/禁用\") await db.commit() await disable_guess_music.finish(\"设置成功\")",
"= ['绿', '黄', '红', '紫', '白'] if groups[0] != \"\":",
"'白'] level_labels2 = ['Basic', 'Advanced', 'Expert', 'Master', 'Re:MASTER'] level_index =",
"in range(11): wm_value.append(h & 3) h >>= 2 s =",
"1 asyncio.create_task(guess_music_loop(bot, event, state)) async def give_answer(bot: Bot, event: Event,",
"\"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\" music = total_list[h2 % len(total_list)] await jrwm.finish(Message([ {\"type\": \"text\",",
"= [] diff_label = ['Bas', 'Adv', 'Exp', 'Mst', 'ReM'] if",
"猜歌设置 启用/禁用\") await db.commit() await disable_guess_music.finish(\"设置成功\") guess_dict: Dict[Tuple[str, str], GuessObject]",
"Permission from nonebot.typing import T_State from nonebot.adapters import Event, Bot",
"} }, { \"type\": \"text\", \"data\": { \"text\": f\"艺术家: {music['basic_info']['artist']}\\n分类:",
"event: Event, state: T_State): await asyncio.sleep(10) guess: GuessObject = state[\"guess_object\"]",
"{level_labels2[level_index]} 分数线 {line}% 允许的最多 TAP GREAT 数量为 {(total_score * reduce",
"time.time() < guess_cd_dict[k]: await guess_music.finish(f\"已经猜过啦,下次猜歌会在 {time.strftime('%H:%M', time.localtime(guess_cd_dict[k]))} 可用噢\") return guess",
"'r', encoding='utf-8') tmp = f.readlines() f.close() for t in tmp:",
"GuessObject = state[\"guess_object\"] if guess.is_end: return cycle = state[\"cycle\"] if",
"result_set = inner_level_q(float(argv[0])) else: result_set = inner_level_q(float(argv[0]), float(argv[1])) if len(result_set)",
"[\"SD\", \"DX\"] level = res.groups()[2] if res.groups()[1] == \"\": music_data",
"return state[\"cycle\"] += 1 asyncio.create_task(guess_music_loop(bot, event, state)) async def give_answer(bot:",
"def _(bot: Bot, event: Event, state: T_State): r = \"([绿黄红紫白])(?:id)?([0-9]+)\"",
"len(result_set) > 50: await inner_level.finish(\"数据超出 50 条,请尝试缩小查询范围\") return s =",
"GREAT 容错以及 BREAK 50落等价的 TAP GREAT 数。 以下为 TAP GREAT",
"best_40_pic = on_command('b40') @best_40_pic.handle() async def _(bot: Bot, event: Event,",
"= [\"SD\", \"DX\"] level = res.groups()[2] if res.groups()[1] == \"\":",
"} ])) except Exception: await query_chart.send(\"未找到该谱面\") else: name = groups[1]",
"Bot, event: Event, state: T_State): regex = \"(.+)是什么歌\" name =",
"0 guess_cd_dict[k] = time.time() + 600 await guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中 5 个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\")",
"* 100:.4f}%)''') except Exception: await query_chart.send(\"格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息\") best_40_pic = on_command('b40')",
"= event.message_type k = (mt, event.user_id if mt == \"private\"",
"tp = [\"SD\", \"DX\"] level = res.groups()[2] if res.groups()[1] ==",
"\"type\": \"text\", \"data\": { \"text\": msg } } ])) except",
"line = float(argv[1]) music = total_list.by_id(chart_id) chart: Dict[Any] = music['charts'][level_index]",
"\"text\", \"data\": { \"text\": f\"{music.id}. {music.title}\\n\" } }, { \"type\":",
"on_message(priority=20) @guess_music_solve.handle() async def _(bot: Bot, event: Event, state: T_State):",
"nonebot.log import logger from nonebot.permission import Permission from nonebot.typing import",
"* from src.libraries.maimai_best_40 import generate import requests import json import",
"in music_data: for i in music.diff: result_set.append((music['id'], music['title'], music['ds'][i], diff_label[i],",
"int(chart['notes'][2]) hold = int(chart['notes'][1]) touch = int(chart['notes'][3]) if len(chart['notes']) ==",
"k in guess_dict: if k in guess_cd_dict and time.time() >",
"in guess_dict: if k in guess_cd_dict and time.time() > guess_cd_dict[k]",
"1: music = total_list.by_title(result_set[0]) await find_song.finish(Message([{\"type\": \"text\", \"data\": {\"text\": \"您要找的是不是\"}}]",
"+ song_txt(music))) music_aliases = defaultdict(list) f = open('src/static/aliases.csv', 'r', encoding='utf-8')",
"logger.info(\"Load help text successfully\") help_text: dict = get_driver().config.help_text help_text['mai'] =",
"= ['Basic', 'Advanced', 'Expert', 'Master', 'Re:MASTER'] level_index = level_labels.index(grp[0]) chart_id",
"GREAT 数。 以下为 TAP GREAT 的对应表: GREAT/GOOD/MISS TAP 1/2.5/5 HOLD",
"SLIDE: {chart['notes'][2]} BREAK: {chart['notes'][3]} 谱师: {chart['charter']} ''' else: msg =",
"music['ds'][level_index] level = music['level'][level_index] file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" if len(chart['notes']) ==",
"if name == \"\": return res = total_list.filter(title_search=name) await search_music.finish(Message([",
"len(chart['notes']) == 4: msg = f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD:",
"查看今天的舞萌运势 XXXmaimaiXXX什么 随机一首歌 随个[dx/标准][绿黄红紫白]<难度> 随机一首指定条件的乐曲 查歌<乐曲标题的一部分> 查询符合条件的乐曲 [绿黄红紫白]id<歌曲编号> 查询乐曲信息或谱面信息 <歌曲别名>是什么歌",
"TAP GREAT 容错以及 BREAK 50落等价的 TAP GREAT 数。 以下为 TAP",
"jrwm.finish(Message([ {\"type\": \"text\", \"data\": {\"text\": s}} ] + song_txt(music))) music_aliases",
"'admin' and str(m['user_id']) not in su: await disable_guess_music.finish(\"只有管理员可以设置猜歌\") return db",
"src.libraries.tool import hash from src.libraries.maimaidx_music import * from src.libraries.image import",
"'紫', '白'] level_labels2 = ['Basic', 'Advanced', 'Expert', 'Master', 'Re:MASTER'] level_index",
"!= \"\": try: level_index = level_labels.index(groups[0]) level_name = ['Basic', 'Advanced',",
"encoding=\"utf-8\")), MessageSegment.text(\"答案将在 30 秒后揭晓\") ]))) asyncio.create_task(give_answer(bot, event, state)) return state[\"cycle\"]",
"''' await query_chart.send(Message([ { \"type\": \"text\", \"data\": { \"text\": f\"{music['id']}.",
"t in tmp: arr = t.strip().split('\\t') for i in range(len(arr)):",
"= open('src/static/aliases.csv', 'r', encoding='utf-8') tmp = f.readlines() f.close() for t",
"db.cursor() await c.execute(f\"select * from guess_table where group_id={gid}\") data =",
"for i in range(11): if wm_value[i] == 3: s +=",
"await db.cursor() await c.execute(f\"select * from guess_table where group_id={gid}\") data",
"s = \"\" for elem in result_set: s += f\"{elem[0]}.",
"\"text\": f\"艺术家: {music['basic_info']['artist']}\\n分类: {music['basic_info']['genre']}\\nBPM: {music['basic_info']['bpm']}\\n版本: {music['basic_info']['from']}\\n难度: {'/'.join(music['level'])}\" } } ]))",
"= Message([{ \"type\": \"image\", \"data\": { \"file\": f\"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}\" }",
"regex = \"(.+)是什么歌\" name = re.match(regex, str(event.get_message())).groups()[0].strip().lower() if name not",
"Message([MessageSegment.text(\"答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")]))) del guess_dict[state[\"k\"]] @guess_music.handle() async def",
"if wm_value[i] == 3: s += f'宜 {wm_list[i]}\\n' elif wm_value[i]",
"else: payload = {'username': username} img, success = await generate(payload)",
"= on_command('inner_level ', aliases={'定数查歌 '}) @inner_level.handle() async def _(bot: Bot,",
"'Mst', 'ReM'] if ds2 is not None: music_data = total_list.filter(ds=(ds1,",
"return Message([ { \"type\": \"text\", \"data\": { \"text\": f\"{music.id}. {music.title}\\n\"",
"get_driver().config.db c = await db.cursor() await c.execute(f\"select * from guess_table",
"详情请输入“分数线 帮助”查看\"\"\") def song_txt(music: Music): return Message([ { \"type\": \"text\",",
"open('src/static/aliases.csv', 'r', encoding='utf-8') tmp = f.readlines() f.close() for t in",
"tap + slide * 1500 + hold * 1000 +",
"{ \"text\": f\"艺术家: {music['basic_info']['artist']}\\n分类: {music['basic_info']['genre']}\\nBPM: {music['basic_info']['bpm']}\\n版本: {music['basic_info']['from']}\\n难度: {'/'.join(music['level'])}\" } }",
"= str(event.get_message()) group_members = await bot.get_group_member_list(group_id=event.group_id) for m in group_members:",
"as e: print(e) await spec_rand.finish(\"随机命令错误,请检查语法\") mr = on_regex(r\".*maimai.*什么\") @mr.handle() async",
"50: await inner_level.finish(\"数据超出 50 条,请尝试缩小查询范围\") return s = \"\" for",
"Message([ MessageSegment.text(\"7/7 这首歌封面的一部分是:\"), MessageSegment.image(\"base64://\" + str(guess.b64image, encoding=\"utf-8\")), MessageSegment.text(\"答案将在 30 秒后揭晓\")",
"{chart['notes'][1]} SLIDE: {chart['notes'][2]} BREAK: {chart['notes'][3]} 谱师: {chart['charter']} ''' else: msg",
"result_set = music_aliases[name] if len(result_set) == 1: music = total_list.by_title(result_set[0])",
"{'qq': str(event.get_user_id())} else: payload = {'username': username} img, success =",
"Event, Bot from nonebot.adapters.cqhttp import Message, MessageSegment, GroupMessageEvent, PrivateMessageEvent from",
"async def _(bot: Bot, event: Event, state: T_State): username =",
"group_id={gid}\") data = await c.fetchone() if data is None: await",
"total_list.filter(level=level, diff=['绿黄红紫白'.index(res.groups()[1])], type=tp) await spec_rand.send(song_txt(music_data.random())) except Exception as e: print(e)",
"from nonebot.log import logger from nonebot.permission import Permission from nonebot.typing",
"= re.match(regex, str(event.get_message())).groups()[0].strip().lower() if name not in music_aliases: await find_song.finish(\"未找到此歌曲\\n舞萌",
"= get_driver().config.superusers if m['role'] != 'owner' and m['role'] != 'admin'",
"50落等价的 TAP GREAT 数。 以下为 TAP GREAT 的对应表: GREAT/GOOD/MISS TAP",
"re.match(regex, str(event.get_message()).lower()) try: if res.groups()[0] == \"dx\": tp = [\"DX\"]",
"} }]) @query_score.handle() async def _(bot: Bot, event: Event, state:",
"= f\"今日人品值:{rp}\\n\" for i in range(11): if wm_value[i] == 3:",
"music_data = total_list.filter(ds=(ds1, ds2)) else: music_data = total_list.filter(ds=ds1) for music",
"diff=['绿黄红紫白'.index(res.groups()[1])], type=tp) await spec_rand.send(song_txt(music_data.random())) except Exception as e: print(e) await",
"MessageSegment.text(\"7/7 这首歌封面的一部分是:\"), MessageSegment.image(\"base64://\" + str(guess.b64image, encoding=\"utf-8\")), MessageSegment.text(\"答案将在 30 秒后揭晓\") ])))",
"await query_chart.send(f'''{music['title']} {level_labels2[level_index]} 分数线 {line}% 允许的最多 TAP GREAT 数量为 {(total_score",
"Music): return Message([ { \"type\": \"text\", \"data\": { \"text\": f\"{music.id}.",
"101: raise ValueError await query_chart.send(f'''{music['title']} {level_labels2[level_index]} 分数线 {line}% 允许的最多 TAP",
"随机一首指定条件的乐曲 查歌<乐曲标题的一部分> 查询符合条件的乐曲 [绿黄红紫白]id<歌曲编号> 查询乐曲信息或谱面信息 <歌曲别名>是什么歌 查询乐曲别名对应的乐曲 定数查歌 <定数> 查询定数对应的乐曲",
"ans == guess.music['id'] or (ans.lower() == guess.music['title'].lower()) or (len(ans) >=",
"import Event, Bot from nonebot.adapters.cqhttp import Message, MessageSegment, GroupMessageEvent, PrivateMessageEvent",
"guess state[\"k\"] = k state[\"guess_object\"] = guess state[\"cycle\"] = 0",
"\"(.+)是什么歌\" name = re.match(regex, str(event.get_message())).groups()[0].strip().lower() if name not in music_aliases:",
"+ hold * 1000 + touch * 500 + brk",
"if mt == \"private\" else event.group_id) if k not in",
"= re.match(regex, str(event.get_message()).lower()) try: if res.groups()[0] == \"dx\": tp =",
"for music in music_data: for i in music.diff: result_set.append((music['id'], music['title'],",
"== \"private\" else event.group_id) if mt == \"group\": gid =",
"src.libraries.maimaidx_music import * from src.libraries.image import * from src.libraries.maimai_best_40 import",
"'Adv', 'Exp', 'Mst', 'ReM'] if ds2 is not None: music_data",
"return s = \"\" for elem in result_set: s +=",
"await c.execute(f'update guess_table set enabled=1 where group_id={event.group_id}') elif arg ==",
"groups[0] != \"\": try: level_index = level_labels.index(groups[0]) level_name = ['Basic',",
"[\"SD\"] else: tp = [\"SD\", \"DX\"] level = res.groups()[2] if",
"re.match(regex, str(event.get_message())).groups()[0].strip().lower() if name not in music_aliases: await find_song.finish(\"未找到此歌曲\\n舞萌 DX",
"total_list.by_id(chart_id) chart: Dict[Any] = music['charts'][level_index] tap = int(chart['notes'][0]) slide =",
"h2 = hash(qq) h = h2 rp = h %",
"(len(ans) >= 5 and ans.lower() in guess.music['title'].lower()): guess.is_end = True",
"def _(bot: Bot, event: Event, state: T_State): await mr.finish(song_txt(total_list.random())) search_music",
"if mt == \"group\": gid = event.group_id db = get_driver().config.db",
"query_score = on_command('分数线') query_score_text = '''此功能为查找某首歌分数线设计。 命令格式:分数线 <难度+歌曲id> <分数线> 例如:分数线",
"hold * 1000 + touch * 500 + brk *",
"if arr[i] != \"\": music_aliases[arr[i].lower()].append(arr[0]) find_song = on_regex(r\".+是什么歌\") @find_song.handle() async",
"} }, { \"type\": \"image\", \"data\": { \"file\": f\"{file}\" }",
"hash from src.libraries.maimaidx_music import * from src.libraries.image import * from",
"+= f'宜 {wm_list[i]}\\n' elif wm_value[i] == 0: s += f'忌",
"= str(event.get_message()).strip().split(\" \") if len(argv) > 2 or len(argv) ==",
"nonebot.adapters import Event, Bot from nonebot.adapters.cqhttp import Message, MessageSegment, GroupMessageEvent,",
"ds = music['ds'][level_index] level = music['level'][level_index] file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" if",
"await guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中 5 个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\") asyncio.create_task(guess_music_loop(bot, event, state)) guess_music_solve = on_message(priority=20)",
"TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} BREAK: {chart['notes'][3]} 谱师: {chart['charter']}",
"random import time import re from urllib import parse driver",
"int(chart['notes'][3]) if len(chart['notes']) == 5 else 0 brk = int(chart['notes'][-1])",
"T_State): username = str(event.get_message()).strip() print(event.message_id) if username == \"\": payload",
"5 个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\") asyncio.create_task(guess_music_loop(bot, event, state)) guess_music_solve = on_message(priority=20) @guess_music_solve.handle() async",
"if success == 400: await best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\") elif success == 403:",
"= int(chart['notes'][-1]) total_score = 500 * tap + slide *",
">= 101: raise ValueError await query_chart.send(f'''{music['title']} {level_labels2[level_index]} 分数线 {line}% 允许的最多",
"HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} TOUCH: {chart['notes'][3]} BREAK: {chart['notes'][4]} 谱师: {chart['charter']}",
"{\"type\": \"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" }} for music",
"event: Event, state: T_State): username = str(event.get_message()).strip() print(event.message_id) if username",
"import * from src.libraries.maimai_best_40 import generate import requests import json",
"MessageSegment, GroupMessageEvent, PrivateMessageEvent from src.libraries.maimaidx_guess import GuessObject from src.libraries.tool import",
"str], GuessObject] = {} guess_cd_dict: Dict[Tuple[str, str], float] = {}",
"400: # 如果已经过了 200 秒则自动结束上一次 del guess_dict[k] else: await guess_music.send(\"当前已有正在进行的猜歌\")",
"import List, Dict, Any from nonebot import on_command, on_message, on_notice,",
"f = open('src/static/aliases.csv', 'r', encoding='utf-8') tmp = f.readlines() f.close() for",
"import * from src.libraries.image import * from src.libraries.maimai_best_40 import generate",
"= hash(qq) h = h2 rp = h % 100",
"on_regex(r\".+是什么歌\") @find_song.handle() async def _(bot: Bot, event: Event, state: T_State):",
"== \"private\" else event.group_id) if k not in guess_dict: return",
"= {'qq': str(event.get_user_id())} else: payload = {'username': username} img, success",
"{chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} BREAK: {chart['notes'][3]} 谱师: {chart['charter']} '''",
"music_data = total_list.filter(level=level, diff=['绿黄红紫白'.index(res.groups()[1])], type=tp) await spec_rand.send(song_txt(music_data.random())) except Exception as",
"GuessObject() guess_dict[k] = guess state[\"k\"] = k state[\"guess_object\"] = guess",
"Event, state: T_State): username = str(event.get_message()).strip() print(event.message_id) if username ==",
"{ \"type\": \"text\", \"data\": { \"text\": f\"\\n{'/'.join(music.level)}\" } } ])",
"find_song.finish(Message([{\"type\": \"text\", \"data\": {\"text\": \"您要找的是不是\"}}] + song_txt(music))) else: s =",
"= str(event.get_message()).strip().split(\" \") if len(argv) == 1 and argv[0] ==",
"music_aliases = defaultdict(list) f = open('src/static/aliases.csv', 'r', encoding='utf-8') tmp =",
"if len(argv) == 1: result_set = inner_level_q(float(argv[0])) else: result_set =",
"- line if reduce <= 0 or reduce >= 101:",
"if res.groups()[0] == \"dx\": tp = [\"DX\"] elif res.groups()[0] ==",
"i in range(11): wm_value.append(h & 3) h >>= 2 s",
"state[\"cycle\"] = 0 guess_cd_dict[k] = time.time() + 600 await guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中",
"whitelists): if len(guess_dict) >= 5: await guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\") return if k",
"T_State): mt = event.message_type k = (mt, event.user_id if mt",
"arr = t.strip().split('\\t') for i in range(len(arr)): if arr[i] !=",
"best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\") elif success == 403: await best_40_pic.send(\"该用户禁止了其他人获取数据。\") else: await best_40_pic.send(Message([",
"if cycle < 6: asyncio.create_task(bot.send(event, f\"{cycle + 1}/7 这首歌\" +",
"len(argv) == 2: try: grp = re.match(r, argv[0]).groups() level_labels =",
"= total_list.filter(ds=(ds1, ds2)) else: music_data = total_list.filter(ds=ds1) for music in",
"in guess_dict: return ans = str(event.get_message()) guess = guess_dict[k] #",
"set enabled=1 where group_id={event.group_id}') elif arg == '禁用': await c.execute(f'update",
"await c.fetchone() if data is None: await c.execute(f'insert into guess_table",
"await c.execute(f'insert into guess_table values ({gid}, 1)') elif data[1] ==",
"m['role'] != 'owner' and m['role'] != 'admin' and str(m['user_id']) not",
"on_regex, get_driver from nonebot.log import logger from nonebot.permission import Permission",
"Event): if event.message_type != \"group\": return arg = str(event.get_message()) group_members",
"guess_table values ({gid}, 1)') elif data[1] == 0: await guess_music.send(\"本群已禁用猜歌\")",
"import Permission from nonebot.typing import T_State from nonebot.adapters import Event,",
"} ])) except Exception: await query_chart.send(\"未找到该乐曲\") wm_list = ['拼机', '推分',",
"c.fetchone() if data is None: await c.execute(f'insert into guess_table values",
"guess_cd_dict[k] - 400: # 如果已经过了 200 秒则自动结束上一次 del guess_dict[k] else:",
"res.groups()[0] == \"标准\": tp = [\"SD\"] else: tp = [\"SD\",",
"chart: Dict[Any] = music['charts'][level_index] tap = int(chart['notes'][0]) slide = int(chart['notes'][2])",
"{ \"file\": f\"https://www.diving-fish.com/covers/{music.id}.jpg\" } }, { \"type\": \"text\", \"data\": {",
"or (ans.lower() == guess.music['title'].lower()) or (len(ans) >= 5 and ans.lower()",
"\"data\": { \"text\": msg } } ])) except Exception: await",
"int(chart['notes'][0]) slide = int(chart['notes'][2]) hold = int(chart['notes'][1]) touch = int(chart['notes'][3])",
"chart_id = grp[1] line = float(argv[1]) music = total_list.by_id(chart_id) chart:",
"reduce >= 101: raise ValueError await query_chart.send(f'''{music['title']} {level_labels2[level_index]} 分数线 {line}%",
"f\"https://www.diving-fish.com/covers/{music.id}.jpg\" } }, { \"type\": \"text\", \"data\": { \"text\": f\"\\n{'/'.join(music.level)}\"",
"= f.readlines() f.close() for t in tmp: arr = t.strip().split('\\t')",
"例如:分数线 白337 100 命令将返回分数线允许的 TAP GREAT 容错以及 BREAK 50落等价的 TAP",
"Bot, event: Event, state: T_State): mt = event.message_type k =",
"guess_cd_dict[k]: await guess_music.finish(f\"已经猜过啦,下次猜歌会在 {time.strftime('%H:%M', time.localtime(guess_cd_dict[k]))} 可用噢\") return guess = GuessObject()",
"<定数> 查询定数对应的乐曲 定数查歌 <定数下限> <定数上限> 分数线 <难度+歌曲id> <分数线> 详情请输入“分数线 帮助”查看\"\"\")",
"in tmp: arr = t.strip().split('\\t') for i in range(len(arr)): if",
"guess_dict[state[\"k\"]] @guess_music.handle() async def _(bot: Bot, event: Event, state: T_State):",
"f\"{file}\" } }, { \"type\": \"text\", \"data\": { \"text\": f\"艺术家:",
"1)') elif data[1] == 0: await guess_music.send(\"本群已禁用猜歌\") return if k",
"}, { \"type\": \"text\", \"data\": { \"text\": msg } }",
"return asyncio.create_task(bot.send(event, Message([MessageSegment.text(\"答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")]))) del guess_dict[state[\"k\"]] @guess_music.handle()",
"({gid}, 1)') elif data[1] == 0: await guess_music.send(\"本群已禁用猜歌\") return if",
"nonebot.permission import Permission from nonebot.typing import T_State from nonebot.adapters import",
"{ \"text\": msg } } ])) except Exception: await query_chart.send(\"未找到该谱面\")",
"f.readlines() f.close() for t in tmp: arr = t.strip().split('\\t') for",
"Event, state: T_State): regex = \"查歌(.+)\" name = re.match(regex, str(event.get_message())).groups()[0].strip()",
"event.user_id if mt == \"private\" else event.group_id) if mt ==",
"_(bot: Bot, event: Event, state: T_State): regex = \"(.+)是什么歌\" name",
"这首歌\" + guess.guess_options[cycle])) else: asyncio.create_task(bot.send(event, Message([ MessageSegment.text(\"7/7 这首歌封面的一部分是:\"), MessageSegment.image(\"base64://\" +",
"music_data = total_list.filter(ds=ds1) for music in music_data: for i in",
"查询定数对应的乐曲 定数查歌 <定数下限> <定数上限> 分数线 <难度+歌曲id> <分数线> 详情请输入“分数线 帮助”查看\"\"\") def",
"del guess_dict[k] await guess_music_solve.finish(Message([ MessageSegment.reply(event.message_id), MessageSegment.text(\"猜对了,答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")",
"== 4: msg = f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]}",
"else: tp = [\"SD\", \"DX\"] level = res.groups()[2] if res.groups()[1]",
"}} for music in res])) query_chart = on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\") @query_chart.handle() async",
"+= f\"{elem[0]}. {elem[1]} {elem[3]} {elem[4]}({elem[2]})\\n\" await inner_level.finish(s.strip()) spec_rand = on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\")",
"guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中 5 个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\") asyncio.create_task(guess_music_loop(bot, event, state)) guess_music_solve = on_message(priority=20) @guess_music_solve.handle()",
"elif data[1] == 0: await guess_music.send(\"本群已禁用猜歌\") return if k in",
"async def _(bot: Bot, event: Event, state: T_State): await mr.finish(song_txt(total_list.random()))",
"= await bot.get_group_member_list(group_id=event.group_id) for m in group_members: if m['user_id'] ==",
"await guess_music_solve.send(ans + \"|\" + guess.music['id']) if ans == guess.music['id']",
"<reponame>LonelyFantasy/Chiyuki-Bot import math from collections import defaultdict from typing import",
"{chart['charter']} ''' else: msg = f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD:",
"随机一首歌 随个[dx/标准][绿黄红紫白]<难度> 随机一首指定条件的乐曲 查歌<乐曲标题的一部分> 查询符合条件的乐曲 [绿黄红紫白]id<歌曲编号> 查询乐曲信息或谱面信息 <歌曲别名>是什么歌 查询乐曲别名对应的乐曲 定数查歌",
"e: print(e) await spec_rand.finish(\"随机命令错误,请检查语法\") mr = on_regex(r\".*maimai.*什么\") @mr.handle() async def",
"brk * 2500 break_bonus = 0.01 / brk break_50_reduce =",
"== guess.music['title'].lower()) or (len(ans) >= 5 and ans.lower() in guess.music['title'].lower()):",
"'禁用': await c.execute(f'update guess_table set enabled=0 where group_id={event.group_id}') else: await",
"= on_command('b40') @best_40_pic.handle() async def _(bot: Bot, event: Event, state:",
"])) disable_guess_music = on_command('猜歌设置', priority=0) @disable_guess_music.handle() async def _(bot: Bot,",
"await best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\") elif success == 403: await best_40_pic.send(\"该用户禁止了其他人获取数据。\") else: await",
"\"DX\"] level = res.groups()[2] if res.groups()[1] == \"\": music_data =",
"Event, state: T_State): r = \"([绿黄红紫白])(?:id)?([0-9]+)\" argv = str(event.get_message()).strip().split(\" \")",
"= \"([绿黄红紫白]?)id([0-9]+)\" groups = re.match(regex, str(event.get_message())).groups() level_labels = ['绿', '黄',",
"+ guess.music['id']) if ans == guess.music['id'] or (ans.lower() == guess.music['title'].lower())",
"not in su: await disable_guess_music.finish(\"只有管理员可以设置猜歌\") return db = get_driver().config.db c",
"BREAK: {chart['notes'][3]} 谱师: {chart['charter']} ''' else: msg = f'''{level_name[level_index]} {level}({ds})",
"{music['basic_info']['artist']}\\n分类: {music['basic_info']['genre']}\\nBPM: {music['basic_info']['bpm']}\\n版本: {music['basic_info']['from']}\\n难度: {'/'.join(music['level'])}\" } } ])) except Exception:",
"print(event.message_id) if username == \"\": payload = {'qq': str(event.get_user_id())} else:",
"s = f\"今日人品值:{rp}\\n\" for i in range(11): if wm_value[i] ==",
"cycle = state[\"cycle\"] if cycle < 6: asyncio.create_task(bot.send(event, f\"{cycle +",
"guess_cd_dict and time.time() < guess_cd_dict[k]: await guess_music.finish(f\"已经猜过啦,下次猜歌会在 {time.strftime('%H:%M', time.localtime(guess_cd_dict[k]))} 可用噢\")",
"定数查歌 <定数下限> <定数上限> 分数线 <难度+歌曲id> <分数线> 详情请输入“分数线 帮助”查看\"\"\") def song_txt(music:",
"cycle < 6: asyncio.create_task(bot.send(event, f\"{cycle + 1}/7 这首歌\" + guess.guess_options[cycle]))",
"async def _(bot: Bot, event: Event, state: T_State): regex =",
"argv[0] == '帮助': await query_score.send(query_score_mes) elif len(argv) == 2: try:",
"return arg = str(event.get_message()) group_members = await bot.get_group_member_list(group_id=event.group_id) for m",
"logger from nonebot.permission import Permission from nonebot.typing import T_State from",
"try: grp = re.match(r, argv[0]).groups() level_labels = ['绿', '黄', '红',",
"driver = get_driver() @driver.on_startup def _(): logger.info(\"Load help text successfully\")",
"/ total_score:.4f}%), BREAK 50落(一共{brk}个)等价于 {(break_50_reduce / 100):.3f} 个 TAP GREAT(-{break_50_reduce",
"len(chart['notes']) == 5 else 0 brk = int(chart['notes'][-1]) total_score =",
"if k in guess_dict: if k in guess_cd_dict and time.time()",
"import T_State from nonebot.adapters import Event, Bot from nonebot.adapters.cqhttp import",
"\"group\": gid = event.group_id db = get_driver().config.db c = await",
"result_set = inner_level_q(float(argv[0]), float(argv[1])) if len(result_set) > 50: await inner_level.finish(\"数据超出",
"level_labels2 = ['Basic', 'Advanced', 'Expert', 'Master', 'Re:MASTER'] level_index = level_labels.index(grp[0])",
"= [\"SD\"] else: tp = [\"SD\", \"DX\"] level = res.groups()[2]",
"state: T_State): level_labels = ['绿', '黄', '红', '紫', '白'] regex",
"if ds2 is not None: music_data = total_list.filter(ds=(ds1, ds2)) else:",
"async def _(bot: Bot, event: Event, state: T_State): mt =",
"state)) guess_music_solve = on_message(priority=20) @guess_music_solve.handle() async def _(bot: Bot, event:",
"def _(bot: Bot, event: Event, state: T_State): mt = event.message_type",
"== \"sd\" or res.groups()[0] == \"标准\": tp = [\"SD\"] else:",
"f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" await query_chart.send(Message([ { \"type\": \"text\", \"data\": { \"text\": f\"{music['id']}.",
"TAP GREAT 的对应表: GREAT/GOOD/MISS TAP 1/2.5/5 HOLD 2/5/10 SLIDE 3/7.5/15",
"if len(argv) > 2 or len(argv) == 0: await inner_level.finish(\"命令格式为\\n定数查歌",
"data is None: await c.execute(f'insert into guess_table values ({gid}, 1)')",
"Bot, event: Event, state: T_State): qq = int(event.get_user_id()) h2 =",
"# await guess_music_solve.send(ans + \"|\" + guess.music['id']) if ans ==",
"= on_regex(r\".+是什么歌\") @find_song.handle() async def _(bot: Bot, event: Event, state:",
"= state[\"cycle\"] if cycle < 6: asyncio.create_task(bot.send(event, f\"{cycle + 1}/7",
"print(e) await spec_rand.finish(\"随机命令错误,请检查语法\") mr = on_regex(r\".*maimai.*什么\") @mr.handle() async def _(bot:",
"定数查歌 <定数> 查询定数对应的乐曲 定数查歌 <定数下限> <定数上限> 分数线 <难度+歌曲id> <分数线> 详情请输入“分数线",
"== \"标准\": tp = [\"SD\"] else: tp = [\"SD\", \"DX\"]",
"'夜勤', '练底力', '练手法', '打旧框', '干饭', '抓绝赞', '收歌'] jrwm = on_command('今日舞萌',",
"= k state[\"guess_object\"] = guess state[\"cycle\"] = 0 guess_cd_dict[k] =",
"enabled=1 where group_id={event.group_id}') elif arg == '禁用': await c.execute(f'update guess_table",
"\"image\", \"data\": { \"file\": f\"{file}\" } }, { \"type\": \"text\",",
"groups[1] music = total_list.by_id(name) chart = music['charts'][level_index] ds = music['ds'][level_index]",
"str(event.get_message())).groups()[0].strip().lower() if name not in music_aliases: await find_song.finish(\"未找到此歌曲\\n舞萌 DX 歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\")",
"wm_value[i] == 0: s += f'忌 {wm_list[i]}\\n' s += \"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\"",
"T_State): regex = \"查歌(.+)\" name = re.match(regex, str(event.get_message())).groups()[0].strip() if name",
"f\"今日人品值:{rp}\\n\" for i in range(11): if wm_value[i] == 3: s",
"'练底力', '练手法', '打旧框', '干饭', '抓绝赞', '收歌'] jrwm = on_command('今日舞萌', aliases={'今日mai'})",
"on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\") @spec_rand.handle() async def _(bot: Bot, event: Event, state: T_State):",
"== '帮助': await query_score.send(query_score_mes) elif len(argv) == 2: try: grp",
"= ['拼机', '推分', '越级', '下埋', '夜勤', '练底力', '练手法', '打旧框', '干饭',",
"encoding='utf-8')}\") ])) disable_guess_music = on_command('猜歌设置', priority=0) @disable_guess_music.handle() async def _(bot:",
"res])) query_chart = on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\") @query_chart.handle() async def _(bot: Bot, event:",
"guess = guess_dict[k] # await guess_music_solve.send(ans + \"|\" + guess.music['id'])",
"inner_level.finish(\"命令格式为\\n定数查歌 <定数>\\n定数查歌 <定数下限> <定数上限>\") return if len(argv) == 1: result_set",
"else event.group_id) if k not in guess_dict: return ans =",
"await c.execute(f'update guess_table set enabled=0 where group_id={event.group_id}') else: await disable_guess_music.finish(\"请输入",
"]) def inner_level_q(ds1, ds2=None): result_set = [] diff_label = ['Bas',",
"{chart['notes'][2]} TOUCH: {chart['notes'][3]} BREAK: {chart['notes'][4]} 谱师: {chart['charter']} ''' await query_chart.send(Message([",
"2 or len(argv) == 0: await inner_level.finish(\"命令格式为\\n定数查歌 <定数>\\n定数查歌 <定数下限> <定数上限>\")",
"slide = int(chart['notes'][2]) hold = int(chart['notes'][1]) touch = int(chart['notes'][3]) if",
"+= \"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\" music = total_list[h2 % len(total_list)] await jrwm.finish(Message([ {\"type\":",
"level_labels.index(grp[0]) chart_id = grp[1] line = float(argv[1]) music = total_list.by_id(chart_id)",
"+ guess.guess_options[cycle])) else: asyncio.create_task(bot.send(event, Message([ MessageSegment.text(\"7/7 这首歌封面的一部分是:\"), MessageSegment.image(\"base64://\" + str(guess.b64image,",
"await disable_guess_music.finish(\"请输入 猜歌设置 启用/禁用\") await db.commit() await disable_guess_music.finish(\"设置成功\") guess_dict: Dict[Tuple[str,",
"str(event.get_message()).strip() print(event.message_id) if username == \"\": payload = {'qq': str(event.get_user_id())}",
"in range(len(arr)): if arr[i] != \"\": music_aliases[arr[i].lower()].append(arr[0]) find_song = on_regex(r\".+是什么歌\")",
"song_txt(music: Music): return Message([ { \"type\": \"text\", \"data\": { \"text\":",
"async def give_answer(bot: Bot, event: Event, state: T_State): await asyncio.sleep(30)",
"msg = f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]}",
"event: Event, state: T_State): r = \"([绿黄红紫白])(?:id)?([0-9]+)\" argv = str(event.get_message()).strip().split(\"",
"event: Event, state: T_State): await asyncio.sleep(30) guess: GuessObject = state[\"guess_object\"]",
"res = re.match(regex, str(event.get_message()).lower()) try: if res.groups()[0] == \"dx\": tp",
"asyncio.create_task(give_answer(bot, event, state)) return state[\"cycle\"] += 1 asyncio.create_task(guess_music_loop(bot, event, state))",
"on_regex(r\"^查歌.+\") @search_music.handle() async def _(bot: Bot, event: Event, state: T_State):",
"% 100 wm_value = [] for i in range(11): wm_value.append(h",
"!= \"group\": return arg = str(event.get_message()) group_members = await bot.get_group_member_list(group_id=event.group_id)",
"su: await disable_guess_music.finish(\"只有管理员可以设置猜歌\") return db = get_driver().config.db c = await",
"music['charts'][level_index] tap = int(chart['notes'][0]) slide = int(chart['notes'][2]) hold = int(chart['notes'][1])",
"\"file\": f\"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}\" } }]) @query_score.handle() async def _(bot: Bot,",
"await query_chart.send(Message([ { \"type\": \"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\"",
"'打旧框', '干饭', '抓绝赞', '收歌'] jrwm = on_command('今日舞萌', aliases={'今日mai'}) @jrwm.handle() async",
"import on_command, on_message, on_notice, on_regex, get_driver from nonebot.log import logger",
"\"text\": f\"{music.id}. {music.title}\\n\" } }, { \"type\": \"image\", \"data\": {",
"MessageSegment.image(f\"base64://{str(image_to_base64(img), encoding='utf-8')}\") ])) disable_guess_music = on_command('猜歌设置', priority=0) @disable_guess_music.handle() async def",
"\"text\", \"data\": {\"text\": s}} ] + song_txt(music))) music_aliases = defaultdict(list)",
"find_song = on_regex(r\".+是什么歌\") @find_song.handle() async def _(bot: Bot, event: Event,",
"= on_message(priority=20) @guess_music_solve.handle() async def _(bot: Bot, event: Event, state:",
"on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\") @query_chart.handle() async def _(bot: Bot, event: Event, state: T_State):",
"state: T_State): await mr.finish(song_txt(total_list.random())) search_music = on_regex(r\"^查歌.+\") @search_music.handle() async def",
"= time.time() + 600 await guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中 5 个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\") asyncio.create_task(guess_music_loop(bot, event,",
"f\"{elem[0]}. {elem[1]} {elem[3]} {elem[4]}({elem[2]})\\n\" await inner_level.finish(s.strip()) spec_rand = on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\") @spec_rand.handle()",
"= '''此功能为查找某首歌分数线设计。 命令格式:分数线 <难度+歌曲id> <分数线> 例如:分数线 白337 100 命令将返回分数线允许的 TAP",
"f\"{music['id']}. {music['title']}\\n\" } }, { \"type\": \"image\", \"data\": { \"file\":",
"== 0: s += f'忌 {wm_list[i]}\\n' s += \"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\" music",
"= f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} TOUCH:",
"if arg == '启用': await c.execute(f'update guess_table set enabled=1 where",
"{music['title']}\\n\" }} for music in res])) query_chart = on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\") @query_chart.handle()",
"\"data\": {\"text\": s}} ] + song_txt(music))) music_aliases = defaultdict(list) f",
"rp = h % 100 wm_value = [] for i",
"or len(argv) == 0: await inner_level.finish(\"命令格式为\\n定数查歌 <定数>\\n定数查歌 <定数下限> <定数上限>\") return",
"await best_40_pic.send(\"该用户禁止了其他人获取数据。\") else: await best_40_pic.send(Message([ MessageSegment.reply(event.message_id), MessageSegment.image(f\"base64://{str(image_to_base64(img), encoding='utf-8')}\") ])) disable_guess_music",
"else: music_data = total_list.filter(level=level, diff=['绿黄红紫白'.index(res.groups()[1])], type=tp) await spec_rand.send(song_txt(music_data.random())) except Exception",
"group_members: if m['user_id'] == event.user_id: break su = get_driver().config.superusers if",
"await disable_guess_music.finish(\"设置成功\") guess_dict: Dict[Tuple[str, str], GuessObject] = {} guess_cd_dict: Dict[Tuple[str,",
"group_id={event.group_id}') elif arg == '禁用': await c.execute(f'update guess_table set enabled=0",
"\"\": music_data = total_list.filter(level=level, type=tp) else: music_data = total_list.filter(level=level, diff=['绿黄红紫白'.index(res.groups()[1])],",
"def _(): logger.info(\"Load help text successfully\") help_text: dict = get_driver().config.help_text",
"result_set inner_level = on_command('inner_level ', aliases={'定数查歌 '}) @inner_level.handle() async def",
"<分数线> 详情请输入“分数线 帮助”查看\"\"\") def song_txt(music: Music): return Message([ { \"type\":",
"state: T_State): await asyncio.sleep(10) guess: GuessObject = state[\"guess_object\"] if guess.is_end:",
"}\") query_score = on_command('分数线') query_score_text = '''此功能为查找某首歌分数线设计。 命令格式:分数线 <难度+歌曲id> <分数线>",
"or reduce >= 101: raise ValueError await query_chart.send(f'''{music['title']} {level_labels2[level_index]} 分数线",
"music.diff: result_set.append((music['id'], music['title'], music['ds'][i], diff_label[i], music['level'][i])) return result_set inner_level =",
"def _(bot: Bot, event: Event, state: T_State): regex = \"查歌(.+)\"",
"guess_music_loop(bot: Bot, event: Event, state: T_State): await asyncio.sleep(10) guess: GuessObject",
"return result_set inner_level = on_command('inner_level ', aliases={'定数查歌 '}) @inner_level.handle() async",
"f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} TOUCH: {chart['notes'][3]}",
"如果已经过了 200 秒则自动结束上一次 del guess_dict[k] else: await guess_music.send(\"当前已有正在进行的猜歌\") return whitelists",
"best_40_pic.send(Message([ MessageSegment.reply(event.message_id), MessageSegment.image(f\"base64://{str(image_to_base64(img), encoding='utf-8')}\") ])) disable_guess_music = on_command('猜歌设置', priority=0) @disable_guess_music.handle()",
"1500 + hold * 1000 + touch * 500 +",
"Event, state: T_State): regex = \"(.+)是什么歌\" name = re.match(regex, str(event.get_message())).groups()[0].strip().lower()",
"except Exception as e: print(e) await spec_rand.finish(\"随机命令错误,请检查语法\") mr = on_regex(r\".*maimai.*什么\")",
"\"group\": return arg = str(event.get_message()) group_members = await bot.get_group_member_list(group_id=event.group_id) for",
"\"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\" res = re.match(regex, str(event.get_message()).lower()) try: if res.groups()[0] == \"dx\":",
"range(11): wm_value.append(h & 3) h >>= 2 s = f\"今日人品值:{rp}\\n\"",
"= on_command('分数线') query_score_text = '''此功能为查找某首歌分数线设计。 命令格式:分数线 <难度+歌曲id> <分数线> 例如:分数线 白337",
"for i in range(len(arr)): if arr[i] != \"\": music_aliases[arr[i].lower()].append(arr[0]) find_song",
"\"([绿黄红紫白]?)id([0-9]+)\" groups = re.match(regex, str(event.get_message())).groups() level_labels = ['绿', '黄', '红',",
"= res.groups()[2] if res.groups()[1] == \"\": music_data = total_list.filter(level=level, type=tp)",
"\"([绿黄红紫白])(?:id)?([0-9]+)\" argv = str(event.get_message()).strip().split(\" \") if len(argv) == 1 and",
"arr[i] != \"\": music_aliases[arr[i].lower()].append(arr[0]) find_song = on_regex(r\".+是什么歌\") @find_song.handle() async def",
"event.group_id) if k not in guess_dict: return ans = str(event.get_message())",
"{chart['charter']} ''' await query_chart.send(Message([ { \"type\": \"text\", \"data\": { \"text\":",
"命令将返回分数线允许的 TAP GREAT 容错以及 BREAK 50落等价的 TAP GREAT 数。 以下为",
"(mt, event.user_id if mt == \"private\" else event.group_id) if k",
"Bot, event: Event): if event.message_type != \"group\": return arg =",
"name = groups[1] music = total_list.by_id(name) chart = music['charts'][level_index] ds",
"= total_list.filter(level=level, diff=['绿黄红紫白'.index(res.groups()[1])], type=tp) await spec_rand.send(song_txt(music_data.random())) except Exception as e:",
"state[\"cycle\"] if cycle < 6: asyncio.create_task(bot.send(event, f\"{cycle + 1}/7 这首歌\"",
"== 400: await best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\") elif success == 403: await best_40_pic.send(\"该用户禁止了其他人获取数据。\")",
"[] for i in range(11): wm_value.append(h & 3) h >>=",
"await find_song.finish(\"未找到此歌曲\\n舞萌 DX 歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\") return result_set = music_aliases[name] if len(result_set)",
"{level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} TOUCH: {chart['notes'][3]} BREAK:",
"= \"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\" res = re.match(regex, str(event.get_message()).lower()) try: if res.groups()[0] ==",
"TAP GREAT 数。 以下为 TAP GREAT 的对应表: GREAT/GOOD/MISS TAP 1/2.5/5",
"total_list[h2 % len(total_list)] await jrwm.finish(Message([ {\"type\": \"text\", \"data\": {\"text\": s}}",
"await guess_music.send(\"当前已有正在进行的猜歌\") return whitelists = get_driver().config.whitelists if not (mt ==",
"async def _(bot: Bot, event: Event): if event.message_type != \"group\":",
"result_set.append((music['id'], music['title'], music['ds'][i], diff_label[i], music['level'][i])) return result_set inner_level = on_command('inner_level",
"guess: GuessObject = state[\"guess_object\"] if guess.is_end: return cycle = state[\"cycle\"]",
"['绿', '黄', '红', '紫', '白'] level_labels2 = ['Basic', 'Advanced', 'Expert',",
"len(total_list)] await jrwm.finish(Message([ {\"type\": \"text\", \"data\": {\"text\": s}} ] +",
"+ slide * 1500 + hold * 1000 + touch",
"> 2 or len(argv) == 0: await inner_level.finish(\"命令格式为\\n定数查歌 <定数>\\n定数查歌 <定数下限>",
"search_music.finish(Message([ {\"type\": \"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" }} for",
"1/2.5/5 BREAK 5/12.5/25(外加200落)''' query_score_mes = Message([{ \"type\": \"image\", \"data\": {",
"if len(chart['notes']) == 4: msg = f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]}",
"import json import random import time import re from urllib",
"GroupMessageEvent, PrivateMessageEvent from src.libraries.maimaidx_guess import GuessObject from src.libraries.tool import hash",
"f.close() for t in tmp: arr = t.strip().split('\\t') for i",
"'ReM'] if ds2 is not None: music_data = total_list.filter(ds=(ds1, ds2))",
"SLIDE: {chart['notes'][2]} TOUCH: {chart['notes'][3]} BREAK: {chart['notes'][4]} 谱师: {chart['charter']} ''' await",
"Event, state: T_State): await asyncio.sleep(10) guess: GuessObject = state[\"guess_object\"] if",
"\"text\", \"data\": { \"text\": f\"\\n{'/'.join(music.level)}\" } } ]) def inner_level_q(ds1,",
"tmp: arr = t.strip().split('\\t') for i in range(len(arr)): if arr[i]",
"disable_guess_music.finish(\"只有管理员可以设置猜歌\") return db = get_driver().config.db c = await db.cursor() if",
"查询乐曲别名对应的乐曲 定数查歌 <定数> 查询定数对应的乐曲 定数查歌 <定数下限> <定数上限> 分数线 <难度+歌曲id> <分数线>",
"guess_music.send(\"当前已有正在进行的猜歌\") return whitelists = get_driver().config.whitelists if not (mt == \"group\"",
"guess_music_solve = on_message(priority=20) @guess_music_solve.handle() async def _(bot: Bot, event: Event,",
"inner_level.finish(s.strip()) spec_rand = on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\") @spec_rand.handle() async def _(bot: Bot, event:",
"import defaultdict from typing import List, Dict, Any from nonebot",
"str(event.get_message())).groups()[0].strip() if name == \"\": return res = total_list.filter(title_search=name) await",
"* 1500 + hold * 1000 + touch * 500",
"MASTER'] name = groups[1] music = total_list.by_id(name) chart = music['charts'][level_index]",
"guess state[\"cycle\"] = 0 guess_cd_dict[k] = time.time() + 600 await",
"def _(bot: Bot, event: Event, state: T_State): regex = \"([绿黄红紫白]?)id([0-9]+)\"",
"== \"\": music_data = total_list.filter(level=level, type=tp) else: music_data = total_list.filter(level=level,",
"h = h2 rp = h % 100 wm_value =",
"= 0.01 / brk break_50_reduce = total_score * break_bonus /",
"music_data = total_list.filter(level=level, type=tp) else: music_data = total_list.filter(level=level, diff=['绿黄红紫白'.index(res.groups()[1])], type=tp)",
"defaultdict from typing import List, Dict, Any from nonebot import",
"_(): logger.info(\"Load help text successfully\") help_text: dict = get_driver().config.help_text help_text['mai']",
"music in res])) query_chart = on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\") @query_chart.handle() async def _(bot:",
"and time.time() < guess_cd_dict[k]: await guess_music.finish(f\"已经猜过啦,下次猜歌会在 {time.strftime('%H:%M', time.localtime(guess_cd_dict[k]))} 可用噢\") return",
"\"\": payload = {'qq': str(event.get_user_id())} else: payload = {'username': username}",
"'\\n'.join(result_set) await find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{ s }\") query_score = on_command('分数线') query_score_text =",
"await query_chart.send(\"未找到该谱面\") else: name = groups[1] music = total_list.by_id(name) try:",
"'Expert', 'Master', 'Re: MASTER'] name = groups[1] music = total_list.by_id(name)",
"\"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" }} for music in",
"music = total_list.by_id(name) try: file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" await query_chart.send(Message([ {",
"if guess.is_end: return asyncio.create_task(bot.send(event, Message([MessageSegment.text(\"答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")]))) del",
"in group_members: if m['user_id'] == event.user_id: break su = get_driver().config.superusers",
"h2 rp = h % 100 wm_value = [] for",
"100):.3f} 个 TAP GREAT(-{break_50_reduce / total_score * 100:.4f}%)''') except Exception:",
"T_State): level_labels = ['绿', '黄', '红', '紫', '白'] regex =",
"0: await inner_level.finish(\"命令格式为\\n定数查歌 <定数>\\n定数查歌 <定数下限> <定数上限>\") return if len(argv) ==",
"\") if len(argv) > 2 or len(argv) == 0: await",
"except Exception: await query_chart.send(\"未找到该乐曲\") wm_list = ['拼机', '推分', '越级', '下埋',",
"event: Event, state: T_State): mt = event.message_type k = (mt,",
"\"您要找的是不是\"}}] + song_txt(music))) else: s = '\\n'.join(result_set) await find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{ s",
"Bot from nonebot.adapters.cqhttp import Message, MessageSegment, GroupMessageEvent, PrivateMessageEvent from src.libraries.maimaidx_guess",
"Any from nonebot import on_command, on_message, on_notice, on_regex, get_driver from",
"= 500 * tap + slide * 1500 + hold",
"MessageSegment.reply(event.message_id), MessageSegment.image(f\"base64://{str(image_to_base64(img), encoding='utf-8')}\") ])) disable_guess_music = on_command('猜歌设置', priority=0) @disable_guess_music.handle() async",
"query_chart.send(\"未找到该乐曲\") wm_list = ['拼机', '推分', '越级', '下埋', '夜勤', '练底力', '练手法',",
"TAP 1/2.5/5 HOLD 2/5/10 SLIDE 3/7.5/15 TOUCH 1/2.5/5 BREAK 5/12.5/25(外加200落)'''",
"ans.lower() in guess.music['title'].lower()): guess.is_end = True del guess_dict[k] await guess_music_solve.finish(Message([",
"return db = get_driver().config.db c = await db.cursor() if arg",
"ds2)) else: music_data = total_list.filter(ds=ds1) for music in music_data: for",
"import parse driver = get_driver() @driver.on_startup def _(): logger.info(\"Load help",
"1 and argv[0] == '帮助': await query_score.send(query_score_mes) elif len(argv) ==",
"= on_command('猜歌', priority=0) async def guess_music_loop(bot: Bot, event: Event, state:",
"grp = re.match(r, argv[0]).groups() level_labels = ['绿', '黄', '红', '紫',",
"!= 'owner' and m['role'] != 'admin' and str(m['user_id']) not in",
"\"data\": { \"file\": f\"{file}\" } }, { \"type\": \"text\", \"data\":",
"_(bot: Bot, event: Event, state: T_State): argv = str(event.get_message()).strip().split(\" \")",
"\"dx\": tp = [\"DX\"] elif res.groups()[0] == \"sd\" or res.groups()[0]",
"from nonebot.permission import Permission from nonebot.typing import T_State from nonebot.adapters",
"= ['绿', '黄', '红', '紫', '白'] level_labels2 = ['Basic', 'Advanced',",
"'帮助': await query_score.send(query_score_mes) elif len(argv) == 2: try: grp =",
"{(total_score * reduce / 10000):.2f}(每个-{10000 / total_score:.4f}%), BREAK 50落(一共{brk}个)等价于 {(break_50_reduce",
"from guess_table where group_id={gid}\") data = await c.fetchone() if data",
"success = await generate(payload) if success == 400: await best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\")",
"= 0 guess_cd_dict[k] = time.time() + 600 await guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中 5",
"from typing import List, Dict, Any from nonebot import on_command,",
"await inner_level.finish(\"命令格式为\\n定数查歌 <定数>\\n定数查歌 <定数下限> <定数上限>\") return if len(argv) == 1:",
"range(len(arr)): if arr[i] != \"\": music_aliases[arr[i].lower()].append(arr[0]) find_song = on_regex(r\".+是什么歌\") @find_song.handle()",
"f\"{cycle + 1}/7 这首歌\" + guess.guess_options[cycle])) else: asyncio.create_task(bot.send(event, Message([ MessageSegment.text(\"7/7",
"= f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} BREAK:",
"\"type\": \"text\", \"data\": { \"text\": f\"{music.id}. {music.title}\\n\" } }, {",
"_(bot: Bot, event: Event, state: T_State): await mr.finish(song_txt(total_list.random())) search_music =",
"\"text\": msg } } ])) except Exception: await query_chart.send(\"未找到该谱面\") else:",
"'抓绝赞', '收歌'] jrwm = on_command('今日舞萌', aliases={'今日mai'}) @jrwm.handle() async def _(bot:",
"{ \"type\": \"text\", \"data\": { \"text\": f\"艺术家: {music['basic_info']['artist']}\\n分类: {music['basic_info']['genre']}\\nBPM: {music['basic_info']['bpm']}\\n版本:",
"guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\") return if k in guess_cd_dict and time.time() < guess_cd_dict[k]:",
"MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")]))) del guess_dict[state[\"k\"]] @guess_music.handle() async def _(bot: Bot, event: Event,",
"= t.strip().split('\\t') for i in range(len(arr)): if arr[i] != \"\":",
"Event, state: T_State): level_labels = ['绿', '黄', '红', '紫', '白']",
"music = total_list.by_id(name) chart = music['charts'][level_index] ds = music['ds'][level_index] level",
"for t in tmp: arr = t.strip().split('\\t') for i in",
"\"\"\"桜千雪です、よろしく。 可用命令如下: 今日舞萌 查看今天的舞萌运势 XXXmaimaiXXX什么 随机一首歌 随个[dx/标准][绿黄红紫白]<难度> 随机一首指定条件的乐曲 查歌<乐曲标题的一部分> 查询符合条件的乐曲",
"on_command('b40') @best_40_pic.handle() async def _(bot: Bot, event: Event, state: T_State):",
"search_music = on_regex(r\"^查歌.+\") @search_music.handle() async def _(bot: Bot, event: Event,",
"\"private\" else event.group_id) if mt == \"group\": gid = event.group_id",
"event.group_id) if mt == \"group\": gid = event.group_id db =",
"10000):.2f}(每个-{10000 / total_score:.4f}%), BREAK 50落(一共{brk}个)等价于 {(break_50_reduce / 100):.3f} 个 TAP",
"/ 4 reduce = 101 - line if reduce <=",
"秒则自动结束上一次 del guess_dict[k] else: await guess_music.send(\"当前已有正在进行的猜歌\") return whitelists = get_driver().config.whitelists",
"guess_dict[k] await guess_music_solve.finish(Message([ MessageSegment.reply(event.message_id), MessageSegment.text(\"猜对了,答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\") ]))",
"inner_level_q(float(argv[0]), float(argv[1])) if len(result_set) > 50: await inner_level.finish(\"数据超出 50 条,请尝试缩小查询范围\")",
"if res.groups()[1] == \"\": music_data = total_list.filter(level=level, type=tp) else: music_data",
"T_State): argv = str(event.get_message()).strip().split(\" \") if len(argv) > 2 or",
"<定数下限> <定数上限> 分数线 <难度+歌曲id> <分数线> 详情请输入“分数线 帮助”查看\"\"\") def song_txt(music: Music):",
"= str(event.get_message()).strip() print(event.message_id) if username == \"\": payload = {'qq':",
"T_State): await asyncio.sleep(30) guess: GuessObject = state[\"guess_object\"] if guess.is_end: return",
"state: T_State): argv = str(event.get_message()).strip().split(\" \") if len(argv) > 2",
"GREAT 的对应表: GREAT/GOOD/MISS TAP 1/2.5/5 HOLD 2/5/10 SLIDE 3/7.5/15 TOUCH",
"on_notice, on_regex, get_driver from nonebot.log import logger from nonebot.permission import",
"= get_driver() @driver.on_startup def _(): logger.info(\"Load help text successfully\") help_text:",
"on_command('inner_level ', aliases={'定数查歌 '}) @inner_level.handle() async def _(bot: Bot, event:",
"gid = event.group_id db = get_driver().config.db c = await db.cursor()",
"groups = re.match(regex, str(event.get_message())).groups() level_labels = ['绿', '黄', '红', '紫',",
"chart = music['charts'][level_index] ds = music['ds'][level_index] level = music['level'][level_index] file",
"= ['绿', '黄', '红', '紫', '白'] regex = \"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\" res",
"guess.music['title'].lower()): guess.is_end = True del guess_dict[k] await guess_music_solve.finish(Message([ MessageSegment.reply(event.message_id), MessageSegment.text(\"猜对了,答案是:\"",
"except Exception: await query_chart.send(\"格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息\") best_40_pic = on_command('b40') @best_40_pic.handle() async",
"state[\"cycle\"] += 1 asyncio.create_task(guess_music_loop(bot, event, state)) async def give_answer(bot: Bot,",
"帮助”以查看帮助信息\") best_40_pic = on_command('b40') @best_40_pic.handle() async def _(bot: Bot, event:",
"if len(result_set) > 50: await inner_level.finish(\"数据超出 50 条,请尝试缩小查询范围\") return s",
"['拼机', '推分', '越级', '下埋', '夜勤', '练底力', '练手法', '打旧框', '干饭', '抓绝赞',",
"{elem[1]} {elem[3]} {elem[4]}({elem[2]})\\n\" await inner_level.finish(s.strip()) spec_rand = on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\") @spec_rand.handle() async",
"None: music_data = total_list.filter(ds=(ds1, ds2)) else: music_data = total_list.filter(ds=ds1) for",
"from src.libraries.maimaidx_guess import GuessObject from src.libraries.tool import hash from src.libraries.maimaidx_music",
"= level_labels.index(grp[0]) chart_id = grp[1] line = float(argv[1]) music =",
"tmp = f.readlines() f.close() for t in tmp: arr =",
"asyncio.create_task(bot.send(event, Message([ MessageSegment.text(\"7/7 这首歌封面的一部分是:\"), MessageSegment.image(\"base64://\" + str(guess.b64image, encoding=\"utf-8\")), MessageSegment.text(\"答案将在 30",
"_(bot: Bot, event: Event, state: T_State): qq = int(event.get_user_id()) h2",
"await jrwm.finish(Message([ {\"type\": \"text\", \"data\": {\"text\": s}} ] + song_txt(music)))",
"else: msg = f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE:",
"state: T_State): qq = int(event.get_user_id()) h2 = hash(qq) h =",
"'Advanced', 'Expert', 'Master', 'Re: MASTER'] name = groups[1] music =",
"帮助”查看\"\"\") def song_txt(music: Music): return Message([ { \"type\": \"text\", \"data\":",
"允许的最多 TAP GREAT 数量为 {(total_score * reduce / 10000):.2f}(每个-{10000 /",
"del guess_dict[k] else: await guess_music.send(\"当前已有正在进行的猜歌\") return whitelists = get_driver().config.whitelists if",
"+= 1 asyncio.create_task(guess_music_loop(bot, event, state)) async def give_answer(bot: Bot, event:",
"if username == \"\": payload = {'qq': str(event.get_user_id())} else: payload",
"# 如果已经过了 200 秒则自动结束上一次 del guess_dict[k] else: await guess_music.send(\"当前已有正在进行的猜歌\") return",
"T_State): r = \"([绿黄红紫白])(?:id)?([0-9]+)\" argv = str(event.get_message()).strip().split(\" \") if len(argv)",
"await find_song.finish(Message([{\"type\": \"text\", \"data\": {\"text\": \"您要找的是不是\"}}] + song_txt(music))) else: s",
"return result_set = music_aliases[name] if len(result_set) == 1: music =",
"music in music_data: for i in music.diff: result_set.append((music['id'], music['title'], music['ds'][i],",
"= on_command('猜歌设置', priority=0) @disable_guess_music.handle() async def _(bot: Bot, event: Event):",
"[绿黄红紫白]id<歌曲编号> 查询乐曲信息或谱面信息 <歌曲别名>是什么歌 查询乐曲别名对应的乐曲 定数查歌 <定数> 查询定数对应的乐曲 定数查歌 <定数下限> <定数上限>",
"= on_command('今日舞萌', aliases={'今日mai'}) @jrwm.handle() async def _(bot: Bot, event: Event,",
"查询符合条件的乐曲 [绿黄红紫白]id<歌曲编号> 查询乐曲信息或谱面信息 <歌曲别名>是什么歌 查询乐曲别名对应的乐曲 定数查歌 <定数> 查询定数对应的乐曲 定数查歌 <定数下限>",
"{'username': username} img, success = await generate(payload) if success ==",
"{ \"file\": f\"{file}\" } }, { \"type\": \"text\", \"data\": {",
"1000 + touch * 500 + brk * 2500 break_bonus",
"regex = \"([绿黄红紫白]?)id([0-9]+)\" groups = re.match(regex, str(event.get_message())).groups() level_labels = ['绿',",
"{chart['notes'][3]} BREAK: {chart['notes'][4]} 谱师: {chart['charter']} ''' await query_chart.send(Message([ { \"type\":",
"if reduce <= 0 or reduce >= 101: raise ValueError",
"= int(event.get_user_id()) h2 = hash(qq) h = h2 rp =",
"= \"查歌(.+)\" name = re.match(regex, str(event.get_message())).groups()[0].strip() if name == \"\":",
"hash(qq) h = h2 rp = h % 100 wm_value",
"{ \"text\": f\"{music['id']}. {music['title']}\\n\" } }, { \"type\": \"image\", \"data\":",
"c.execute(f'insert into guess_table values ({gid}, 1)') elif data[1] == 0:",
"await inner_level.finish(s.strip()) spec_rand = on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\") @spec_rand.handle() async def _(bot: Bot,",
"res.groups()[0] == \"sd\" or res.groups()[0] == \"标准\": tp = [\"SD\"]",
"float(argv[1])) if len(result_set) > 50: await inner_level.finish(\"数据超出 50 条,请尝试缩小查询范围\") return",
"reduce <= 0 or reduce >= 101: raise ValueError await",
"@disable_guess_music.handle() async def _(bot: Bot, event: Event): if event.message_type !=",
"on_command, on_message, on_notice, on_regex, get_driver from nonebot.log import logger from",
"level_labels = ['绿', '黄', '红', '紫', '白'] if groups[0] !=",
"mt = event.message_type k = (mt, event.user_id if mt ==",
"guess_dict: if k in guess_cd_dict and time.time() > guess_cd_dict[k] -",
"== 1: music = total_list.by_title(result_set[0]) await find_song.finish(Message([{\"type\": \"text\", \"data\": {\"text\":",
"music_aliases[name] if len(result_set) == 1: music = total_list.by_title(result_set[0]) await find_song.finish(Message([{\"type\":",
"type=tp) await spec_rand.send(song_txt(music_data.random())) except Exception as e: print(e) await spec_rand.finish(\"随机命令错误,请检查语法\")",
"Dict[Tuple[str, str], float] = {} guess_music = on_command('猜歌', priority=0) async",
"wm_value.append(h & 3) h >>= 2 s = f\"今日人品值:{rp}\\n\" for",
"\") if len(argv) == 1 and argv[0] == '帮助': await",
"= guess state[\"k\"] = k state[\"guess_object\"] = guess state[\"cycle\"] =",
"str(m['user_id']) not in su: await disable_guess_music.finish(\"只有管理员可以设置猜歌\") return db = get_driver().config.db",
"event: Event, state: T_State): regex = \"(.+)是什么歌\" name = re.match(regex,",
"if mt == \"private\" else event.group_id) if mt == \"group\":",
"success == 400: await best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\") elif success == 403: await",
"music['charts'][level_index] ds = music['ds'][level_index] level = music['level'][level_index] file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\"",
"successfully\") help_text: dict = get_driver().config.help_text help_text['mai'] = ('查看舞萌相关功能', \"\"\"桜千雪です、よろしく。 可用命令如下:",
"len(argv) == 1: result_set = inner_level_q(float(argv[0])) else: result_set = inner_level_q(float(argv[0]),",
"> guess_cd_dict[k] - 400: # 如果已经过了 200 秒则自动结束上一次 del guess_dict[k]",
"import math from collections import defaultdict from typing import List,",
"& 3) h >>= 2 s = f\"今日人品值:{rp}\\n\" for i",
"f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} BREAK: {chart['notes'][3]}",
"guess_cd_dict[k] = time.time() + 600 await guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中 5 个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\") asyncio.create_task(guess_music_loop(bot,",
"nonebot import on_command, on_message, on_notice, on_regex, get_driver from nonebot.log import",
"= music_aliases[name] if len(result_set) == 1: music = total_list.by_title(result_set[0]) await",
"guess.music['title'].lower()) or (len(ans) >= 5 and ans.lower() in guess.music['title'].lower()): guess.is_end",
"= GuessObject() guess_dict[k] = guess state[\"k\"] = k state[\"guess_object\"] =",
"403: await best_40_pic.send(\"该用户禁止了其他人获取数据。\") else: await best_40_pic.send(Message([ MessageSegment.reply(event.message_id), MessageSegment.image(f\"base64://{str(image_to_base64(img), encoding='utf-8')}\") ]))",
"or res.groups()[0] == \"标准\": tp = [\"SD\"] else: tp =",
"await generate(payload) if success == 400: await best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\") elif success",
"+ 600 await guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中 5 个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\") asyncio.create_task(guess_music_loop(bot, event, state)) guess_music_solve",
"event: Event, state: T_State): regex = \"([绿黄红紫白]?)id([0-9]+)\" groups = re.match(regex,",
"range(11): if wm_value[i] == 3: s += f'宜 {wm_list[i]}\\n' elif",
"import generate import requests import json import random import time",
"Exception: await query_chart.send(\"格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息\") best_40_pic = on_command('b40') @best_40_pic.handle() async def",
"= \"([绿黄红紫白])(?:id)?([0-9]+)\" argv = str(event.get_message()).strip().split(\" \") if len(argv) == 1",
"k not in guess_dict: return ans = str(event.get_message()) guess =",
"Bot, event: Event, state: T_State): regex = \"查歌(.+)\" name =",
"await search_music.finish(Message([ {\"type\": \"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" }}",
"h % 100 wm_value = [] for i in range(11):",
"\"text\": f\"{music['id']}. {music['title']}\\n\" }} for music in res])) query_chart =",
"total_list.filter(level=level, type=tp) else: music_data = total_list.filter(level=level, diff=['绿黄红紫白'.index(res.groups()[1])], type=tp) await spec_rand.send(song_txt(music_data.random()))",
"== \"\": return res = total_list.filter(title_search=name) await search_music.finish(Message([ {\"type\": \"text\",",
"get_driver().config.db c = await db.cursor() if arg == '启用': await",
"re from urllib import parse driver = get_driver() @driver.on_startup def",
"grp[1] line = float(argv[1]) music = total_list.by_id(chart_id) chart: Dict[Any] =",
"total_list.by_id(name) chart = music['charts'][level_index] ds = music['ds'][level_index] level = music['level'][level_index]",
"if k in guess_cd_dict and time.time() > guess_cd_dict[k] - 400:",
"50落(一共{brk}个)等价于 {(break_50_reduce / 100):.3f} 个 TAP GREAT(-{break_50_reduce / total_score *",
"parse driver = get_driver() @driver.on_startup def _(): logger.info(\"Load help text",
"'干饭', '抓绝赞', '收歌'] jrwm = on_command('今日舞萌', aliases={'今日mai'}) @jrwm.handle() async def",
"not in guess_dict: return ans = str(event.get_message()) guess = guess_dict[k]",
"guess.guess_options[cycle])) else: asyncio.create_task(bot.send(event, Message([ MessageSegment.text(\"7/7 这首歌封面的一部分是:\"), MessageSegment.image(\"base64://\" + str(guess.b64image, encoding=\"utf-8\")),",
"Event, state: T_State): argv = str(event.get_message()).strip().split(\" \") if len(argv) >",
"= ['Bas', 'Adv', 'Exp', 'Mst', 'ReM'] if ds2 is not",
"m['user_id'] == event.user_id: break su = get_driver().config.superusers if m['role'] !=",
"len(result_set) == 1: music = total_list.by_title(result_set[0]) await find_song.finish(Message([{\"type\": \"text\", \"data\":",
"= total_list[h2 % len(total_list)] await jrwm.finish(Message([ {\"type\": \"text\", \"data\": {\"text\":",
"\"查歌(.+)\" name = re.match(regex, str(event.get_message())).groups()[0].strip() if name == \"\": return",
"1/2.5/5 HOLD 2/5/10 SLIDE 3/7.5/15 TOUCH 1/2.5/5 BREAK 5/12.5/25(外加200落)''' query_score_mes",
"else: await best_40_pic.send(Message([ MessageSegment.reply(event.message_id), MessageSegment.image(f\"base64://{str(image_to_base64(img), encoding='utf-8')}\") ])) disable_guess_music = on_command('猜歌设置',",
"Exception: await query_chart.send(\"未找到该谱面\") else: name = groups[1] music = total_list.by_id(name)",
"in guess_cd_dict and time.time() < guess_cd_dict[k]: await guess_music.finish(f\"已经猜过啦,下次猜歌会在 {time.strftime('%H:%M', time.localtime(guess_cd_dict[k]))}",
"state: T_State): username = str(event.get_message()).strip() print(event.message_id) if username == \"\":",
"help_text['mai'] = ('查看舞萌相关功能', \"\"\"桜千雪です、よろしく。 可用命令如下: 今日舞萌 查看今天的舞萌运势 XXXmaimaiXXX什么 随机一首歌 随个[dx/标准][绿黄红紫白]<难度>",
"str(event.get_message()) guess = guess_dict[k] # await guess_music_solve.send(ans + \"|\" +",
"in result_set: s += f\"{elem[0]}. {elem[1]} {elem[3]} {elem[4]}({elem[2]})\\n\" await inner_level.finish(s.strip())",
"<定数上限>\") return if len(argv) == 1: result_set = inner_level_q(float(argv[0])) else:",
"Dict[Any] = music['charts'][level_index] tap = int(chart['notes'][0]) slide = int(chart['notes'][2]) hold",
"len(argv) == 0: await inner_level.finish(\"命令格式为\\n定数查歌 <定数>\\n定数查歌 <定数下限> <定数上限>\") return if",
"into guess_table values ({gid}, 1)') elif data[1] == 0: await",
"分数线 <难度+歌曲id> <分数线> 详情请输入“分数线 帮助”查看\"\"\") def song_txt(music: Music): return Message([",
"s += f'宜 {wm_list[i]}\\n' elif wm_value[i] == 0: s +=",
"return cycle = state[\"cycle\"] if cycle < 6: asyncio.create_task(bot.send(event, f\"{cycle",
"argv = str(event.get_message()).strip().split(\" \") if len(argv) == 1 and argv[0]",
"state: T_State): mt = event.message_type k = (mt, event.user_id if",
"\"type\": \"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" } }, {",
"re.match(regex, str(event.get_message())).groups() level_labels = ['绿', '黄', '红', '紫', '白'] if",
"\"private\" else event.group_id) if k not in guess_dict: return ans",
"3) h >>= 2 s = f\"今日人品值:{rp}\\n\" for i in",
"from nonebot.adapters import Event, Bot from nonebot.adapters.cqhttp import Message, MessageSegment,",
"msg } } ])) except Exception: await query_chart.send(\"未找到该谱面\") else: name",
"@mr.handle() async def _(bot: Bot, event: Event, state: T_State): await",
"{music['title']}\\n\" } }, { \"type\": \"image\", \"data\": { \"file\": f\"{file}\"",
"if len(chart['notes']) == 5 else 0 brk = int(chart['notes'][-1]) total_score",
"c.execute(f'update guess_table set enabled=1 where group_id={event.group_id}') elif arg == '禁用':",
"} } ])) except Exception: await query_chart.send(\"未找到该乐曲\") wm_list = ['拼机',",
"on_command('猜歌设置', priority=0) @disable_guess_music.handle() async def _(bot: Bot, event: Event): if",
"event: Event): if event.message_type != \"group\": return arg = str(event.get_message())",
"qq = int(event.get_user_id()) h2 = hash(qq) h = h2 rp",
"<= 0 or reduce >= 101: raise ValueError await query_chart.send(f'''{music['title']}",
"async def _(bot: Bot, event: Event, state: T_State): level_labels =",
"'越级', '下埋', '夜勤', '练底力', '练手法', '打旧框', '干饭', '抓绝赞', '收歌'] jrwm",
"= int(chart['notes'][0]) slide = int(chart['notes'][2]) hold = int(chart['notes'][1]) touch =",
"else event.group_id) if mt == \"group\": gid = event.group_id db",
"= h2 rp = h % 100 wm_value = []",
"BREAK 5/12.5/25(外加200落)''' query_score_mes = Message([{ \"type\": \"image\", \"data\": { \"file\":",
"{music['basic_info']['bpm']}\\n版本: {music['basic_info']['from']}\\n难度: {'/'.join(music['level'])}\" } } ])) except Exception: await query_chart.send(\"未找到该乐曲\")",
"state[\"k\"] = k state[\"guess_object\"] = guess state[\"cycle\"] = 0 guess_cd_dict[k]",
"TOUCH 1/2.5/5 BREAK 5/12.5/25(外加200落)''' query_score_mes = Message([{ \"type\": \"image\", \"data\":",
"T_State from nonebot.adapters import Event, Bot from nonebot.adapters.cqhttp import Message,",
"数量为 {(total_score * reduce / 10000):.2f}(每个-{10000 / total_score:.4f}%), BREAK 50落(一共{brk}个)等价于",
"@guess_music_solve.handle() async def _(bot: Bot, event: Event, state: T_State): mt",
"\"|\" + guess.music['id']) if ans == guess.music['id'] or (ans.lower() ==",
"{elem[3]} {elem[4]}({elem[2]})\\n\" await inner_level.finish(s.strip()) spec_rand = on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\") @spec_rand.handle() async def",
"Event, state: T_State): await asyncio.sleep(30) guess: GuessObject = state[\"guess_object\"] if",
"touch * 500 + brk * 2500 break_bonus = 0.01",
"if not (mt == \"group\" and gid in whitelists): if",
"<歌曲别名>是什么歌 查询乐曲别名对应的乐曲 定数查歌 <定数> 查询定数对应的乐曲 定数查歌 <定数下限> <定数上限> 分数线 <难度+歌曲id>",
"async def guess_music_loop(bot: Bot, event: Event, state: T_State): await asyncio.sleep(10)",
"@find_song.handle() async def _(bot: Bot, event: Event, state: T_State): regex",
"inner_level.finish(\"数据超出 50 条,请尝试缩小查询范围\") return s = \"\" for elem in",
"asyncio.create_task(bot.send(event, Message([MessageSegment.text(\"答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")]))) del guess_dict[state[\"k\"]] @guess_music.handle() async",
"{wm_list[i]}\\n' s += \"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\" music = total_list[h2 % len(total_list)] await",
"from src.libraries.tool import hash from src.libraries.maimaidx_music import * from src.libraries.image",
"guess_dict: return ans = str(event.get_message()) guess = guess_dict[k] # await",
"break su = get_driver().config.superusers if m['role'] != 'owner' and m['role']",
"level = res.groups()[2] if res.groups()[1] == \"\": music_data = total_list.filter(level=level,",
"break_bonus = 0.01 / brk break_50_reduce = total_score * break_bonus",
"try: file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" await query_chart.send(Message([ { \"type\": \"text\", \"data\":",
"} }, { \"type\": \"text\", \"data\": { \"text\": f\"\\n{'/'.join(music.level)}\" }",
"ds2 is not None: music_data = total_list.filter(ds=(ds1, ds2)) else: music_data",
"分数线 {line}% 允许的最多 TAP GREAT 数量为 {(total_score * reduce /",
"== '启用': await c.execute(f'update guess_table set enabled=1 where group_id={event.group_id}') elif",
"total_score = 500 * tap + slide * 1500 +",
"on_command('猜歌', priority=0) async def guess_music_loop(bot: Bot, event: Event, state: T_State):",
"['Basic', 'Advanced', 'Expert', 'Master', 'Re: MASTER'] name = groups[1] music",
"inner_level_q(float(argv[0])) else: result_set = inner_level_q(float(argv[0]), float(argv[1])) if len(result_set) > 50:",
"on_command('今日舞萌', aliases={'今日mai'}) @jrwm.handle() async def _(bot: Bot, event: Event, state:",
"try: if res.groups()[0] == \"dx\": tp = [\"DX\"] elif res.groups()[0]",
"where group_id={event.group_id}') elif arg == '禁用': await c.execute(f'update guess_table set",
"await db.commit() await disable_guess_music.finish(\"设置成功\") guess_dict: Dict[Tuple[str, str], GuessObject] = {}",
"* from guess_table where group_id={gid}\") data = await c.fetchone() if",
"* 500 + brk * 2500 break_bonus = 0.01 /",
"state[\"guess_object\"] if guess.is_end: return cycle = state[\"cycle\"] if cycle <",
"{'/'.join(music['level'])}\" } } ])) except Exception: await query_chart.send(\"未找到该乐曲\") wm_list =",
"2/5/10 SLIDE 3/7.5/15 TOUCH 1/2.5/5 BREAK 5/12.5/25(外加200落)''' query_score_mes = Message([{",
"_(bot: Bot, event: Event, state: T_State): mt = event.message_type k",
"wm_list = ['拼机', '推分', '越级', '下埋', '夜勤', '练底力', '练手法', '打旧框',",
"TOUCH: {chart['notes'][3]} BREAK: {chart['notes'][4]} 谱师: {chart['charter']} ''' await query_chart.send(Message([ {",
"'练手法', '打旧框', '干饭', '抓绝赞', '收歌'] jrwm = on_command('今日舞萌', aliases={'今日mai'}) @jrwm.handle()",
"tap = int(chart['notes'][0]) slide = int(chart['notes'][2]) hold = int(chart['notes'][1]) touch",
"await mr.finish(song_txt(total_list.random())) search_music = on_regex(r\"^查歌.+\") @search_music.handle() async def _(bot: Bot,",
"Event, state: T_State): qq = int(event.get_user_id()) h2 = hash(qq) h",
"urllib import parse driver = get_driver() @driver.on_startup def _(): logger.info(\"Load",
"{wm_list[i]}\\n' elif wm_value[i] == 0: s += f'忌 {wm_list[i]}\\n' s",
"priority=0) async def guess_music_loop(bot: Bot, event: Event, state: T_State): await",
"\"data\": { \"text\": f\"\\n{'/'.join(music.level)}\" } } ]) def inner_level_q(ds1, ds2=None):",
"in guess.music['title'].lower()): guess.is_end = True del guess_dict[k] await guess_music_solve.finish(Message([ MessageSegment.reply(event.message_id),",
"\"type\": \"image\", \"data\": { \"file\": f\"https://www.diving-fish.com/covers/{music.id}.jpg\" } }, { \"type\":",
"f'忌 {wm_list[i]}\\n' s += \"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\" music = total_list[h2 % len(total_list)]",
"import time import re from urllib import parse driver =",
"= guess state[\"cycle\"] = 0 guess_cd_dict[k] = time.time() + 600",
"disable_guess_music.finish(\"请输入 猜歌设置 启用/禁用\") await db.commit() await disable_guess_music.finish(\"设置成功\") guess_dict: Dict[Tuple[str, str],",
"asyncio.create_task(guess_music_loop(bot, event, state)) async def give_answer(bot: Bot, event: Event, state:",
"_(bot: Bot, event: Event): if event.message_type != \"group\": return arg",
"for i in range(11): wm_value.append(h & 3) h >>= 2",
"'Re:MASTER'] level_index = level_labels.index(grp[0]) chart_id = grp[1] line = float(argv[1])",
"<定数上限> 分数线 <难度+歌曲id> <分数线> 详情请输入“分数线 帮助”查看\"\"\") def song_txt(music: Music): return",
"await guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\") return if k in guess_cd_dict and time.time() <",
"on_regex(r\".*maimai.*什么\") @mr.handle() async def _(bot: Bot, event: Event, state: T_State):",
"try: level_index = level_labels.index(groups[0]) level_name = ['Basic', 'Advanced', 'Expert', 'Master',",
"_(bot: Bot, event: Event, state: T_State): username = str(event.get_message()).strip() print(event.message_id)",
"await disable_guess_music.finish(\"只有管理员可以设置猜歌\") return db = get_driver().config.db c = await db.cursor()",
"<难度+歌曲id> <分数线> 详情请输入“分数线 帮助”查看\"\"\") def song_txt(music: Music): return Message([ {",
"time.time() > guess_cd_dict[k] - 400: # 如果已经过了 200 秒则自动结束上一次 del",
"str(event.get_message()).strip().split(\" \") if len(argv) == 1 and argv[0] == '帮助':",
"== event.user_id: break su = get_driver().config.superusers if m['role'] != 'owner'",
"30 秒后揭晓\") ]))) asyncio.create_task(give_answer(bot, event, state)) return state[\"cycle\"] += 1",
"Bot, event: Event, state: T_State): await asyncio.sleep(30) guess: GuessObject =",
"on_message, on_notice, on_regex, get_driver from nonebot.log import logger from nonebot.permission",
"await find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{ s }\") query_score = on_command('分数线') query_score_text = '''此功能为查找某首歌分数线设计。",
"from nonebot.typing import T_State from nonebot.adapters import Event, Bot from",
"query_chart = on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\") @query_chart.handle() async def _(bot: Bot, event: Event,",
"music['level'][i])) return result_set inner_level = on_command('inner_level ', aliases={'定数查歌 '}) @inner_level.handle()",
"Dict, Any from nonebot import on_command, on_message, on_notice, on_regex, get_driver",
"= \"(.+)是什么歌\" name = re.match(regex, str(event.get_message())).groups()[0].strip().lower() if name not in",
"{ \"type\": \"text\", \"data\": { \"text\": msg } } ]))",
"= [\"DX\"] elif res.groups()[0] == \"sd\" or res.groups()[0] == \"标准\":",
"hold = int(chart['notes'][1]) touch = int(chart['notes'][3]) if len(chart['notes']) == 5",
"result_set = [] diff_label = ['Bas', 'Adv', 'Exp', 'Mst', 'ReM']",
"for music in res])) query_chart = on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\") @query_chart.handle() async def",
"if k not in guess_dict: return ans = str(event.get_message()) guess",
"% len(total_list)] await jrwm.finish(Message([ {\"type\": \"text\", \"data\": {\"text\": s}} ]",
"await asyncio.sleep(30) guess: GuessObject = state[\"guess_object\"] if guess.is_end: return asyncio.create_task(bot.send(event,",
"diff_label = ['Bas', 'Adv', 'Exp', 'Mst', 'ReM'] if ds2 is",
"f\"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}\" } }]) @query_score.handle() async def _(bot: Bot, event:",
"\"text\", \"data\": { \"text\": f\"艺术家: {music['basic_info']['artist']}\\n分类: {music['basic_info']['genre']}\\nBPM: {music['basic_info']['bpm']}\\n版本: {music['basic_info']['from']}\\n难度: {'/'.join(music['level'])}\"",
"payload = {'username': username} img, success = await generate(payload) if",
"asyncio.sleep(10) guess: GuessObject = state[\"guess_object\"] if guess.is_end: return cycle =",
"(ans.lower() == guess.music['title'].lower()) or (len(ans) >= 5 and ans.lower() in",
"bot.get_group_member_list(group_id=event.group_id) for m in group_members: if m['user_id'] == event.user_id: break",
"\"text\", \"data\": {\"text\": \"您要找的是不是\"}}] + song_txt(music))) else: s = '\\n'.join(result_set)",
"+ 1}/7 这首歌\" + guess.guess_options[cycle])) else: asyncio.create_task(bot.send(event, Message([ MessageSegment.text(\"7/7 这首歌封面的一部分是:\"),",
"@best_40_pic.handle() async def _(bot: Bot, event: Event, state: T_State): username",
"in music.diff: result_set.append((music['id'], music['title'], music['ds'][i], diff_label[i], music['level'][i])) return result_set inner_level",
"= get_driver().config.db c = await db.cursor() if arg == '启用':",
"= total_list.by_id(name) chart = music['charts'][level_index] ds = music['ds'][level_index] level =",
"re.match(r, argv[0]).groups() level_labels = ['绿', '黄', '红', '紫', '白'] level_labels2",
"1: result_set = inner_level_q(float(argv[0])) else: result_set = inner_level_q(float(argv[0]), float(argv[1])) if",
"event, state)) guess_music_solve = on_message(priority=20) @guess_music_solve.handle() async def _(bot: Bot,",
"!= \"\": music_aliases[arr[i].lower()].append(arr[0]) find_song = on_regex(r\".+是什么歌\") @find_song.handle() async def _(bot:",
"spec_rand.finish(\"随机命令错误,请检查语法\") mr = on_regex(r\".*maimai.*什么\") @mr.handle() async def _(bot: Bot, event:",
"BREAK 50落等价的 TAP GREAT 数。 以下为 TAP GREAT 的对应表: GREAT/GOOD/MISS",
"def give_answer(bot: Bot, event: Event, state: T_State): await asyncio.sleep(30) guess:",
"guess.is_end = True del guess_dict[k] await guess_music_solve.finish(Message([ MessageSegment.reply(event.message_id), MessageSegment.text(\"猜对了,答案是:\" +",
"music_data: for i in music.diff: result_set.append((music['id'], music['title'], music['ds'][i], diff_label[i], music['level'][i]))",
"Message, MessageSegment, GroupMessageEvent, PrivateMessageEvent from src.libraries.maimaidx_guess import GuessObject from src.libraries.tool",
"= music['level'][level_index] file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" if len(chart['notes']) == 4: msg",
"except Exception: await query_chart.send(\"未找到该谱面\") else: name = groups[1] music =",
"''' else: msg = f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]}",
"}, { \"type\": \"text\", \"data\": { \"text\": f\"艺术家: {music['basic_info']['artist']}\\n分类: {music['basic_info']['genre']}\\nBPM:",
"5/12.5/25(外加200落)''' query_score_mes = Message([{ \"type\": \"image\", \"data\": { \"file\": f\"base64://{str(image_to_base64(text_to_image(query_score_text)),",
"time import re from urllib import parse driver = get_driver()",
"int(chart['notes'][1]) touch = int(chart['notes'][3]) if len(chart['notes']) == 5 else 0",
"'红', '紫', '白'] level_labels2 = ['Basic', 'Advanced', 'Expert', 'Master', 'Re:MASTER']",
"= event.group_id db = get_driver().config.db c = await db.cursor() await",
"GuessObject = state[\"guess_object\"] if guess.is_end: return asyncio.create_task(bot.send(event, Message([MessageSegment.text(\"答案是:\" + f\"{guess.music['id']}.",
"elif res.groups()[0] == \"sd\" or res.groups()[0] == \"标准\": tp =",
"dict = get_driver().config.help_text help_text['mai'] = ('查看舞萌相关功能', \"\"\"桜千雪です、よろしく。 可用命令如下: 今日舞萌 查看今天的舞萌运势",
"guess: GuessObject = state[\"guess_object\"] if guess.is_end: return asyncio.create_task(bot.send(event, Message([MessageSegment.text(\"答案是:\" +",
"src.libraries.maimai_best_40 import generate import requests import json import random import",
"\"data\": { \"file\": f\"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}\" } }]) @query_score.handle() async def",
"+= f'忌 {wm_list[i]}\\n' s += \"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\" music = total_list[h2 %",
"not None: music_data = total_list.filter(ds=(ds1, ds2)) else: music_data = total_list.filter(ds=ds1)",
"\"file\": f\"{file}\" } }, { \"type\": \"text\", \"data\": { \"text\":",
"return res = total_list.filter(title_search=name) await search_music.finish(Message([ {\"type\": \"text\", \"data\": {",
"{music['basic_info']['from']}\\n难度: {'/'.join(music['level'])}\" } } ])) except Exception: await query_chart.send(\"未找到该乐曲\") wm_list",
"name = re.match(regex, str(event.get_message())).groups()[0].strip().lower() if name not in music_aliases: await",
"@query_score.handle() async def _(bot: Bot, event: Event, state: T_State): r",
"+ touch * 500 + brk * 2500 break_bonus =",
"}]) @query_score.handle() async def _(bot: Bot, event: Event, state: T_State):",
"<定数>\\n定数查歌 <定数下限> <定数上限>\") return if len(argv) == 1: result_set =",
"* reduce / 10000):.2f}(每个-{10000 / total_score:.4f}%), BREAK 50落(一共{brk}个)等价于 {(break_50_reduce /",
"m in group_members: if m['user_id'] == event.user_id: break su =",
"guess.is_end: return cycle = state[\"cycle\"] if cycle < 6: asyncio.create_task(bot.send(event,",
"from src.libraries.maimaidx_music import * from src.libraries.image import * from src.libraries.maimai_best_40",
"and str(m['user_id']) not in su: await disable_guess_music.finish(\"只有管理员可以设置猜歌\") return db =",
"s += f'忌 {wm_list[i]}\\n' s += \"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\" music = total_list[h2",
"f\"艺术家: {music['basic_info']['artist']}\\n分类: {music['basic_info']['genre']}\\nBPM: {music['basic_info']['bpm']}\\n版本: {music['basic_info']['from']}\\n难度: {'/'.join(music['level'])}\" } } ])) except",
"db = get_driver().config.db c = await db.cursor() await c.execute(f\"select *",
"file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" await query_chart.send(Message([ { \"type\": \"text\", \"data\": {",
"歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\") return result_set = music_aliases[name] if len(result_set) == 1: music",
"\"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" } }, { \"type\":",
"groups[1] music = total_list.by_id(name) try: file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" await query_chart.send(Message([",
"{} guess_cd_dict: Dict[Tuple[str, str], float] = {} guess_music = on_command('猜歌',",
"= await c.fetchone() if data is None: await c.execute(f'insert into",
"GREAT(-{break_50_reduce / total_score * 100:.4f}%)''') except Exception: await query_chart.send(\"格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息\")",
"str(event.get_message()) group_members = await bot.get_group_member_list(group_id=event.group_id) for m in group_members: if",
"guess = GuessObject() guess_dict[k] = guess state[\"k\"] = k state[\"guess_object\"]",
"for m in group_members: if m['user_id'] == event.user_id: break su",
">= 5 and ans.lower() in guess.music['title'].lower()): guess.is_end = True del",
"{ \"text\": f\"{music['id']}. {music['title']}\\n\" }} for music in res])) query_chart",
"'推分', '越级', '下埋', '夜勤', '练底力', '练手法', '打旧框', '干饭', '抓绝赞', '收歌']",
"is not None: music_data = total_list.filter(ds=(ds1, ds2)) else: music_data =",
"len(argv) > 2 or len(argv) == 0: await inner_level.finish(\"命令格式为\\n定数查歌 <定数>\\n定数查歌",
"{time.strftime('%H:%M', time.localtime(guess_cd_dict[k]))} 可用噢\") return guess = GuessObject() guess_dict[k] = guess",
"GuessObject from src.libraries.tool import hash from src.libraries.maimaidx_music import * from",
"= (mt, event.user_id if mt == \"private\" else event.group_id) if",
"state)) async def give_answer(bot: Bot, event: Event, state: T_State): await",
"可用噢\") return guess = GuessObject() guess_dict[k] = guess state[\"k\"] =",
"async def _(bot: Bot, event: Event, state: T_State): r =",
"db.cursor() if arg == '启用': await c.execute(f'update guess_table set enabled=1",
"3: s += f'宜 {wm_list[i]}\\n' elif wm_value[i] == 0: s",
"if event.message_type != \"group\": return arg = str(event.get_message()) group_members =",
"= guess_dict[k] # await guess_music_solve.send(ans + \"|\" + guess.music['id']) if",
"elif success == 403: await best_40_pic.send(\"该用户禁止了其他人获取数据。\") else: await best_40_pic.send(Message([ MessageSegment.reply(event.message_id),",
"help_text: dict = get_driver().config.help_text help_text['mai'] = ('查看舞萌相关功能', \"\"\"桜千雪です、よろしく。 可用命令如下: 今日舞萌",
"{ \"file\": f\"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}\" } }]) @query_score.handle() async def _(bot:",
"'黄', '红', '紫', '白'] level_labels2 = ['Basic', 'Advanced', 'Expert', 'Master',",
"'白'] if groups[0] != \"\": try: level_index = level_labels.index(groups[0]) level_name",
"from src.libraries.maimai_best_40 import generate import requests import json import random",
"\"data\": { \"file\": f\"https://www.diving-fish.com/covers/{music.id}.jpg\" } }, { \"type\": \"text\", \"data\":",
"return guess = GuessObject() guess_dict[k] = guess state[\"k\"] = k",
"else: s = '\\n'.join(result_set) await find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{ s }\") query_score =",
"\"标准\": tp = [\"SD\"] else: tp = [\"SD\", \"DX\"] level",
"reduce / 10000):.2f}(每个-{10000 / total_score:.4f}%), BREAK 50落(一共{brk}个)等价于 {(break_50_reduce / 100):.3f}",
"\"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" }} for music in res]))",
"float] = {} guess_music = on_command('猜歌', priority=0) async def guess_music_loop(bot:",
"break_bonus / 4 reduce = 101 - line if reduce",
"_(bot: Bot, event: Event, state: T_State): level_labels = ['绿', '黄',",
"== '禁用': await c.execute(f'update guess_table set enabled=0 where group_id={event.group_id}') else:",
"import Message, MessageSegment, GroupMessageEvent, PrivateMessageEvent from src.libraries.maimaidx_guess import GuessObject from",
"in music_aliases: await find_song.finish(\"未找到此歌曲\\n舞萌 DX 歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\") return result_set = music_aliases[name]",
"best_40_pic.send(\"该用户禁止了其他人获取数据。\") else: await best_40_pic.send(Message([ MessageSegment.reply(event.message_id), MessageSegment.image(f\"base64://{str(image_to_base64(img), encoding='utf-8')}\") ])) disable_guess_music =",
"defaultdict(list) f = open('src/static/aliases.csv', 'r', encoding='utf-8') tmp = f.readlines() f.close()",
"/ 100):.3f} 个 TAP GREAT(-{break_50_reduce / total_score * 100:.4f}%)''') except",
"tp = [\"SD\"] else: tp = [\"SD\", \"DX\"] level =",
"+ song_txt(music))) else: s = '\\n'.join(result_set) await find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{ s }\")",
"查歌<乐曲标题的一部分> 查询符合条件的乐曲 [绿黄红紫白]id<歌曲编号> 查询乐曲信息或谱面信息 <歌曲别名>是什么歌 查询乐曲别名对应的乐曲 定数查歌 <定数> 查询定数对应的乐曲 定数查歌",
"] + song_txt(music))) music_aliases = defaultdict(list) f = open('src/static/aliases.csv', 'r',",
"启用/禁用\") await db.commit() await disable_guess_music.finish(\"设置成功\") guess_dict: Dict[Tuple[str, str], GuessObject] =",
"= int(chart['notes'][2]) hold = int(chart['notes'][1]) touch = int(chart['notes'][3]) if len(chart['notes'])",
"== guess.music['id'] or (ans.lower() == guess.music['title'].lower()) or (len(ans) >= 5",
"get_driver() @driver.on_startup def _(): logger.info(\"Load help text successfully\") help_text: dict",
"await best_40_pic.send(Message([ MessageSegment.reply(event.message_id), MessageSegment.image(f\"base64://{str(image_to_base64(img), encoding='utf-8')}\") ])) disable_guess_music = on_command('猜歌设置', priority=0)",
"i in music.diff: result_set.append((music['id'], music['title'], music['ds'][i], diff_label[i], music['level'][i])) return result_set",
"def guess_music_loop(bot: Bot, event: Event, state: T_State): await asyncio.sleep(10) guess:",
"arg == '启用': await c.execute(f'update guess_table set enabled=1 where group_id={event.group_id}')",
"touch = int(chart['notes'][3]) if len(chart['notes']) == 5 else 0 brk",
"+ brk * 2500 break_bonus = 0.01 / brk break_50_reduce",
"Bot, event: Event, state: T_State): await asyncio.sleep(10) guess: GuessObject =",
"h >>= 2 s = f\"今日人品值:{rp}\\n\" for i in range(11):",
"level_name = ['Basic', 'Advanced', 'Expert', 'Master', 'Re: MASTER'] name =",
"return ans = str(event.get_message()) guess = guess_dict[k] # await guess_music_solve.send(ans",
"1}/7 这首歌\" + guess.guess_options[cycle])) else: asyncio.create_task(bot.send(event, Message([ MessageSegment.text(\"7/7 这首歌封面的一部分是:\"), MessageSegment.image(\"base64://\"",
"src.libraries.maimaidx_guess import GuessObject from src.libraries.tool import hash from src.libraries.maimaidx_music import",
"not (mt == \"group\" and gid in whitelists): if len(guess_dict)",
"GuessObject] = {} guess_cd_dict: Dict[Tuple[str, str], float] = {} guess_music",
"秒后揭晓\") ]))) asyncio.create_task(give_answer(bot, event, state)) return state[\"cycle\"] += 1 asyncio.create_task(guess_music_loop(bot,",
"def _(bot: Bot, event: Event): if event.message_type != \"group\": return",
"100 wm_value = [] for i in range(11): wm_value.append(h &",
"{\"type\": \"text\", \"data\": {\"text\": s}} ] + song_txt(music))) music_aliases =",
"随个[dx/标准][绿黄红紫白]<难度> 随机一首指定条件的乐曲 查歌<乐曲标题的一部分> 查询符合条件的乐曲 [绿黄红紫白]id<歌曲编号> 查询乐曲信息或谱面信息 <歌曲别名>是什么歌 查询乐曲别名对应的乐曲 定数查歌 <定数>",
"以下为 TAP GREAT 的对应表: GREAT/GOOD/MISS TAP 1/2.5/5 HOLD 2/5/10 SLIDE",
"<定数下限> <定数上限>\") return if len(argv) == 1: result_set = inner_level_q(float(argv[0]))",
"{chart['notes'][4]} 谱师: {chart['charter']} ''' await query_chart.send(Message([ { \"type\": \"text\", \"data\":",
"payload = {'qq': str(event.get_user_id())} else: payload = {'username': username} img,",
"str(event.get_user_id())} else: payload = {'username': username} img, success = await",
"state: T_State): regex = \"(.+)是什么歌\" name = re.match(regex, str(event.get_message())).groups()[0].strip().lower() if",
"'启用': await c.execute(f'update guess_table set enabled=1 where group_id={event.group_id}') elif arg",
"{} guess_music = on_command('猜歌', priority=0) async def guess_music_loop(bot: Bot, event:",
"typing import List, Dict, Any from nonebot import on_command, on_message,",
"\"text\": f\"\\n{'/'.join(music.level)}\" } } ]) def inner_level_q(ds1, ds2=None): result_set =",
"{ \"type\": \"image\", \"data\": { \"file\": f\"{file}\" } }, {",
"state[\"guess_object\"] if guess.is_end: return asyncio.create_task(bot.send(event, Message([MessageSegment.text(\"答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")])))",
"== 0: await inner_level.finish(\"命令格式为\\n定数查歌 <定数>\\n定数查歌 <定数下限> <定数上限>\") return if len(argv)",
"result_set: s += f\"{elem[0]}. {elem[1]} {elem[3]} {elem[4]}({elem[2]})\\n\" await inner_level.finish(s.strip()) spec_rand",
"name == \"\": return res = total_list.filter(title_search=name) await search_music.finish(Message([ {\"type\":",
"mr.finish(song_txt(total_list.random())) search_music = on_regex(r\"^查歌.+\") @search_music.handle() async def _(bot: Bot, event:",
"BREAK: {chart['notes'][4]} 谱师: {chart['charter']} ''' await query_chart.send(Message([ { \"type\": \"text\",",
"'Expert', 'Master', 'Re:MASTER'] level_index = level_labels.index(grp[0]) chart_id = grp[1] line",
"in range(11): if wm_value[i] == 3: s += f'宜 {wm_list[i]}\\n'",
"= True del guess_dict[k] await guess_music_solve.finish(Message([ MessageSegment.reply(event.message_id), MessageSegment.text(\"猜对了,答案是:\" + f\"{guess.music['id']}.",
"get_driver().config.help_text help_text['mai'] = ('查看舞萌相关功能', \"\"\"桜千雪です、よろしく。 可用命令如下: 今日舞萌 查看今天的舞萌运势 XXXmaimaiXXX什么 随机一首歌",
"k state[\"guess_object\"] = guess state[\"cycle\"] = 0 guess_cd_dict[k] = time.time()",
"guess_table set enabled=1 where group_id={event.group_id}') elif arg == '禁用': await",
"== 2: try: grp = re.match(r, argv[0]).groups() level_labels = ['绿',",
"wm_value = [] for i in range(11): wm_value.append(h & 3)",
"argv[0]).groups() level_labels = ['绿', '黄', '红', '紫', '白'] level_labels2 =",
"'}) @inner_level.handle() async def _(bot: Bot, event: Event, state: T_State):",
"= total_list.filter(level=level, type=tp) else: music_data = total_list.filter(level=level, diff=['绿黄红紫白'.index(res.groups()[1])], type=tp) await",
"@spec_rand.handle() async def _(bot: Bot, event: Event, state: T_State): level_labels",
"])) except Exception: await query_chart.send(\"未找到该谱面\") else: name = groups[1] music",
"give_answer(bot: Bot, event: Event, state: T_State): await asyncio.sleep(30) guess: GuessObject",
"= re.match(regex, str(event.get_message())).groups() level_labels = ['绿', '黄', '红', '紫', '白']",
"state[\"guess_object\"] = guess state[\"cycle\"] = 0 guess_cd_dict[k] = time.time() +",
"= get_driver().config.db c = await db.cursor() await c.execute(f\"select * from",
"music = total_list[h2 % len(total_list)] await jrwm.finish(Message([ {\"type\": \"text\", \"data\":",
"500 * tap + slide * 1500 + hold *",
"tp = [\"DX\"] elif res.groups()[0] == \"sd\" or res.groups()[0] ==",
"slide * 1500 + hold * 1000 + touch *",
"level = music['level'][level_index] file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" if len(chart['notes']) == 4:",
"query_chart.send(\"格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息\") best_40_pic = on_command('b40') @best_40_pic.handle() async def _(bot: Bot,",
"text successfully\") help_text: dict = get_driver().config.help_text help_text['mai'] = ('查看舞萌相关功能', \"\"\"桜千雪です、よろしく。",
"True del guess_dict[k] await guess_music_solve.finish(Message([ MessageSegment.reply(event.message_id), MessageSegment.text(\"猜对了,答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"),",
"s }\") query_score = on_command('分数线') query_score_text = '''此功能为查找某首歌分数线设计。 命令格式:分数线 <难度+歌曲id>",
"int(chart['notes'][-1]) total_score = 500 * tap + slide * 1500",
"= music['ds'][level_index] level = music['level'][level_index] file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" if len(chart['notes'])",
"= [] for i in range(11): wm_value.append(h & 3) h",
"} }, { \"type\": \"image\", \"data\": { \"file\": f\"https://www.diving-fish.com/covers/{music.id}.jpg\" }",
"+ f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")]))) del guess_dict[state[\"k\"]] @guess_music.handle() async def _(bot:",
"ans = str(event.get_message()) guess = guess_dict[k] # await guess_music_solve.send(ans +",
"= on_regex(r\".*maimai.*什么\") @mr.handle() async def _(bot: Bot, event: Event, state:",
"event: Event, state: T_State): level_labels = ['绿', '黄', '红', '紫',",
"guess_table set enabled=0 where group_id={event.group_id}') else: await disable_guess_music.finish(\"请输入 猜歌设置 启用/禁用\")",
"_(bot: Bot, event: Event, state: T_State): r = \"([绿黄红紫白])(?:id)?([0-9]+)\" argv",
"from nonebot.adapters.cqhttp import Message, MessageSegment, GroupMessageEvent, PrivateMessageEvent from src.libraries.maimaidx_guess import",
"len(argv) == 1 and argv[0] == '帮助': await query_score.send(query_score_mes) elif",
"music = total_list.by_id(chart_id) chart: Dict[Any] = music['charts'][level_index] tap = int(chart['notes'][0])",
"else: asyncio.create_task(bot.send(event, Message([ MessageSegment.text(\"7/7 这首歌封面的一部分是:\"), MessageSegment.image(\"base64://\" + str(guess.b64image, encoding=\"utf-8\")), MessageSegment.text(\"答案将在",
"_(bot: Bot, event: Event, state: T_State): regex = \"([绿黄红紫白]?)id([0-9]+)\" groups",
"mr = on_regex(r\".*maimai.*什么\") @mr.handle() async def _(bot: Bot, event: Event,",
"is None: await c.execute(f'insert into guess_table values ({gid}, 1)') elif",
"= f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" await query_chart.send(Message([ { \"type\": \"text\", \"data\": { \"text\":",
"query_score_mes = Message([{ \"type\": \"image\", \"data\": { \"file\": f\"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}\"",
"arg == '禁用': await c.execute(f'update guess_table set enabled=0 where group_id={event.group_id}')",
"', aliases={'定数查歌 '}) @inner_level.handle() async def _(bot: Bot, event: Event,",
"time.localtime(guess_cd_dict[k]))} 可用噢\") return guess = GuessObject() guess_dict[k] = guess state[\"k\"]",
"= {'username': username} img, success = await generate(payload) if success",
"== \"group\": gid = event.group_id db = get_driver().config.db c =",
"str], float] = {} guess_music = on_command('猜歌', priority=0) async def",
"命令格式:分数线 <难度+歌曲id> <分数线> 例如:分数线 白337 100 命令将返回分数线允许的 TAP GREAT 容错以及",
"{elem[4]}({elem[2]})\\n\" await inner_level.finish(s.strip()) spec_rand = on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\") @spec_rand.handle() async def _(bot:",
"music_aliases[arr[i].lower()].append(arr[0]) find_song = on_regex(r\".+是什么歌\") @find_song.handle() async def _(bot: Bot, event:",
"{(break_50_reduce / 100):.3f} 个 TAP GREAT(-{break_50_reduce / total_score * 100:.4f}%)''')",
"if guess.is_end: return cycle = state[\"cycle\"] if cycle < 6:",
"on_command('分数线') query_score_text = '''此功能为查找某首歌分数线设计。 命令格式:分数线 <难度+歌曲id> <分数线> 例如:分数线 白337 100",
"\"\": try: level_index = level_labels.index(groups[0]) level_name = ['Basic', 'Advanced', 'Expert',",
"su = get_driver().config.superusers if m['role'] != 'owner' and m['role'] !=",
"guess_cd_dict: Dict[Tuple[str, str], float] = {} guess_music = on_command('猜歌', priority=0)",
"and ans.lower() in guess.music['title'].lower()): guess.is_end = True del guess_dict[k] await",
"music['ds'][i], diff_label[i], music['level'][i])) return result_set inner_level = on_command('inner_level ', aliases={'定数查歌",
"mt == \"group\": gid = event.group_id db = get_driver().config.db c",
"= inner_level_q(float(argv[0]), float(argv[1])) if len(result_set) > 50: await inner_level.finish(\"数据超出 50",
"from collections import defaultdict from typing import List, Dict, Any",
"== 5 else 0 brk = int(chart['notes'][-1]) total_score = 500",
"* 1000 + touch * 500 + brk * 2500",
"import random import time import re from urllib import parse",
"priority=0) @disable_guess_music.handle() async def _(bot: Bot, event: Event): if event.message_type",
"in guess_cd_dict and time.time() > guess_cd_dict[k] - 400: # 如果已经过了",
"T_State): regex = \"([绿黄红紫白]?)id([0-9]+)\" groups = re.match(regex, str(event.get_message())).groups() level_labels =",
"Bot, event: Event, state: T_State): await mr.finish(song_txt(total_list.random())) search_music = on_regex(r\"^查歌.+\")",
"import GuessObject from src.libraries.tool import hash from src.libraries.maimaidx_music import *",
"guess_dict[k] else: await guess_music.send(\"当前已有正在进行的猜歌\") return whitelists = get_driver().config.whitelists if not",
"asyncio.sleep(30) guess: GuessObject = state[\"guess_object\"] if guess.is_end: return asyncio.create_task(bot.send(event, Message([MessageSegment.text(\"答案是:\"",
"Bot, event: Event, state: T_State): level_labels = ['绿', '黄', '红',",
"total_score:.4f}%), BREAK 50落(一共{brk}个)等价于 {(break_50_reduce / 100):.3f} 个 TAP GREAT(-{break_50_reduce /",
"db.commit() await disable_guess_music.finish(\"设置成功\") guess_dict: Dict[Tuple[str, str], GuessObject] = {} guess_cd_dict:",
"这首歌封面的一部分是:\"), MessageSegment.image(\"base64://\" + str(guess.b64image, encoding=\"utf-8\")), MessageSegment.text(\"答案将在 30 秒后揭晓\") ]))) asyncio.create_task(give_answer(bot,",
"@inner_level.handle() async def _(bot: Bot, event: Event, state: T_State): argv",
"> 50: await inner_level.finish(\"数据超出 50 条,请尝试缩小查询范围\") return s = \"\"",
"total_list.filter(title_search=name) await search_music.finish(Message([ {\"type\": \"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\"",
"\"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" } }, { \"type\": \"image\",",
"elem in result_set: s += f\"{elem[0]}. {elem[1]} {elem[3]} {elem[4]}({elem[2]})\\n\" await",
"math from collections import defaultdict from typing import List, Dict,",
"line if reduce <= 0 or reduce >= 101: raise",
"nonebot.typing import T_State from nonebot.adapters import Event, Bot from nonebot.adapters.cqhttp",
"await inner_level.finish(\"数据超出 50 条,请尝试缩小查询范围\") return s = \"\" for elem",
"MessageSegment.image(\"base64://\" + str(guess.b64image, encoding=\"utf-8\")), MessageSegment.text(\"答案将在 30 秒后揭晓\") ]))) asyncio.create_task(give_answer(bot, event,",
"== 1 and argv[0] == '帮助': await query_score.send(query_score_mes) elif len(argv)",
"DX 歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\") return result_set = music_aliases[name] if len(result_set) == 1:",
"help text successfully\") help_text: dict = get_driver().config.help_text help_text['mai'] = ('查看舞萌相关功能',",
"event: Event, state: T_State): argv = str(event.get_message()).strip().split(\" \") if len(argv)",
"* tap + slide * 1500 + hold * 1000",
"float(argv[1]) music = total_list.by_id(chart_id) chart: Dict[Any] = music['charts'][level_index] tap =",
"== 0: await guess_music.send(\"本群已禁用猜歌\") return if k in guess_dict: if",
"/ 10000):.2f}(每个-{10000 / total_score:.4f}%), BREAK 50落(一共{brk}个)等价于 {(break_50_reduce / 100):.3f} 个",
"regex = \"查歌(.+)\" name = re.match(regex, str(event.get_message())).groups()[0].strip() if name ==",
"== \"group\" and gid in whitelists): if len(guess_dict) >= 5:",
"\"group\" and gid in whitelists): if len(guess_dict) >= 5: await",
"f\"\\n{'/'.join(music.level)}\" } } ]) def inner_level_q(ds1, ds2=None): result_set = []",
"List, Dict, Any from nonebot import on_command, on_message, on_notice, on_regex,",
"'红', '紫', '白'] regex = \"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\" res = re.match(regex, str(event.get_message()).lower())",
"= str(event.get_message()) guess = guess_dict[k] # await guess_music_solve.send(ans + \"|\"",
"guess_music.finish(f\"已经猜过啦,下次猜歌会在 {time.strftime('%H:%M', time.localtime(guess_cd_dict[k]))} 可用噢\") return guess = GuessObject() guess_dict[k] =",
"file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" if len(chart['notes']) == 4: msg = f'''{level_name[level_index]}",
"t.strip().split('\\t') for i in range(len(arr)): if arr[i] != \"\": music_aliases[arr[i].lower()].append(arr[0])",
"Event, state: T_State): mt = event.message_type k = (mt, event.user_id",
"= music['charts'][level_index] tap = int(chart['notes'][0]) slide = int(chart['notes'][2]) hold =",
"argv = str(event.get_message()).strip().split(\" \") if len(argv) > 2 or len(argv)",
"values ({gid}, 1)') elif data[1] == 0: await guess_music.send(\"本群已禁用猜歌\") return",
"music_aliases: await find_song.finish(\"未找到此歌曲\\n舞萌 DX 歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\") return result_set = music_aliases[name] if",
"/ brk break_50_reduce = total_score * break_bonus / 4 reduce",
"type=tp) else: music_data = total_list.filter(level=level, diff=['绿黄红紫白'.index(res.groups()[1])], type=tp) await spec_rand.send(song_txt(music_data.random())) except",
"success == 403: await best_40_pic.send(\"该用户禁止了其他人获取数据。\") else: await best_40_pic.send(Message([ MessageSegment.reply(event.message_id), MessageSegment.image(f\"base64://{str(image_to_base64(img),",
"query_chart.send(Message([ { \"type\": \"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" }",
"s = '\\n'.join(result_set) await find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{ s }\") query_score = on_command('分数线')",
"@guess_music.handle() async def _(bot: Bot, event: Event, state: T_State): mt",
"len(guess_dict) >= 5: await guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\") return if k in guess_cd_dict",
"generate(payload) if success == 400: await best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\") elif success ==",
"'红', '紫', '白'] if groups[0] != \"\": try: level_index =",
"in whitelists): if len(guess_dict) >= 5: await guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\") return if",
"0.01 / brk break_50_reduce = total_score * break_bonus / 4",
"= re.match(regex, str(event.get_message())).groups()[0].strip() if name == \"\": return res =",
"song_txt(music))) else: s = '\\n'.join(result_set) await find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{ s }\") query_score",
"* from src.libraries.image import * from src.libraries.maimai_best_40 import generate import",
"c.execute(f'update guess_table set enabled=0 where group_id={event.group_id}') else: await disable_guess_music.finish(\"请输入 猜歌设置",
"} } ])) except Exception: await query_chart.send(\"未找到该谱面\") else: name =",
"4: msg = f'''{level_name[level_index]} {level}({ds}) TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE:",
"= re.match(r, argv[0]).groups() level_labels = ['绿', '黄', '红', '紫', '白']",
"的对应表: GREAT/GOOD/MISS TAP 1/2.5/5 HOLD 2/5/10 SLIDE 3/7.5/15 TOUCH 1/2.5/5",
"\"type\": \"image\", \"data\": { \"file\": f\"{file}\" } }, { \"type\":",
"@search_music.handle() async def _(bot: Bot, event: Event, state: T_State): regex",
"None: await c.execute(f'insert into guess_table values ({gid}, 1)') elif data[1]",
"== 1: result_set = inner_level_q(float(argv[0])) else: result_set = inner_level_q(float(argv[0]), float(argv[1]))",
"arg = str(event.get_message()) group_members = await bot.get_group_member_list(group_id=event.group_id) for m in",
"brk break_50_reduce = total_score * break_bonus / 4 reduce =",
"query_score.send(query_score_mes) elif len(argv) == 2: try: grp = re.match(r, argv[0]).groups()",
"guess_music = on_command('猜歌', priority=0) async def guess_music_loop(bot: Bot, event: Event,",
"del guess_dict[state[\"k\"]] @guess_music.handle() async def _(bot: Bot, event: Event, state:",
"['Bas', 'Adv', 'Exp', 'Mst', 'ReM'] if ds2 is not None:",
"= level_labels.index(groups[0]) level_name = ['Basic', 'Advanced', 'Expert', 'Master', 'Re: MASTER']",
"else: result_set = inner_level_q(float(argv[0]), float(argv[1])) if len(result_set) > 50: await",
"= on_regex(r\"^随个(?:dx|sd|标准)?[绿黄红紫白]?[0-9]+\\+?\") @spec_rand.handle() async def _(bot: Bot, event: Event, state:",
"async def _(bot: Bot, event: Event, state: T_State): argv =",
"= await db.cursor() if arg == '启用': await c.execute(f'update guess_table",
"\"data\": { \"text\": f\"艺术家: {music['basic_info']['artist']}\\n分类: {music['basic_info']['genre']}\\nBPM: {music['basic_info']['bpm']}\\n版本: {music['basic_info']['from']}\\n难度: {'/'.join(music['level'])}\" }",
"0 or reduce >= 101: raise ValueError await query_chart.send(f'''{music['title']} {level_labels2[level_index]}",
"jrwm = on_command('今日舞萌', aliases={'今日mai'}) @jrwm.handle() async def _(bot: Bot, event:",
"level_labels = ['绿', '黄', '红', '紫', '白'] level_labels2 = ['Basic',",
"{ \"text\": f\"{music.id}. {music.title}\\n\" } }, { \"type\": \"image\", \"data\":",
"await query_score.send(query_score_mes) elif len(argv) == 2: try: grp = re.match(r,",
"Message([{ \"type\": \"image\", \"data\": { \"file\": f\"base64://{str(image_to_base64(text_to_image(query_score_text)), encoding='utf-8')}\" } }])",
"{chart['notes'][3]} 谱师: {chart['charter']} ''' else: msg = f'''{level_name[level_index]} {level}({ds}) TAP:",
"= inner_level_q(float(argv[0])) else: result_set = inner_level_q(float(argv[0]), float(argv[1])) if len(result_set) >",
"'Master', 'Re:MASTER'] level_index = level_labels.index(grp[0]) chart_id = grp[1] line =",
"数。 以下为 TAP GREAT 的对应表: GREAT/GOOD/MISS TAP 1/2.5/5 HOLD 2/5/10",
"4 reduce = 101 - line if reduce <= 0",
"disable_guess_music.finish(\"设置成功\") guess_dict: Dict[Tuple[str, str], GuessObject] = {} guess_cd_dict: Dict[Tuple[str, str],",
"if name not in music_aliases: await find_song.finish(\"未找到此歌曲\\n舞萌 DX 歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\") return",
"event, state)) async def give_answer(bot: Bot, event: Event, state: T_State):",
"state: T_State): regex = \"查歌(.+)\" name = re.match(regex, str(event.get_message())).groups()[0].strip() if",
"可用命令如下: 今日舞萌 查看今天的舞萌运势 XXXmaimaiXXX什么 随机一首歌 随个[dx/标准][绿黄红紫白]<难度> 随机一首指定条件的乐曲 查歌<乐曲标题的一部分> 查询符合条件的乐曲 [绿黄红紫白]id<歌曲编号>",
"elif arg == '禁用': await c.execute(f'update guess_table set enabled=0 where",
"}, { \"type\": \"image\", \"data\": { \"file\": f\"https://www.diving-fish.com/covers/{music.id}.jpg\" } },",
"wm_value[i] == 3: s += f'宜 {wm_list[i]}\\n' elif wm_value[i] ==",
"T_State): await asyncio.sleep(10) guess: GuessObject = state[\"guess_object\"] if guess.is_end: return",
"def _(bot: Bot, event: Event, state: T_State): username = str(event.get_message()).strip()",
"@driver.on_startup def _(): logger.info(\"Load help text successfully\") help_text: dict =",
"XXXmaimaiXXX什么 随机一首歌 随个[dx/标准][绿黄红紫白]<难度> 随机一首指定条件的乐曲 查歌<乐曲标题的一部分> 查询符合条件的乐曲 [绿黄红紫白]id<歌曲编号> 查询乐曲信息或谱面信息 <歌曲别名>是什么歌 查询乐曲别名对应的乐曲",
"query_score_text = '''此功能为查找某首歌分数线设计。 命令格式:分数线 <难度+歌曲id> <分数线> 例如:分数线 白337 100 命令将返回分数线允许的",
"find_song.finish(f\"您要找的可能是以下歌曲中的其中一首:\\n{ s }\") query_score = on_command('分数线') query_score_text = '''此功能为查找某首歌分数线设计。 命令格式:分数线",
"k in guess_cd_dict and time.time() > guess_cd_dict[k] - 400: #",
"{\"text\": s}} ] + song_txt(music))) music_aliases = defaultdict(list) f =",
"(mt == \"group\" and gid in whitelists): if len(guess_dict) >=",
"db = get_driver().config.db c = await db.cursor() if arg ==",
"total_score * break_bonus / 4 reduce = 101 - line",
"asyncio.create_task(guess_music_loop(bot, event, state)) guess_music_solve = on_message(priority=20) @guess_music_solve.handle() async def _(bot:",
"await db.cursor() if arg == '启用': await c.execute(f'update guess_table set",
"{chart['notes'][1]} SLIDE: {chart['notes'][2]} TOUCH: {chart['notes'][3]} BREAK: {chart['notes'][4]} 谱师: {chart['charter']} '''",
"level_index = level_labels.index(groups[0]) level_name = ['Basic', 'Advanced', 'Expert', 'Master', 'Re:",
"disable_guess_music = on_command('猜歌设置', priority=0) @disable_guess_music.handle() async def _(bot: Bot, event:",
"where group_id={event.group_id}') else: await disable_guess_music.finish(\"请输入 猜歌设置 启用/禁用\") await db.commit() await",
"res.groups()[0] == \"dx\": tp = [\"DX\"] elif res.groups()[0] == \"sd\"",
"T_State): await mr.finish(song_txt(total_list.random())) search_music = on_regex(r\"^查歌.+\") @search_music.handle() async def _(bot:",
"+ \"|\" + guess.music['id']) if ans == guess.music['id'] or (ans.lower()",
"for elem in result_set: s += f\"{elem[0]}. {elem[1]} {elem[3]} {elem[4]}({elem[2]})\\n\"",
"name not in music_aliases: await find_song.finish(\"未找到此歌曲\\n舞萌 DX 歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\") return result_set",
">= 5: await guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\") return if k in guess_cd_dict and",
"= grp[1] line = float(argv[1]) music = total_list.by_id(chart_id) chart: Dict[Any]",
"gid in whitelists): if len(guess_dict) >= 5: await guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\") return",
"\"text\", \"data\": { \"text\": msg } } ])) except Exception:",
"= ['Basic', 'Advanced', 'Expert', 'Master', 'Re: MASTER'] name = groups[1]",
"('查看舞萌相关功能', \"\"\"桜千雪です、よろしく。 可用命令如下: 今日舞萌 查看今天的舞萌运势 XXXmaimaiXXX什么 随机一首歌 随个[dx/标准][绿黄红紫白]<难度> 随机一首指定条件的乐曲 查歌<乐曲标题的一部分>",
"= total_list.filter(title_search=name) await search_music.finish(Message([ {\"type\": \"text\", \"data\": { \"text\": f\"{music['id']}.",
"条,请尝试缩小查询范围\") return s = \"\" for elem in result_set: s",
"'Advanced', 'Expert', 'Master', 'Re:MASTER'] level_index = level_labels.index(grp[0]) chart_id = grp[1]",
"\"data\": {\"text\": \"您要找的是不是\"}}] + song_txt(music))) else: s = '\\n'.join(result_set) await",
"GREAT 数量为 {(total_score * reduce / 10000):.2f}(每个-{10000 / total_score:.4f}%), BREAK",
"(mt, event.user_id if mt == \"private\" else event.group_id) if mt",
"600 await guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中 5 个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\") asyncio.create_task(guess_music_loop(bot, event, state)) guess_music_solve =",
"} ]) def inner_level_q(ds1, ds2=None): result_set = [] diff_label =",
"inner_level_q(ds1, ds2=None): result_set = [] diff_label = ['Bas', 'Adv', 'Exp',",
"state: T_State): r = \"([绿黄红紫白])(?:id)?([0-9]+)\" argv = str(event.get_message()).strip().split(\" \") if",
"await c.execute(f\"select * from guess_table where group_id={gid}\") data = await",
"aliases={'定数查歌 '}) @inner_level.handle() async def _(bot: Bot, event: Event, state:",
"re.match(regex, str(event.get_message())).groups()[0].strip() if name == \"\": return res = total_list.filter(title_search=name)",
"<分数线> 例如:分数线 白337 100 命令将返回分数线允许的 TAP GREAT 容错以及 BREAK 50落等价的",
"T_State): regex = \"(.+)是什么歌\" name = re.match(regex, str(event.get_message())).groups()[0].strip().lower() if name",
"s}} ] + song_txt(music))) music_aliases = defaultdict(list) f = open('src/static/aliases.csv',",
"5 else 0 brk = int(chart['notes'][-1]) total_score = 500 *",
"guess.music['id'] or (ans.lower() == guess.music['title'].lower()) or (len(ans) >= 5 and",
"else: music_data = total_list.filter(ds=ds1) for music in music_data: for i",
"event: Event, state: T_State): await mr.finish(song_txt(total_list.random())) search_music = on_regex(r\"^查歌.+\") @search_music.handle()",
"'黄', '红', '紫', '白'] if groups[0] != \"\": try: level_index",
"c = await db.cursor() await c.execute(f\"select * from guess_table where",
"查询乐曲信息或谱面信息 <歌曲别名>是什么歌 查询乐曲别名对应的乐曲 定数查歌 <定数> 查询定数对应的乐曲 定数查歌 <定数下限> <定数上限> 分数线",
"@query_chart.handle() async def _(bot: Bot, event: Event, state: T_State): regex",
"int(event.get_user_id()) h2 = hash(qq) h = h2 rp = h",
"2: try: grp = re.match(r, argv[0]).groups() level_labels = ['绿', '黄',",
"music = total_list.by_title(result_set[0]) await find_song.finish(Message([{\"type\": \"text\", \"data\": {\"text\": \"您要找的是不是\"}}] +",
"\"text\": f\"{music['id']}. {music['title']}\\n\" } }, { \"type\": \"image\", \"data\": {",
"total_list.filter(ds=(ds1, ds2)) else: music_data = total_list.filter(ds=ds1) for music in music_data:",
"mt == \"private\" else event.group_id) if k not in guess_dict:",
"requests import json import random import time import re from",
"]))) asyncio.create_task(give_answer(bot, event, state)) return state[\"cycle\"] += 1 asyncio.create_task(guess_music_loop(bot, event,",
"])) except Exception: await query_chart.send(\"未找到该乐曲\") wm_list = ['拼机', '推分', '越级',",
"500 + brk * 2500 break_bonus = 0.01 / brk",
"@jrwm.handle() async def _(bot: Bot, event: Event, state: T_State): qq",
"= total_list.by_id(name) try: file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" await query_chart.send(Message([ { \"type\":",
"PrivateMessageEvent from src.libraries.maimaidx_guess import GuessObject from src.libraries.tool import hash from",
"+ str(guess.b64image, encoding=\"utf-8\")), MessageSegment.text(\"答案将在 30 秒后揭晓\") ]))) asyncio.create_task(give_answer(bot, event, state))",
"else 0 brk = int(chart['notes'][-1]) total_score = 500 * tap",
"\"type\": \"text\", \"data\": { \"text\": f\"艺术家: {music['basic_info']['artist']}\\n分类: {music['basic_info']['genre']}\\nBPM: {music['basic_info']['bpm']}\\n版本: {music['basic_info']['from']}\\n难度:",
"time.time() + 600 await guess_music.send(\"我将从热门乐曲中选择一首歌,并描述它的一些特征,请输入歌曲的【id】、【歌曲标题】或【歌曲标题中 5 个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\") asyncio.create_task(guess_music_loop(bot, event, state))",
"data[1] == 0: await guess_music.send(\"本群已禁用猜歌\") return if k in guess_dict:",
"guess.music['id']) if ans == guess.music['id'] or (ans.lower() == guess.music['title'].lower()) or",
"{ \"text\": f\"\\n{'/'.join(music.level)}\" } } ]) def inner_level_q(ds1, ds2=None): result_set",
"level_labels.index(groups[0]) level_name = ['Basic', 'Advanced', 'Expert', 'Master', 'Re: MASTER'] name",
"event: Event, state: T_State): regex = \"查歌(.+)\" name = re.match(regex,",
"import hash from src.libraries.maimaidx_music import * from src.libraries.image import *",
"return if k in guess_dict: if k in guess_cd_dict and",
"5 and ans.lower() in guess.music['title'].lower()): guess.is_end = True del guess_dict[k]",
"= await generate(payload) if success == 400: await best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\") elif",
"\"\" for elem in result_set: s += f\"{elem[0]}. {elem[1]} {elem[3]}",
"ds2=None): result_set = [] diff_label = ['Bas', 'Adv', 'Exp', 'Mst',",
"'owner' and m['role'] != 'admin' and str(m['user_id']) not in su:",
"break_50_reduce = total_score * break_bonus / 4 reduce = 101",
"3/7.5/15 TOUCH 1/2.5/5 BREAK 5/12.5/25(外加200落)''' query_score_mes = Message([{ \"type\": \"image\",",
"await spec_rand.send(song_txt(music_data.random())) except Exception as e: print(e) await spec_rand.finish(\"随机命令错误,请检查语法\") mr",
"level_labels = ['绿', '黄', '红', '紫', '白'] regex = \"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\"",
"return whitelists = get_driver().config.whitelists if not (mt == \"group\" and",
"event.message_type != \"group\": return arg = str(event.get_message()) group_members = await",
"song_txt(music))) music_aliases = defaultdict(list) f = open('src/static/aliases.csv', 'r', encoding='utf-8') tmp",
"and m['role'] != 'admin' and str(m['user_id']) not in su: await",
"guess_dict[k] = guess state[\"k\"] = k state[\"guess_object\"] = guess state[\"cycle\"]",
"res.groups()[1] == \"\": music_data = total_list.filter(level=level, type=tp) else: music_data =",
"import logger from nonebot.permission import Permission from nonebot.typing import T_State",
"= state[\"guess_object\"] if guess.is_end: return asyncio.create_task(bot.send(event, Message([MessageSegment.text(\"答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"),",
"谱师: {chart['charter']} ''' await query_chart.send(Message([ { \"type\": \"text\", \"data\": {",
"guess_table where group_id={gid}\") data = await c.fetchone() if data is",
"def _(bot: Bot, event: Event, state: T_State): level_labels = ['绿',",
"0: s += f'忌 {wm_list[i]}\\n' s += \"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\" music =",
"await spec_rand.finish(\"随机命令错误,请检查语法\") mr = on_regex(r\".*maimai.*什么\") @mr.handle() async def _(bot: Bot,",
"query_chart.send(\"未找到该谱面\") else: name = groups[1] music = total_list.by_id(name) try: file",
"= groups[1] music = total_list.by_id(name) chart = music['charts'][level_index] ds =",
"music['level'][level_index] file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" if len(chart['notes']) == 4: msg =",
"diff_label[i], music['level'][i])) return result_set inner_level = on_command('inner_level ', aliases={'定数查歌 '})",
"encoding='utf-8')}\" } }]) @query_score.handle() async def _(bot: Bot, event: Event,",
"total_score * 100:.4f}%)''') except Exception: await query_chart.send(\"格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息\") best_40_pic =",
"SLIDE 3/7.5/15 TOUCH 1/2.5/5 BREAK 5/12.5/25(外加200落)''' query_score_mes = Message([{ \"type\":",
"r = \"([绿黄红紫白])(?:id)?([0-9]+)\" argv = str(event.get_message()).strip().split(\" \") if len(argv) ==",
"find_song.finish(\"未找到此歌曲\\n舞萌 DX 歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\") return result_set = music_aliases[name] if len(result_set) ==",
"今日舞萌 查看今天的舞萌运势 XXXmaimaiXXX什么 随机一首歌 随个[dx/标准][绿黄红紫白]<难度> 随机一首指定条件的乐曲 查歌<乐曲标题的一部分> 查询符合条件的乐曲 [绿黄红紫白]id<歌曲编号> 查询乐曲信息或谱面信息",
"in su: await disable_guess_music.finish(\"只有管理员可以设置猜歌\") return db = get_driver().config.db c =",
"[\"DX\"] elif res.groups()[0] == \"sd\" or res.groups()[0] == \"标准\": tp",
"= 101 - line if reduce <= 0 or reduce",
"guess_music_solve.send(ans + \"|\" + guess.music['id']) if ans == guess.music['id'] or",
"== \"\": payload = {'qq': str(event.get_user_id())} else: payload = {'username':",
"state)) return state[\"cycle\"] += 1 asyncio.create_task(guess_music_loop(bot, event, state)) async def",
"= h % 100 wm_value = [] for i in",
"100 命令将返回分数线允许的 TAP GREAT 容错以及 BREAK 50落等价的 TAP GREAT 数。",
"Bot, event: Event, state: T_State): argv = str(event.get_message()).strip().split(\" \") if",
"\"type\": \"text\", \"data\": { \"text\": f\"\\n{'/'.join(music.level)}\" } } ]) def",
"白337 100 命令将返回分数线允许的 TAP GREAT 容错以及 BREAK 50落等价的 TAP GREAT",
"event.user_id: break su = get_driver().config.superusers if m['role'] != 'owner' and",
"HOLD 2/5/10 SLIDE 3/7.5/15 TOUCH 1/2.5/5 BREAK 5/12.5/25(外加200落)''' query_score_mes =",
"'紫', '白'] regex = \"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\" res = re.match(regex, str(event.get_message()).lower()) try:",
"from urllib import parse driver = get_driver() @driver.on_startup def _():",
"* break_bonus / 4 reduce = 101 - line if",
"and gid in whitelists): if len(guess_dict) >= 5: await guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\")",
"if k in guess_cd_dict and time.time() < guess_cd_dict[k]: await guess_music.finish(f\"已经猜过啦,下次猜歌会在",
"state: T_State): await asyncio.sleep(30) guess: GuessObject = state[\"guess_object\"] if guess.is_end:",
"get_driver().config.whitelists if not (mt == \"group\" and gid in whitelists):",
"enabled=0 where group_id={event.group_id}') else: await disable_guess_music.finish(\"请输入 猜歌设置 启用/禁用\") await db.commit()",
"level_index = level_labels.index(grp[0]) chart_id = grp[1] line = float(argv[1]) music",
"- 400: # 如果已经过了 200 秒则自动结束上一次 del guess_dict[k] else: await",
"data = await c.fetchone() if data is None: await c.execute(f'insert",
"'下埋', '夜勤', '练底力', '练手法', '打旧框', '干饭', '抓绝赞', '收歌'] jrwm =",
"< 6: asyncio.create_task(bot.send(event, f\"{cycle + 1}/7 这首歌\" + guess.guess_options[cycle])) else:",
"= total_score * break_bonus / 4 reduce = 101 -",
"400: await best_40_pic.send(\"未找到此玩家,请确保此玩家的用户名和查分器中的用户名相同。\") elif success == 403: await best_40_pic.send(\"该用户禁止了其他人获取数据。\") else:",
"not in music_aliases: await find_song.finish(\"未找到此歌曲\\n舞萌 DX 歌曲别名收集计划:https://docs.qq.com/sheet/DSXhaUXVsRlhxRmtJ\") return result_set =",
"k = (mt, event.user_id if mt == \"private\" else event.group_id)",
"where group_id={gid}\") data = await c.fetchone() if data is None:",
"{music['basic_info']['genre']}\\nBPM: {music['basic_info']['bpm']}\\n版本: {music['basic_info']['from']}\\n难度: {'/'.join(music['level'])}\" } } ])) except Exception: await",
"{ \"type\": \"text\", \"data\": { \"text\": f\"{music['id']}. {music['title']}\\n\" } },",
"个 TAP GREAT(-{break_50_reduce / total_score * 100:.4f}%)''') except Exception: await",
"guess_cd_dict and time.time() > guess_cd_dict[k] - 400: # 如果已经过了 200",
"= get_driver().config.whitelists if not (mt == \"group\" and gid in",
"'Re: MASTER'] name = groups[1] music = total_list.by_id(name) chart =",
"i in range(11): if wm_value[i] == 3: s += f'宜",
"}, { \"type\": \"text\", \"data\": { \"text\": f\"\\n{'/'.join(music.level)}\" } }",
"str(guess.b64image, encoding=\"utf-8\")), MessageSegment.text(\"答案将在 30 秒后揭晓\") ]))) asyncio.create_task(give_answer(bot, event, state)) return",
"mt == \"private\" else event.group_id) if mt == \"group\": gid",
"= int(chart['notes'][3]) if len(chart['notes']) == 5 else 0 brk =",
"个以上连续的字符】进行猜歌(DX乐谱和标准乐谱视为两首歌)。猜歌时查歌等其他命令依然可用。\\n警告:这个命令可能会很刷屏,管理员可以使用【猜歌设置】指令进行设置。\") asyncio.create_task(guess_music_loop(bot, event, state)) guess_music_solve = on_message(priority=20) @guess_music_solve.handle() async def",
"\"file\": f\"https://www.diving-fish.com/covers/{music.id}.jpg\" } }, { \"type\": \"text\", \"data\": { \"text\":",
"f\"{music['id']}. {music['title']}\\n\" }} for music in res])) query_chart = on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\")",
"await guess_music.finish(f\"已经猜过啦,下次猜歌会在 {time.strftime('%H:%M', time.localtime(guess_cd_dict[k]))} 可用噢\") return guess = GuessObject() guess_dict[k]",
"if len(guess_dict) >= 5: await guess_music.finish(\"千雪有点忙不过来了。现在正在猜的群有点多,晚点再试试如何?\") return if k in",
"return if k in guess_cd_dict and time.time() < guess_cd_dict[k]: await",
"= float(argv[1]) music = total_list.by_id(chart_id) chart: Dict[Any] = music['charts'][level_index] tap",
"= {} guess_music = on_command('猜歌', priority=0) async def guess_music_loop(bot: Bot,",
"= get_driver().config.help_text help_text['mai'] = ('查看舞萌相关功能', \"\"\"桜千雪です、よろしく。 可用命令如下: 今日舞萌 查看今天的舞萌运势 XXXmaimaiXXX什么",
"c = await db.cursor() if arg == '启用': await c.execute(f'update",
"await query_chart.send(\"格式错误或未找到乐曲,输入“分数线 帮助”以查看帮助信息\") best_40_pic = on_command('b40') @best_40_pic.handle() async def _(bot:",
"encoding='utf-8') tmp = f.readlines() f.close() for t in tmp: arr",
"reduce = 101 - line if reduce <= 0 or",
"= total_list.by_id(chart_id) chart: Dict[Any] = music['charts'][level_index] tap = int(chart['notes'][0]) slide",
"def inner_level_q(ds1, ds2=None): result_set = [] diff_label = ['Bas', 'Adv',",
"guess.is_end: return asyncio.create_task(bot.send(event, Message([MessageSegment.text(\"答案是:\" + f\"{guess.music['id']}. {guess.music['title']}\\n\"), MessageSegment.image(f\"https://www.diving-fish.com/covers/{guess.music['id']}.jpg\")]))) del guess_dict[state[\"k\"]]",
"res.groups()[2] if res.groups()[1] == \"\": music_data = total_list.filter(level=level, type=tp) else:",
"= state[\"guess_object\"] if guess.is_end: return cycle = state[\"cycle\"] if cycle",
"in res])) query_chart = on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\") @query_chart.handle() async def _(bot: Bot,",
"0: await guess_music.send(\"本群已禁用猜歌\") return if k in guess_dict: if k",
"and argv[0] == '帮助': await query_score.send(query_score_mes) elif len(argv) == 2:",
"!= 'admin' and str(m['user_id']) not in su: await disable_guess_music.finish(\"只有管理员可以设置猜歌\") return",
"s += f\"{elem[0]}. {elem[1]} {elem[3]} {elem[4]}({elem[2]})\\n\" await inner_level.finish(s.strip()) spec_rand =",
"event.user_id if mt == \"private\" else event.group_id) if k not",
"= total_list.filter(ds=ds1) for music in music_data: for i in music.diff:",
"str(event.get_message()).strip().split(\" \") if len(argv) > 2 or len(argv) == 0:",
"'紫', '白'] if groups[0] != \"\": try: level_index = level_labels.index(groups[0])",
"= defaultdict(list) f = open('src/static/aliases.csv', 'r', encoding='utf-8') tmp = f.readlines()",
"if ans == guess.music['id'] or (ans.lower() == guess.music['title'].lower()) or (len(ans)",
"if m['role'] != 'owner' and m['role'] != 'admin' and str(m['user_id'])",
"{ \"type\": \"text\", \"data\": { \"text\": f\"{music.id}. {music.title}\\n\" } },",
"await guess_music.send(\"本群已禁用猜歌\") return if k in guess_dict: if k in",
"img, success = await generate(payload) if success == 400: await",
"= await db.cursor() await c.execute(f\"select * from guess_table where group_id={gid}\")",
"= on_regex(r\"^([绿黄红紫白]?)id([0-9]+)\") @query_chart.handle() async def _(bot: Bot, event: Event, state:",
"TAP GREAT 数量为 {(total_score * reduce / 10000):.2f}(每个-{10000 / total_score:.4f}%),",
"* 2500 break_bonus = 0.01 / brk break_50_reduce = total_score",
"and time.time() > guess_cd_dict[k] - 400: # 如果已经过了 200 秒则自动结束上一次",
"} } ]) def inner_level_q(ds1, ds2=None): result_set = [] diff_label",
"{chart['notes'][2]} BREAK: {chart['notes'][3]} 谱师: {chart['charter']} ''' else: msg = f'''{level_name[level_index]}",
"if len(argv) == 1 and argv[0] == '帮助': await query_score.send(query_score_mes)",
"else: await guess_music.send(\"当前已有正在进行的猜歌\") return whitelists = get_driver().config.whitelists if not (mt",
"regex = \"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\" res = re.match(regex, str(event.get_message()).lower()) try: if res.groups()[0]",
"\"image\", \"data\": { \"file\": f\"https://www.diving-fish.com/covers/{music.id}.jpg\" } }, { \"type\": \"text\",",
"{chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} TOUCH: {chart['notes'][3]} BREAK: {chart['notes'][4]} 谱师:",
"GREAT/GOOD/MISS TAP 1/2.5/5 HOLD 2/5/10 SLIDE 3/7.5/15 TOUCH 1/2.5/5 BREAK",
"= music['charts'][level_index] ds = music['ds'][level_index] level = music['level'][level_index] file =",
"TAP: {chart['notes'][0]} HOLD: {chart['notes'][1]} SLIDE: {chart['notes'][2]} TOUCH: {chart['notes'][3]} BREAK: {chart['notes'][4]}",
"Bot, event: Event, state: T_State): username = str(event.get_message()).strip() print(event.message_id) if",
"f'宜 {wm_list[i]}\\n' elif wm_value[i] == 0: s += f'忌 {wm_list[i]}\\n'",
"'白'] regex = \"随个((?:dx|sd|标准))?([绿黄红紫白]?)([0-9]+\\+?)\" res = re.match(regex, str(event.get_message()).lower()) try: if",
"BREAK 50落(一共{brk}个)等价于 {(break_50_reduce / 100):.3f} 个 TAP GREAT(-{break_50_reduce / total_score",
"nonebot.adapters.cqhttp import Message, MessageSegment, GroupMessageEvent, PrivateMessageEvent from src.libraries.maimaidx_guess import GuessObject",
"s += \"千雪提醒您:打机时不要大力拍打或滑动哦\\n今日推荐歌曲:\" music = total_list[h2 % len(total_list)] await jrwm.finish(Message([",
"guess_dict: Dict[Tuple[str, str], GuessObject] = {} guess_cd_dict: Dict[Tuple[str, str], float]",
">>= 2 s = f\"今日人品值:{rp}\\n\" for i in range(11): if",
"= on_regex(r\"^查歌.+\") @search_music.handle() async def _(bot: Bot, event: Event, state:",
"if groups[0] != \"\": try: level_index = level_labels.index(groups[0]) level_name =",
"'Master', 'Re: MASTER'] name = groups[1] music = total_list.by_id(name) chart",
"asyncio.create_task(bot.send(event, f\"{cycle + 1}/7 这首歌\" + guess.guess_options[cycle])) else: asyncio.create_task(bot.send(event, Message([",
"['Basic', 'Advanced', 'Expert', 'Master', 'Re:MASTER'] level_index = level_labels.index(grp[0]) chart_id =",
"{line}% 允许的最多 TAP GREAT 数量为 {(total_score * reduce / 10000):.2f}(每个-{10000",
"total_list.filter(ds=ds1) for music in music_data: for i in music.diff: result_set.append((music['id'],",
"total_list.by_id(name) try: file = f\"https://www.diving-fish.com/covers/{music['id']}.jpg\" await query_chart.send(Message([ { \"type\": \"text\",",
"await asyncio.sleep(10) guess: GuessObject = state[\"guess_object\"] if guess.is_end: return cycle",
"event.group_id db = get_driver().config.db c = await db.cursor() await c.execute(f\"select",
"def _(bot: Bot, event: Event, state: T_State): argv = str(event.get_message()).strip().split(\""
] |
[
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"Communication from trace_analysis.node import Node UNDEFINED_STR = \"UNDEFINED\" class PathAlias:",
"# # 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,",
"def path_aliases(self) -> List[PathAlias]: pass @property @abstractmethod def communications(self) ->",
"distributed under the License is distributed on an \"AS IS\"",
"@property @abstractmethod def path_aliases(self) -> List[PathAlias]: pass @property @abstractmethod def",
"abc import ABCMeta, abstractmethod from trace_analysis.callback import CallbackBase from trace_analysis.communication",
"from trace_analysis.node import Node UNDEFINED_STR = \"UNDEFINED\" class PathAlias: def",
"pass @abstractmethod def exec(self, path: str, ignore_topics: Optional[List[str]] = None)",
"the specific language governing permissions and # limitations under the",
"@property @abstractmethod def nodes(self) -> List[Node]: pass @property @abstractmethod def",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"Planning, Inc. # # Licensed under the Apache License, Version",
"CallbackBase from trace_analysis.communication import VariablePassing, Communication from trace_analysis.node import Node",
"def nodes(self) -> List[Node]: pass @property @abstractmethod def path_aliases(self) ->",
"class ArchitectureInterface(metaclass=ABCMeta): @property @abstractmethod def nodes(self) -> List[Node]: pass @property",
"pass @property @abstractmethod def path_aliases(self) -> List[PathAlias]: pass @property @abstractmethod",
"express or implied. # See the License for the specific",
"applicable law or agreed to in writing, software # distributed",
"<gh_stars>0 # Copyright 2021 Research Institute of Systems Planning, Inc.",
"except in compliance with the License. # You may obtain",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"nodes(self) -> List[Node]: pass @property @abstractmethod def path_aliases(self) -> List[PathAlias]:",
"path_aliases(self) -> List[PathAlias]: pass @property @abstractmethod def communications(self) -> List[Communication]:",
"class ArchitectureImporter(ArchitectureInterface): @abstractmethod def __init__(self) -> None: pass @abstractmethod def",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"List, Optional from abc import ABCMeta, abstractmethod from trace_analysis.callback import",
"not use this file except in compliance with the License.",
"limitations under the License. from typing import List, Optional from",
"-> List[Node]: pass @property @abstractmethod def path_aliases(self) -> List[PathAlias]: pass",
"ArchitectureExporter(metaclass=ABCMeta): @abstractmethod def exec(self, architecture: ArchitectureInterface, path) -> None: pass",
"__init__(self, alias: str, callback_names: List[str]): self.path_name = alias self.callback_names =",
"from trace_analysis.communication import VariablePassing, Communication from trace_analysis.node import Node UNDEFINED_STR",
"writing, software # distributed under the License is distributed on",
"2021 Research Institute of Systems Planning, Inc. # # Licensed",
"in writing, software # distributed under the License is distributed",
"@abstractmethod def __init__(self) -> None: pass @abstractmethod def exec(self, path:",
"= None) -> None: pass class ArchitectureExporter(metaclass=ABCMeta): @abstractmethod def exec(self,",
"def __init__(self, alias: str, callback_names: List[str]): self.path_name = alias self.callback_names",
"you may not use this file except in compliance with",
"VariablePassing, Communication from trace_analysis.node import Node UNDEFINED_STR = \"UNDEFINED\" class",
"@property @abstractmethod def variable_passings(self) -> List[VariablePassing]: pass class ArchitectureImporter(ArchitectureInterface): @abstractmethod",
"alias: str, callback_names: List[str]): self.path_name = alias self.callback_names = callback_names",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"from typing import List, Optional from abc import ABCMeta, abstractmethod",
"@property @abstractmethod def communications(self) -> List[Communication]: pass @property @abstractmethod def",
"language governing permissions and # limitations under the License. from",
"str, callback_names: List[str]): self.path_name = alias self.callback_names = callback_names class",
"-> None: pass @abstractmethod def exec(self, path: str, ignore_topics: Optional[List[str]]",
"ignore_topics: Optional[List[str]] = None) -> None: pass class ArchitectureExporter(metaclass=ABCMeta): @abstractmethod",
"import VariablePassing, Communication from trace_analysis.node import Node UNDEFINED_STR = \"UNDEFINED\"",
"governing permissions and # limitations under the License. from typing",
"use this file except in compliance with the License. #",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"trace_analysis.communication import VariablePassing, Communication from trace_analysis.node import Node UNDEFINED_STR =",
"exec(self, path: str, ignore_topics: Optional[List[str]] = None) -> None: pass",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"ABCMeta, abstractmethod from trace_analysis.callback import CallbackBase from trace_analysis.communication import VariablePassing,",
"self.path_name = alias self.callback_names = callback_names class ArchitectureInterface(metaclass=ABCMeta): @property @abstractmethod",
"Institute of Systems Planning, Inc. # # Licensed under the",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"the License. from typing import List, Optional from abc import",
"from trace_analysis.callback import CallbackBase from trace_analysis.communication import VariablePassing, Communication from",
"import Node UNDEFINED_STR = \"UNDEFINED\" class PathAlias: def __init__(self, alias:",
"or implied. # See the License for the specific language",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"callback_names class ArchitectureInterface(metaclass=ABCMeta): @property @abstractmethod def nodes(self) -> List[Node]: pass",
"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",
"# 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.",
"-> None: pass class ArchitectureExporter(metaclass=ABCMeta): @abstractmethod def exec(self, architecture: ArchitectureInterface,",
"under the License is distributed on an \"AS IS\" BASIS,",
"and # limitations under the License. from typing import List,",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"License for the specific language governing permissions and # limitations",
"__init__(self) -> None: pass @abstractmethod def exec(self, path: str, ignore_topics:",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"def communications(self) -> List[Communication]: pass @property @abstractmethod def variable_passings(self) ->",
"List[str]): self.path_name = alias self.callback_names = callback_names class ArchitectureInterface(metaclass=ABCMeta): @property",
"pass class ArchitectureExporter(metaclass=ABCMeta): @abstractmethod def exec(self, architecture: ArchitectureInterface, path) ->",
"# Copyright 2021 Research Institute of Systems Planning, Inc. #",
"def variable_passings(self) -> List[VariablePassing]: pass class ArchitectureImporter(ArchitectureInterface): @abstractmethod def __init__(self)",
"@abstractmethod def nodes(self) -> List[Node]: pass @property @abstractmethod def path_aliases(self)",
"@abstractmethod def exec(self, path: str, ignore_topics: Optional[List[str]] = None) ->",
"License. from typing import List, Optional from abc import ABCMeta,",
"Copyright 2021 Research Institute of Systems Planning, Inc. # #",
"the License for the specific language governing permissions and #",
"self.callback_names = callback_names class ArchitectureInterface(metaclass=ABCMeta): @property @abstractmethod def nodes(self) ->",
"(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",
"UNDEFINED_STR = \"UNDEFINED\" class PathAlias: def __init__(self, alias: str, callback_names:",
"pass @property @abstractmethod def communications(self) -> List[Communication]: pass @property @abstractmethod",
"import List, Optional from abc import ABCMeta, abstractmethod from trace_analysis.callback",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"ArchitectureImporter(ArchitectureInterface): @abstractmethod def __init__(self) -> None: pass @abstractmethod def exec(self,",
"def __init__(self) -> None: pass @abstractmethod def exec(self, path: str,",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"-> List[PathAlias]: pass @property @abstractmethod def communications(self) -> List[Communication]: pass",
"the License is distributed on an \"AS IS\" BASIS, #",
"in compliance with the License. # You may obtain a",
"trace_analysis.node import Node UNDEFINED_STR = \"UNDEFINED\" class PathAlias: def __init__(self,",
"software # distributed under the License is distributed on an",
"permissions and # limitations under the License. from typing import",
"PathAlias: def __init__(self, alias: str, callback_names: List[str]): self.path_name = alias",
"@abstractmethod def variable_passings(self) -> List[VariablePassing]: pass class ArchitectureImporter(ArchitectureInterface): @abstractmethod def",
"# # Unless required by applicable law or agreed to",
"pass @property @abstractmethod def variable_passings(self) -> List[VariablePassing]: pass class ArchitectureImporter(ArchitectureInterface):",
"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",
"ArchitectureInterface(metaclass=ABCMeta): @property @abstractmethod def nodes(self) -> List[Node]: pass @property @abstractmethod",
"Version 2.0 (the \"License\"); # you may not use this",
"trace_analysis.callback import CallbackBase from trace_analysis.communication import VariablePassing, Communication from trace_analysis.node",
"= callback_names class ArchitectureInterface(metaclass=ABCMeta): @property @abstractmethod def nodes(self) -> List[Node]:",
"alias self.callback_names = callback_names class ArchitectureInterface(metaclass=ABCMeta): @property @abstractmethod def nodes(self)",
"None: pass class ArchitectureExporter(metaclass=ABCMeta): @abstractmethod def exec(self, architecture: ArchitectureInterface, path)",
"Research Institute of Systems Planning, Inc. # # Licensed under",
"law or agreed to in writing, software # distributed under",
"class ArchitectureExporter(metaclass=ABCMeta): @abstractmethod def exec(self, architecture: ArchitectureInterface, path) -> None:",
"List[Node]: pass @property @abstractmethod def path_aliases(self) -> List[PathAlias]: pass @property",
"import ABCMeta, abstractmethod from trace_analysis.callback import CallbackBase from trace_analysis.communication import",
"str, ignore_topics: Optional[List[str]] = None) -> None: pass class ArchitectureExporter(metaclass=ABCMeta):",
"variable_passings(self) -> List[VariablePassing]: pass class ArchitectureImporter(ArchitectureInterface): @abstractmethod def __init__(self) ->",
"path: str, ignore_topics: Optional[List[str]] = None) -> None: pass class",
"\"UNDEFINED\" class PathAlias: def __init__(self, alias: str, callback_names: List[str]): self.path_name",
"implied. # See the License for the specific language governing",
"List[PathAlias]: pass @property @abstractmethod def communications(self) -> List[Communication]: pass @property",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"\"License\"); # you may not use this file except in",
"communications(self) -> List[Communication]: pass @property @abstractmethod def variable_passings(self) -> List[VariablePassing]:",
"List[Communication]: pass @property @abstractmethod def variable_passings(self) -> List[VariablePassing]: pass class",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"typing import List, Optional from abc import ABCMeta, abstractmethod from",
"import CallbackBase from trace_analysis.communication import VariablePassing, Communication from trace_analysis.node import",
"abstractmethod from trace_analysis.callback import CallbackBase from trace_analysis.communication import VariablePassing, Communication",
"@abstractmethod def path_aliases(self) -> List[PathAlias]: pass @property @abstractmethod def communications(self)",
"of Systems Planning, Inc. # # Licensed under the Apache",
"pass class ArchitectureImporter(ArchitectureInterface): @abstractmethod def __init__(self) -> None: pass @abstractmethod",
"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.",
"= \"UNDEFINED\" class PathAlias: def __init__(self, alias: str, callback_names: List[str]):",
"callback_names: List[str]): self.path_name = alias self.callback_names = callback_names class ArchitectureInterface(metaclass=ABCMeta):",
"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",
"-> List[Communication]: pass @property @abstractmethod def variable_passings(self) -> List[VariablePassing]: pass",
"def exec(self, path: str, ignore_topics: Optional[List[str]] = None) -> None:",
"under the License. from typing import List, Optional from abc",
"Optional[List[str]] = None) -> None: pass class ArchitectureExporter(metaclass=ABCMeta): @abstractmethod def",
"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",
"class PathAlias: def __init__(self, alias: str, callback_names: List[str]): self.path_name =",
"None: pass @abstractmethod def exec(self, path: str, ignore_topics: Optional[List[str]] =",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"to in writing, software # distributed under the License is",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"Inc. # # Licensed under the Apache License, Version 2.0",
"# See the License for the specific language governing permissions",
"Systems Planning, Inc. # # Licensed under the Apache License,",
"= alias self.callback_names = callback_names class ArchitectureInterface(metaclass=ABCMeta): @property @abstractmethod def",
"from abc import ABCMeta, abstractmethod from trace_analysis.callback import CallbackBase from",
"You may obtain a copy of the License at #",
"may not use this file except in compliance with the",
"or agreed to in writing, software # distributed under the",
"-> List[VariablePassing]: pass class ArchitectureImporter(ArchitectureInterface): @abstractmethod def __init__(self) -> None:",
"required by applicable law or agreed to in writing, software",
"List[VariablePassing]: pass class ArchitectureImporter(ArchitectureInterface): @abstractmethod def __init__(self) -> None: pass",
"None) -> None: pass class ArchitectureExporter(metaclass=ABCMeta): @abstractmethod def exec(self, architecture:",
"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",
"@abstractmethod def communications(self) -> List[Communication]: pass @property @abstractmethod def variable_passings(self)",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"# limitations under the License. from typing import List, Optional",
"Node UNDEFINED_STR = \"UNDEFINED\" class PathAlias: def __init__(self, alias: str,",
"Optional from abc import ABCMeta, abstractmethod from trace_analysis.callback import CallbackBase"
] |
[] |
[
"training=self.training) return h class ApplyNodeFunc(nn.Module): \"\"\" This class is used",
"+ g.ndata['neigh'] if self.apply_func is not None: h = self.apply_func(h)",
"NETWORKS? (<NAME>, <NAME>, <NAME> and <NAME>, ICLR 2019) https://arxiv.org/pdf/1810.00826.pdf \"\"\"",
"for using residual connection. init_eps : optional Initial :math:`\\epsilon` value,",
"eps is trainable or not. if learn_eps: self.eps = torch.nn.Parameter(torch.FloatTensor([init_eps]))",
"apply this function to the updated node feature, the :math:`f_\\Theta`",
"hidden_dim)) self.linears.append(nn.Linear(hidden_dim, output_dim)) for layer in range(num_layers - 1): self.batch_norms.append(nn.BatchNorm1d((hidden_dim)))",
"specify whether eps is trainable or not. if learn_eps: self.eps",
"= h* snorm_n # normalize activation w.r.t. graph size if",
"activation w.r.t. graph size if self.batch_norm: h = self.bn_node_h(h) #",
"connection g = g.local_var() g.ndata['h'] = h g.update_all(fn.copy_u('h', 'm'), self._reducer('m',",
"= graph_norm self.batch_norm = batch_norm self.residual = residual self.dropout =",
"self.output_dim = output_dim self.input_dim = input_dim if num_layers < 1:",
"for layer in range(num_layers - 1): self.batch_norms.append(nn.BatchNorm1d((hidden_dim))) def forward(self, x):",
"function to the updated node feature, the :math:`f_\\Theta` in the",
"self.apply_func is not None: h = self.apply_func(h) if self.graph_norm: h",
"w.r.t. graph size if self.batch_norm: h = self.bn_node_h(h) # batch",
"output features normalization w.r.t. graph sizes. batch_norm : boolean flag",
"and <NAME>, ICLR 2019) https://arxiv.org/pdf/1810.00826.pdf \"\"\" class GINLayer(nn.Module): \"\"\" [!]",
"match out_dim of apply_func if not None. dropout : Required",
"super().__init__() self.linear_or_not = True # default is linear model self.num_layers",
"as F import dgl.function as fn \"\"\" GIN: Graph Isomorphism",
"HOW POWERFUL ARE GRAPH NEURAL NETWORKS? (<NAME>, <NAME>, <NAME> and",
"to specify whether eps is trainable or not. if learn_eps:",
"forward(self, g, h, snorm_n): h_in = h # for residual",
"---------- apply_func : callable activation function/layer or None If not",
":math:`f_\\Theta` in the formula. aggr_type : Aggregator type to use",
"is not None: h = self.apply_func(h) if self.graph_norm: h =",
"class GINNet Update the node feature hv with MLP \"\"\"",
"of output features. graph_norm : boolean flag for output features",
"graph size if self.batch_norm: h = self.bn_node_h(h) # batch normalization",
"used in class GINNet Update the node feature hv with",
"= fn.mean else: raise KeyError('Aggregator type {} not recognized.'.format(aggr_type)) self.graph_norm",
"1): self.batch_norms.append(nn.BatchNorm1d((hidden_dim))) def forward(self, x): if self.linear_or_not: # If linear",
"self.linear(x) else: # If MLP h = x for i",
"default: ``0``. learn_eps : bool, optional If True, :math:`\\epsilon` will",
"Multi-layer model self.linear_or_not = False self.linears = torch.nn.ModuleList() self.batch_norms =",
"layer; should match out_dim of apply_func if not None. dropout",
"def forward(self, h): h = self.mlp(h) return h class MLP(nn.Module):",
"1: raise ValueError(\"number of layers should be positive!\") elif num_layers",
"= h_in + h # residual connection h = F.dropout(h,",
"code adapted from dgl implementation of GINConv Parameters ---------- apply_func",
"self.bn_node_h = nn.BatchNorm1d(out_dim) def forward(self, g, h, snorm_n): h_in =",
"node feature hv with MLP \"\"\" def __init__(self, mlp): super().__init__()",
"GINNet Update the node feature hv with MLP \"\"\" def",
"sizes. batch_norm : boolean flag for batch_norm layer. residual :",
"boolean flag for batch_norm layer. residual : boolean flag for",
"dropout : Required for dropout of output features. graph_norm :",
"(1 + self.eps) * h + g.ndata['neigh'] if self.apply_func is",
"optional If True, :math:`\\epsilon` will be a learnable parameter. \"\"\"",
"KeyError('Aggregator type {} not recognized.'.format(aggr_type)) self.graph_norm = graph_norm self.batch_norm =",
"layer in range(num_layers - 2): self.linears.append(nn.Linear(hidden_dim, hidden_dim)) self.linears.append(nn.Linear(hidden_dim, output_dim)) for",
"batch norm layer; should match out_dim of apply_func if not",
"residual connection. init_eps : optional Initial :math:`\\epsilon` value, default: ``0``.",
"h = h* snorm_n # normalize activation w.r.t. graph size",
"else: # Multi-layer model self.linear_or_not = False self.linears = torch.nn.ModuleList()",
"'neigh')) h = (1 + self.eps) * h + g.ndata['neigh']",
"in the formula. aggr_type : Aggregator type to use (``sum``,",
"= h g.update_all(fn.copy_u('h', 'm'), self._reducer('m', 'neigh')) h = (1 +",
"= apply_func if aggr_type == 'sum': self._reducer = fn.sum elif",
"h = (1 + self.eps) * h + g.ndata['neigh'] if",
"ApplyNodeFunc(nn.Module): \"\"\" This class is used in class GINNet Update",
"= False self.linears = torch.nn.ModuleList() self.batch_norms = torch.nn.ModuleList() self.linears.append(nn.Linear(input_dim, hidden_dim))",
"else: # If MLP h = x for i in",
"return self.linear(x) else: # If MLP h = x for",
"!= out_dim: self.residual = False # to specify whether eps",
"https://arxiv.org/pdf/1810.00826.pdf \"\"\" class GINLayer(nn.Module): \"\"\" [!] code adapted from dgl",
"input_dim, hidden_dim, output_dim): super().__init__() self.linear_or_not = True # default is",
"False self.linears = torch.nn.ModuleList() self.batch_norms = torch.nn.ModuleList() self.linears.append(nn.Linear(input_dim, hidden_dim)) for",
"residual connection h = F.dropout(h, self.dropout, training=self.training) return h class",
"not None: h = self.apply_func(h) if self.graph_norm: h = h*",
"GRAPH NEURAL NETWORKS? (<NAME>, <NAME>, <NAME> and <NAME>, ICLR 2019)",
"for residual connection g = g.local_var() g.ndata['h'] = h g.update_all(fn.copy_u('h',",
"self.batch_norm = batch_norm self.residual = residual self.dropout = dropout in_dim",
"h = self.mlp(h) return h class MLP(nn.Module): \"\"\"MLP with linear",
"torch.nn.Parameter(torch.FloatTensor([init_eps])) else: self.register_buffer('eps', torch.FloatTensor([init_eps])) self.bn_node_h = nn.BatchNorm1d(out_dim) def forward(self, g,",
"import torch import torch.nn as nn import torch.nn.functional as F",
"__init__(self, num_layers, input_dim, hidden_dim, output_dim): super().__init__() self.linear_or_not = True #",
"g.local_var() g.ndata['h'] = h g.update_all(fn.copy_u('h', 'm'), self._reducer('m', 'neigh')) h =",
"class GINLayer(nn.Module): \"\"\" [!] code adapted from dgl implementation of",
"not None, apply this function to the updated node feature,",
"self.linears.append(nn.Linear(hidden_dim, output_dim)) for layer in range(num_layers - 1): self.batch_norms.append(nn.BatchNorm1d((hidden_dim))) def",
"a learnable parameter. \"\"\" def __init__(self, apply_func, aggr_type, dropout, graph_norm,",
"(``sum``, ``max`` or ``mean``). out_dim : Rquired for batch norm",
"flag for output features normalization w.r.t. graph sizes. batch_norm :",
"self.dropout, training=self.training) return h class ApplyNodeFunc(nn.Module): \"\"\" This class is",
"flag for batch_norm layer. residual : boolean flag for using",
"= self.apply_func(h) if self.graph_norm: h = h* snorm_n # normalize",
"# batch normalization h = F.relu(h) # non-linear activation if",
"if self.graph_norm: h = h* snorm_n # normalize activation w.r.t.",
"linear output\"\"\" def __init__(self, num_layers, input_dim, hidden_dim, output_dim): super().__init__() self.linear_or_not",
"range(num_layers - 1): self.batch_norms.append(nn.BatchNorm1d((hidden_dim))) def forward(self, x): if self.linear_or_not: #",
"formula. aggr_type : Aggregator type to use (``sum``, ``max`` or",
"# for residual connection g = g.local_var() g.ndata['h'] = h",
"'sum': self._reducer = fn.sum elif aggr_type == 'max': self._reducer =",
"graph sizes. batch_norm : boolean flag for batch_norm layer. residual",
"should match out_dim of apply_func if not None. dropout :",
"True # default is linear model self.num_layers = num_layers self.output_dim",
"if self.residual: h = h_in + h # residual connection",
"be a learnable parameter. \"\"\" def __init__(self, apply_func, aggr_type, dropout,",
"= F.dropout(h, self.dropout, training=self.training) return h class ApplyNodeFunc(nn.Module): \"\"\" This",
"linear model return self.linear(x) else: # If MLP h =",
"'m'), self._reducer('m', 'neigh')) h = (1 + self.eps) * h",
"Initial :math:`\\epsilon` value, default: ``0``. learn_eps : bool, optional If",
"self.linear_or_not = False self.linears = torch.nn.ModuleList() self.batch_norms = torch.nn.ModuleList() self.linears.append(nn.Linear(input_dim,",
"(<NAME>, <NAME>, <NAME> and <NAME>, ICLR 2019) https://arxiv.org/pdf/1810.00826.pdf \"\"\" class",
"self.linears.append(nn.Linear(input_dim, hidden_dim)) for layer in range(num_layers - 2): self.linears.append(nn.Linear(hidden_dim, hidden_dim))",
"h_in + h # residual connection h = F.dropout(h, self.dropout,",
"self._reducer = fn.sum elif aggr_type == 'max': self._reducer = fn.max",
"for batch norm layer; should match out_dim of apply_func if",
"def __init__(self, apply_func, aggr_type, dropout, graph_norm, batch_norm, residual=False, init_eps=0, learn_eps=False):",
"If not None, apply this function to the updated node",
"h class ApplyNodeFunc(nn.Module): \"\"\" This class is used in class",
"connection h = F.dropout(h, self.dropout, training=self.training) return h class ApplyNodeFunc(nn.Module):",
"MLP \"\"\" def __init__(self, mlp): super().__init__() self.mlp = mlp def",
"2019) https://arxiv.org/pdf/1810.00826.pdf \"\"\" class GINLayer(nn.Module): \"\"\" [!] code adapted from",
"use (``sum``, ``max`` or ``mean``). out_dim : Rquired for batch",
"w.r.t. graph sizes. batch_norm : boolean flag for batch_norm layer.",
"from dgl implementation of GINConv Parameters ---------- apply_func : callable",
"h = x for i in range(self.num_layers - 1): h",
"or ``mean``). out_dim : Rquired for batch norm layer; should",
"for batch_norm layer. residual : boolean flag for using residual",
"node feature, the :math:`f_\\Theta` in the formula. aggr_type : Aggregator",
"for dropout of output features. graph_norm : boolean flag for",
"\"\"\" def __init__(self, apply_func, aggr_type, dropout, graph_norm, batch_norm, residual=False, init_eps=0,",
"MLP(nn.Module): \"\"\"MLP with linear output\"\"\" def __init__(self, num_layers, input_dim, hidden_dim,",
"= False # to specify whether eps is trainable or",
"import torch.nn.functional as F import dgl.function as fn \"\"\" GIN:",
"def __init__(self, num_layers, input_dim, hidden_dim, output_dim): super().__init__() self.linear_or_not = True",
"\"\"\" This class is used in class GINNet Update the",
"If True, :math:`\\epsilon` will be a learnable parameter. \"\"\" def",
"This class is used in class GINNet Update the node",
"= F.relu(h) # non-linear activation if self.residual: h = h_in",
"MLP h = x for i in range(self.num_layers - 1):",
"for layer in range(num_layers - 2): self.linears.append(nn.Linear(hidden_dim, hidden_dim)) self.linears.append(nn.Linear(hidden_dim, output_dim))",
"[!] code adapted from dgl implementation of GINConv Parameters ----------",
"= self.bn_node_h(h) # batch normalization h = F.relu(h) # non-linear",
"flag for using residual connection. init_eps : optional Initial :math:`\\epsilon`",
"\"\"\" [!] code adapted from dgl implementation of GINConv Parameters",
"fn.sum elif aggr_type == 'max': self._reducer = fn.max elif aggr_type",
"adapted from dgl implementation of GINConv Parameters ---------- apply_func :",
"Aggregator type to use (``sum``, ``max`` or ``mean``). out_dim :",
"torch.nn.ModuleList() self.linears.append(nn.Linear(input_dim, hidden_dim)) for layer in range(num_layers - 2): self.linears.append(nn.Linear(hidden_dim,",
"num_layers self.output_dim = output_dim self.input_dim = input_dim if num_layers <",
"= batch_norm self.residual = residual self.dropout = dropout in_dim =",
"def forward(self, x): if self.linear_or_not: # If linear model return",
"# If linear model return self.linear(x) else: # If MLP",
"to the updated node feature, the :math:`f_\\Theta` in the formula.",
"normalization h = F.relu(h) # non-linear activation if self.residual: h",
"num_layers < 1: raise ValueError(\"number of layers should be positive!\")",
"batch_norm layer. residual : boolean flag for using residual connection.",
"apply_func.mlp.output_dim if in_dim != out_dim: self.residual = False # to",
"connection. init_eps : optional Initial :math:`\\epsilon` value, default: ``0``. learn_eps",
"Parameters ---------- apply_func : callable activation function/layer or None If",
"# normalize activation w.r.t. graph size if self.batch_norm: h =",
"in_dim = apply_func.mlp.input_dim out_dim = apply_func.mlp.output_dim if in_dim != out_dim:",
"hv with MLP \"\"\" def __init__(self, mlp): super().__init__() self.mlp =",
"== 1: # Linear model self.linear = nn.Linear(input_dim, output_dim) else:",
"\"\"\" class GINLayer(nn.Module): \"\"\" [!] code adapted from dgl implementation",
"dropout in_dim = apply_func.mlp.input_dim out_dim = apply_func.mlp.output_dim if in_dim !=",
"batch_norm : boolean flag for batch_norm layer. residual : boolean",
"2): self.linears.append(nn.Linear(hidden_dim, hidden_dim)) self.linears.append(nn.Linear(hidden_dim, output_dim)) for layer in range(num_layers -",
"or None If not None, apply this function to the",
"if not None. dropout : Required for dropout of output",
"h): h = self.mlp(h) return h class MLP(nn.Module): \"\"\"MLP with",
"# residual connection h = F.dropout(h, self.dropout, training=self.training) return h",
"True, :math:`\\epsilon` will be a learnable parameter. \"\"\" def __init__(self,",
"fn.mean else: raise KeyError('Aggregator type {} not recognized.'.format(aggr_type)) self.graph_norm =",
"features. graph_norm : boolean flag for output features normalization w.r.t.",
"h = self.bn_node_h(h) # batch normalization h = F.relu(h) #",
"if self.apply_func is not None: h = self.apply_func(h) if self.graph_norm:",
"None, apply this function to the updated node feature, the",
"of apply_func if not None. dropout : Required for dropout",
"self.linear_or_not = True # default is linear model self.num_layers =",
"elif aggr_type == 'max': self._reducer = fn.max elif aggr_type ==",
"# If MLP h = x for i in range(self.num_layers",
"If MLP h = x for i in range(self.num_layers -",
"= fn.sum elif aggr_type == 'max': self._reducer = fn.max elif",
"\"\"\"MLP with linear output\"\"\" def __init__(self, num_layers, input_dim, hidden_dim, output_dim):",
"raise KeyError('Aggregator type {} not recognized.'.format(aggr_type)) self.graph_norm = graph_norm self.batch_norm",
"type to use (``sum``, ``max`` or ``mean``). out_dim : Rquired",
": callable activation function/layer or None If not None, apply",
"not. if learn_eps: self.eps = torch.nn.Parameter(torch.FloatTensor([init_eps])) else: self.register_buffer('eps', torch.FloatTensor([init_eps])) self.bn_node_h",
"non-linear activation if self.residual: h = h_in + h #",
"self.residual = False # to specify whether eps is trainable",
"``mean``). out_dim : Rquired for batch norm layer; should match",
"g, h, snorm_n): h_in = h # for residual connection",
"``max`` or ``mean``). out_dim : Rquired for batch norm layer;",
"model self.linear = nn.Linear(input_dim, output_dim) else: # Multi-layer model self.linear_or_not",
"self.mlp(h) return h class MLP(nn.Module): \"\"\"MLP with linear output\"\"\" def",
"normalization w.r.t. graph sizes. batch_norm : boolean flag for batch_norm",
"dgl implementation of GINConv Parameters ---------- apply_func : callable activation",
"= fn.max elif aggr_type == 'mean': self._reducer = fn.mean else:",
"# default is linear model self.num_layers = num_layers self.output_dim =",
"self.residual = residual self.dropout = dropout in_dim = apply_func.mlp.input_dim out_dim",
"of layers should be positive!\") elif num_layers == 1: #",
"bool, optional If True, :math:`\\epsilon` will be a learnable parameter.",
"boolean flag for output features normalization w.r.t. graph sizes. batch_norm",
"in range(num_layers - 2): self.linears.append(nn.Linear(hidden_dim, hidden_dim)) self.linears.append(nn.Linear(hidden_dim, output_dim)) for layer",
"dropout of output features. graph_norm : boolean flag for output",
": boolean flag for using residual connection. init_eps : optional",
"h class MLP(nn.Module): \"\"\"MLP with linear output\"\"\" def __init__(self, num_layers,",
"norm layer; should match out_dim of apply_func if not None.",
"= num_layers self.output_dim = output_dim self.input_dim = input_dim if num_layers",
"graph_norm : boolean flag for output features normalization w.r.t. graph",
"activation function/layer or None If not None, apply this function",
"normalize activation w.r.t. graph size if self.batch_norm: h = self.bn_node_h(h)",
"recognized.'.format(aggr_type)) self.graph_norm = graph_norm self.batch_norm = batch_norm self.residual = residual",
"= x for i in range(self.num_layers - 1): h =",
"= dropout in_dim = apply_func.mlp.input_dim out_dim = apply_func.mlp.output_dim if in_dim",
"batch_norm, residual=False, init_eps=0, learn_eps=False): super().__init__() self.apply_func = apply_func if aggr_type",
"GINLayer(nn.Module): \"\"\" [!] code adapted from dgl implementation of GINConv",
"super().__init__() self.apply_func = apply_func if aggr_type == 'sum': self._reducer =",
"= self.mlp(h) return h class MLP(nn.Module): \"\"\"MLP with linear output\"\"\"",
"aggr_type == 'max': self._reducer = fn.max elif aggr_type == 'mean':",
"super().__init__() self.mlp = mlp def forward(self, h): h = self.mlp(h)",
"torch.nn as nn import torch.nn.functional as F import dgl.function as",
"<NAME>, <NAME> and <NAME>, ICLR 2019) https://arxiv.org/pdf/1810.00826.pdf \"\"\" class GINLayer(nn.Module):",
"model self.num_layers = num_layers self.output_dim = output_dim self.input_dim = input_dim",
"None: h = self.apply_func(h) if self.graph_norm: h = h* snorm_n",
"or not. if learn_eps: self.eps = torch.nn.Parameter(torch.FloatTensor([init_eps])) else: self.register_buffer('eps', torch.FloatTensor([init_eps]))",
"batch_norm self.residual = residual self.dropout = dropout in_dim = apply_func.mlp.input_dim",
"dropout, graph_norm, batch_norm, residual=False, init_eps=0, learn_eps=False): super().__init__() self.apply_func = apply_func",
"aggr_type, dropout, graph_norm, batch_norm, residual=False, init_eps=0, learn_eps=False): super().__init__() self.apply_func =",
"should be positive!\") elif num_layers == 1: # Linear model",
"- 1): self.batch_norms.append(nn.BatchNorm1d((hidden_dim))) def forward(self, x): if self.linear_or_not: # If",
"+ h # residual connection h = F.dropout(h, self.dropout, training=self.training)",
"in_dim != out_dim: self.residual = False # to specify whether",
"g.ndata['h'] = h g.update_all(fn.copy_u('h', 'm'), self._reducer('m', 'neigh')) h = (1",
"to use (``sum``, ``max`` or ``mean``). out_dim : Rquired for",
"< 1: raise ValueError(\"number of layers should be positive!\") elif",
"self._reducer = fn.mean else: raise KeyError('Aggregator type {} not recognized.'.format(aggr_type))",
"__init__(self, mlp): super().__init__() self.mlp = mlp def forward(self, h): h",
"self.graph_norm: h = h* snorm_n # normalize activation w.r.t. graph",
"self.bn_node_h(h) # batch normalization h = F.relu(h) # non-linear activation",
"forward(self, x): if self.linear_or_not: # If linear model return self.linear(x)",
"type {} not recognized.'.format(aggr_type)) self.graph_norm = graph_norm self.batch_norm = batch_norm",
"h_in = h # for residual connection g = g.local_var()",
": Rquired for batch norm layer; should match out_dim of",
"default is linear model self.num_layers = num_layers self.output_dim = output_dim",
"layer. residual : boolean flag for using residual connection. init_eps",
"linear model self.num_layers = num_layers self.output_dim = output_dim self.input_dim =",
"<reponame>JakeStevens/benchmarking-gnns<gh_stars>100-1000 import torch import torch.nn as nn import torch.nn.functional as",
"activation if self.residual: h = h_in + h # residual",
"learn_eps : bool, optional If True, :math:`\\epsilon` will be a",
"trainable or not. if learn_eps: self.eps = torch.nn.Parameter(torch.FloatTensor([init_eps])) else: self.register_buffer('eps',",
"GIN: Graph Isomorphism Networks HOW POWERFUL ARE GRAPH NEURAL NETWORKS?",
"h = self.apply_func(h) if self.graph_norm: h = h* snorm_n #",
"h* snorm_n # normalize activation w.r.t. graph size if self.batch_norm:",
"= torch.nn.Parameter(torch.FloatTensor([init_eps])) else: self.register_buffer('eps', torch.FloatTensor([init_eps])) self.bn_node_h = nn.BatchNorm1d(out_dim) def forward(self,",
"if aggr_type == 'sum': self._reducer = fn.sum elif aggr_type ==",
"h g.update_all(fn.copy_u('h', 'm'), self._reducer('m', 'neigh')) h = (1 + self.eps)",
"self.residual: h = h_in + h # residual connection h",
"class MLP(nn.Module): \"\"\"MLP with linear output\"\"\" def __init__(self, num_layers, input_dim,",
"= apply_func.mlp.input_dim out_dim = apply_func.mlp.output_dim if in_dim != out_dim: self.residual",
"= output_dim self.input_dim = input_dim if num_layers < 1: raise",
"model self.linear_or_not = False self.linears = torch.nn.ModuleList() self.batch_norms = torch.nn.ModuleList()",
"not None. dropout : Required for dropout of output features.",
"If linear model return self.linear(x) else: # If MLP h",
"using residual connection. init_eps : optional Initial :math:`\\epsilon` value, default:",
"in range(num_layers - 1): self.batch_norms.append(nn.BatchNorm1d((hidden_dim))) def forward(self, x): if self.linear_or_not:",
"= mlp def forward(self, h): h = self.mlp(h) return h",
"num_layers == 1: # Linear model self.linear = nn.Linear(input_dim, output_dim)",
"nn.BatchNorm1d(out_dim) def forward(self, g, h, snorm_n): h_in = h #",
"Rquired for batch norm layer; should match out_dim of apply_func",
"graph_norm self.batch_norm = batch_norm self.residual = residual self.dropout = dropout",
"x for i in range(self.num_layers - 1): h = F.relu(self.batch_norms[i](self.linears[i](h)))",
"= (1 + self.eps) * h + g.ndata['neigh'] if self.apply_func",
"ICLR 2019) https://arxiv.org/pdf/1810.00826.pdf \"\"\" class GINLayer(nn.Module): \"\"\" [!] code adapted",
"output features. graph_norm : boolean flag for output features normalization",
"== 'sum': self._reducer = fn.sum elif aggr_type == 'max': self._reducer",
"F.dropout(h, self.dropout, training=self.training) return h class ApplyNodeFunc(nn.Module): \"\"\" This class",
"\"\"\" def __init__(self, mlp): super().__init__() self.mlp = mlp def forward(self,",
"h, snorm_n): h_in = h # for residual connection g",
"= torch.nn.ModuleList() self.linears.append(nn.Linear(input_dim, hidden_dim)) for layer in range(num_layers - 2):",
"torch.nn.ModuleList() self.batch_norms = torch.nn.ModuleList() self.linears.append(nn.Linear(input_dim, hidden_dim)) for layer in range(num_layers",
":math:`\\epsilon` will be a learnable parameter. \"\"\" def __init__(self, apply_func,",
"= input_dim if num_layers < 1: raise ValueError(\"number of layers",
"batch normalization h = F.relu(h) # non-linear activation if self.residual:",
": Aggregator type to use (``sum``, ``max`` or ``mean``). out_dim",
"h = h_in + h # residual connection h =",
"with linear output\"\"\" def __init__(self, num_layers, input_dim, hidden_dim, output_dim): super().__init__()",
"dgl.function as fn \"\"\" GIN: Graph Isomorphism Networks HOW POWERFUL",
"def forward(self, g, h, snorm_n): h_in = h # for",
"in class GINNet Update the node feature hv with MLP",
"self._reducer('m', 'neigh')) h = (1 + self.eps) * h +",
"self.batch_norms = torch.nn.ModuleList() self.linears.append(nn.Linear(input_dim, hidden_dim)) for layer in range(num_layers -",
"of GINConv Parameters ---------- apply_func : callable activation function/layer or",
"torch.nn.functional as F import dgl.function as fn \"\"\" GIN: Graph",
"apply_func if not None. dropout : Required for dropout of",
"self.batch_norm: h = self.bn_node_h(h) # batch normalization h = F.relu(h)",
"elif aggr_type == 'mean': self._reducer = fn.mean else: raise KeyError('Aggregator",
"implementation of GINConv Parameters ---------- apply_func : callable activation function/layer",
"is used in class GINNet Update the node feature hv",
"<NAME>, ICLR 2019) https://arxiv.org/pdf/1810.00826.pdf \"\"\" class GINLayer(nn.Module): \"\"\" [!] code",
"= residual self.dropout = dropout in_dim = apply_func.mlp.input_dim out_dim =",
"g = g.local_var() g.ndata['h'] = h g.update_all(fn.copy_u('h', 'm'), self._reducer('m', 'neigh'))",
"init_eps=0, learn_eps=False): super().__init__() self.apply_func = apply_func if aggr_type == 'sum':",
"apply_func : callable activation function/layer or None If not None,",
"Update the node feature hv with MLP \"\"\" def __init__(self,",
"out_dim : Rquired for batch norm layer; should match out_dim",
"class ApplyNodeFunc(nn.Module): \"\"\" This class is used in class GINNet",
"hidden_dim, output_dim): super().__init__() self.linear_or_not = True # default is linear",
"self.linear_or_not: # If linear model return self.linear(x) else: # If",
"whether eps is trainable or not. if learn_eps: self.eps =",
"\"\"\" GIN: Graph Isomorphism Networks HOW POWERFUL ARE GRAPH NEURAL",
"positive!\") elif num_layers == 1: # Linear model self.linear =",
"model return self.linear(x) else: # If MLP h = x",
"aggr_type == 'sum': self._reducer = fn.sum elif aggr_type == 'max':",
"hidden_dim)) for layer in range(num_layers - 2): self.linears.append(nn.Linear(hidden_dim, hidden_dim)) self.linears.append(nn.Linear(hidden_dim,",
"fn.max elif aggr_type == 'mean': self._reducer = fn.mean else: raise",
"for i in range(self.num_layers - 1): h = F.relu(self.batch_norms[i](self.linears[i](h))) return",
"if learn_eps: self.eps = torch.nn.Parameter(torch.FloatTensor([init_eps])) else: self.register_buffer('eps', torch.FloatTensor([init_eps])) self.bn_node_h =",
"self.eps) * h + g.ndata['neigh'] if self.apply_func is not None:",
"``0``. learn_eps : bool, optional If True, :math:`\\epsilon` will be",
"snorm_n # normalize activation w.r.t. graph size if self.batch_norm: h",
"layers should be positive!\") elif num_layers == 1: # Linear",
"snorm_n): h_in = h # for residual connection g =",
"apply_func.mlp.input_dim out_dim = apply_func.mlp.output_dim if in_dim != out_dim: self.residual =",
"h = F.dropout(h, self.dropout, training=self.training) return h class ApplyNodeFunc(nn.Module): \"\"\"",
"the :math:`f_\\Theta` in the formula. aggr_type : Aggregator type to",
"Linear model self.linear = nn.Linear(input_dim, output_dim) else: # Multi-layer model",
"callable activation function/layer or None If not None, apply this",
"1: # Linear model self.linear = nn.Linear(input_dim, output_dim) else: #",
"self._reducer = fn.max elif aggr_type == 'mean': self._reducer = fn.mean",
"self.linear = nn.Linear(input_dim, output_dim) else: # Multi-layer model self.linear_or_not =",
"def __init__(self, mlp): super().__init__() self.mlp = mlp def forward(self, h):",
"self.batch_norms.append(nn.BatchNorm1d((hidden_dim))) def forward(self, x): if self.linear_or_not: # If linear model",
": boolean flag for output features normalization w.r.t. graph sizes.",
"= torch.nn.ModuleList() self.batch_norms = torch.nn.ModuleList() self.linears.append(nn.Linear(input_dim, hidden_dim)) for layer in",
"range(num_layers - 2): self.linears.append(nn.Linear(hidden_dim, hidden_dim)) self.linears.append(nn.Linear(hidden_dim, output_dim)) for layer in",
": Required for dropout of output features. graph_norm : boolean",
"value, default: ``0``. learn_eps : bool, optional If True, :math:`\\epsilon`",
"self.apply_func = apply_func if aggr_type == 'sum': self._reducer = fn.sum",
"learn_eps: self.eps = torch.nn.Parameter(torch.FloatTensor([init_eps])) else: self.register_buffer('eps', torch.FloatTensor([init_eps])) self.bn_node_h = nn.BatchNorm1d(out_dim)",
"updated node feature, the :math:`f_\\Theta` in the formula. aggr_type :",
"- 2): self.linears.append(nn.Linear(hidden_dim, hidden_dim)) self.linears.append(nn.Linear(hidden_dim, output_dim)) for layer in range(num_layers",
"'max': self._reducer = fn.max elif aggr_type == 'mean': self._reducer =",
"self.dropout = dropout in_dim = apply_func.mlp.input_dim out_dim = apply_func.mlp.output_dim if",
"None. dropout : Required for dropout of output features. graph_norm",
"out_dim of apply_func if not None. dropout : Required for",
"if num_layers < 1: raise ValueError(\"number of layers should be",
"will be a learnable parameter. \"\"\" def __init__(self, apply_func, aggr_type,",
"return h class ApplyNodeFunc(nn.Module): \"\"\" This class is used in",
"# non-linear activation if self.residual: h = h_in + h",
"= nn.Linear(input_dim, output_dim) else: # Multi-layer model self.linear_or_not = False",
"nn import torch.nn.functional as F import dgl.function as fn \"\"\"",
"optional Initial :math:`\\epsilon` value, default: ``0``. learn_eps : bool, optional",
"self.eps = torch.nn.Parameter(torch.FloatTensor([init_eps])) else: self.register_buffer('eps', torch.FloatTensor([init_eps])) self.bn_node_h = nn.BatchNorm1d(out_dim) def",
"output_dim) else: # Multi-layer model self.linear_or_not = False self.linears =",
"num_layers, input_dim, hidden_dim, output_dim): super().__init__() self.linear_or_not = True # default",
"is linear model self.num_layers = num_layers self.output_dim = output_dim self.input_dim",
"not recognized.'.format(aggr_type)) self.graph_norm = graph_norm self.batch_norm = batch_norm self.residual =",
"apply_func, aggr_type, dropout, graph_norm, batch_norm, residual=False, init_eps=0, learn_eps=False): super().__init__() self.apply_func",
"output_dim)) for layer in range(num_layers - 1): self.batch_norms.append(nn.BatchNorm1d((hidden_dim))) def forward(self,",
"i in range(self.num_layers - 1): h = F.relu(self.batch_norms[i](self.linears[i](h))) return self.linears[-1](h)",
"== 'max': self._reducer = fn.max elif aggr_type == 'mean': self._reducer",
"self.graph_norm = graph_norm self.batch_norm = batch_norm self.residual = residual self.dropout",
"input_dim if num_layers < 1: raise ValueError(\"number of layers should",
"h # for residual connection g = g.local_var() g.ndata['h'] =",
"as nn import torch.nn.functional as F import dgl.function as fn",
"g.update_all(fn.copy_u('h', 'm'), self._reducer('m', 'neigh')) h = (1 + self.eps) *",
"if self.batch_norm: h = self.bn_node_h(h) # batch normalization h =",
"aggr_type : Aggregator type to use (``sum``, ``max`` or ``mean``).",
"x): if self.linear_or_not: # If linear model return self.linear(x) else:",
"None If not None, apply this function to the updated",
"Graph Isomorphism Networks HOW POWERFUL ARE GRAPH NEURAL NETWORKS? (<NAME>,",
"boolean flag for using residual connection. init_eps : optional Initial",
"F.relu(h) # non-linear activation if self.residual: h = h_in +",
"h # residual connection h = F.dropout(h, self.dropout, training=self.training) return",
"# Multi-layer model self.linear_or_not = False self.linears = torch.nn.ModuleList() self.batch_norms",
"size if self.batch_norm: h = self.bn_node_h(h) # batch normalization h",
"residual : boolean flag for using residual connection. init_eps :",
"output_dim self.input_dim = input_dim if num_layers < 1: raise ValueError(\"number",
"apply_func if aggr_type == 'sum': self._reducer = fn.sum elif aggr_type",
"feature hv with MLP \"\"\" def __init__(self, mlp): super().__init__() self.mlp",
"+ self.eps) * h + g.ndata['neigh'] if self.apply_func is not",
": optional Initial :math:`\\epsilon` value, default: ``0``. learn_eps : bool,",
"import dgl.function as fn \"\"\" GIN: Graph Isomorphism Networks HOW",
"learnable parameter. \"\"\" def __init__(self, apply_func, aggr_type, dropout, graph_norm, batch_norm,",
"<NAME> and <NAME>, ICLR 2019) https://arxiv.org/pdf/1810.00826.pdf \"\"\" class GINLayer(nn.Module): \"\"\"",
"self.mlp = mlp def forward(self, h): h = self.mlp(h) return",
"as fn \"\"\" GIN: Graph Isomorphism Networks HOW POWERFUL ARE",
"graph_norm, batch_norm, residual=False, init_eps=0, learn_eps=False): super().__init__() self.apply_func = apply_func if",
"else: self.register_buffer('eps', torch.FloatTensor([init_eps])) self.bn_node_h = nn.BatchNorm1d(out_dim) def forward(self, g, h,",
"h = F.relu(h) # non-linear activation if self.residual: h =",
"the node feature hv with MLP \"\"\" def __init__(self, mlp):",
"residual connection g = g.local_var() g.ndata['h'] = h g.update_all(fn.copy_u('h', 'm'),",
"mlp def forward(self, h): h = self.mlp(h) return h class",
"nn.Linear(input_dim, output_dim) else: # Multi-layer model self.linear_or_not = False self.linears",
"if self.linear_or_not: # If linear model return self.linear(x) else: #",
"self.linears = torch.nn.ModuleList() self.batch_norms = torch.nn.ModuleList() self.linears.append(nn.Linear(input_dim, hidden_dim)) for layer",
"= g.local_var() g.ndata['h'] = h g.update_all(fn.copy_u('h', 'm'), self._reducer('m', 'neigh')) h",
"= apply_func.mlp.output_dim if in_dim != out_dim: self.residual = False #",
"GINConv Parameters ---------- apply_func : callable activation function/layer or None",
"self.register_buffer('eps', torch.FloatTensor([init_eps])) self.bn_node_h = nn.BatchNorm1d(out_dim) def forward(self, g, h, snorm_n):",
"mlp): super().__init__() self.mlp = mlp def forward(self, h): h =",
"with MLP \"\"\" def __init__(self, mlp): super().__init__() self.mlp = mlp",
"features normalization w.r.t. graph sizes. batch_norm : boolean flag for",
"F import dgl.function as fn \"\"\" GIN: Graph Isomorphism Networks",
"parameter. \"\"\" def __init__(self, apply_func, aggr_type, dropout, graph_norm, batch_norm, residual=False,",
"layer in range(num_layers - 1): self.batch_norms.append(nn.BatchNorm1d((hidden_dim))) def forward(self, x): if",
"ValueError(\"number of layers should be positive!\") elif num_layers == 1:",
"{} not recognized.'.format(aggr_type)) self.graph_norm = graph_norm self.batch_norm = batch_norm self.residual",
"= True # default is linear model self.num_layers = num_layers",
"elif num_layers == 1: # Linear model self.linear = nn.Linear(input_dim,",
"out_dim = apply_func.mlp.output_dim if in_dim != out_dim: self.residual = False",
"fn \"\"\" GIN: Graph Isomorphism Networks HOW POWERFUL ARE GRAPH",
"be positive!\") elif num_layers == 1: # Linear model self.linear",
"torch.FloatTensor([init_eps])) self.bn_node_h = nn.BatchNorm1d(out_dim) def forward(self, g, h, snorm_n): h_in",
"torch import torch.nn as nn import torch.nn.functional as F import",
"return h class MLP(nn.Module): \"\"\"MLP with linear output\"\"\" def __init__(self,",
"class is used in class GINNet Update the node feature",
"self.apply_func(h) if self.graph_norm: h = h* snorm_n # normalize activation",
"init_eps : optional Initial :math:`\\epsilon` value, default: ``0``. learn_eps :",
"__init__(self, apply_func, aggr_type, dropout, graph_norm, batch_norm, residual=False, init_eps=0, learn_eps=False): super().__init__()",
"NEURAL NETWORKS? (<NAME>, <NAME>, <NAME> and <NAME>, ICLR 2019) https://arxiv.org/pdf/1810.00826.pdf",
"import torch.nn as nn import torch.nn.functional as F import dgl.function",
"feature, the :math:`f_\\Theta` in the formula. aggr_type : Aggregator type",
"residual self.dropout = dropout in_dim = apply_func.mlp.input_dim out_dim = apply_func.mlp.output_dim",
"Isomorphism Networks HOW POWERFUL ARE GRAPH NEURAL NETWORKS? (<NAME>, <NAME>,",
"forward(self, h): h = self.mlp(h) return h class MLP(nn.Module): \"\"\"MLP",
"* h + g.ndata['neigh'] if self.apply_func is not None: h",
"Networks HOW POWERFUL ARE GRAPH NEURAL NETWORKS? (<NAME>, <NAME>, <NAME>",
"output\"\"\" def __init__(self, num_layers, input_dim, hidden_dim, output_dim): super().__init__() self.linear_or_not =",
"the updated node feature, the :math:`f_\\Theta` in the formula. aggr_type",
":math:`\\epsilon` value, default: ``0``. learn_eps : bool, optional If True,",
"POWERFUL ARE GRAPH NEURAL NETWORKS? (<NAME>, <NAME>, <NAME> and <NAME>,",
"if in_dim != out_dim: self.residual = False # to specify",
": bool, optional If True, :math:`\\epsilon` will be a learnable",
"= h # for residual connection g = g.local_var() g.ndata['h']",
"g.ndata['neigh'] if self.apply_func is not None: h = self.apply_func(h) if",
"function/layer or None If not None, apply this function to",
"raise ValueError(\"number of layers should be positive!\") elif num_layers ==",
"learn_eps=False): super().__init__() self.apply_func = apply_func if aggr_type == 'sum': self._reducer",
"# Linear model self.linear = nn.Linear(input_dim, output_dim) else: # Multi-layer",
"out_dim: self.residual = False # to specify whether eps is",
"'mean': self._reducer = fn.mean else: raise KeyError('Aggregator type {} not",
"the formula. aggr_type : Aggregator type to use (``sum``, ``max``",
"aggr_type == 'mean': self._reducer = fn.mean else: raise KeyError('Aggregator type",
"self.num_layers = num_layers self.output_dim = output_dim self.input_dim = input_dim if",
"this function to the updated node feature, the :math:`f_\\Theta` in",
"is trainable or not. if learn_eps: self.eps = torch.nn.Parameter(torch.FloatTensor([init_eps])) else:",
"output_dim): super().__init__() self.linear_or_not = True # default is linear model",
"residual=False, init_eps=0, learn_eps=False): super().__init__() self.apply_func = apply_func if aggr_type ==",
"False # to specify whether eps is trainable or not.",
"for output features normalization w.r.t. graph sizes. batch_norm : boolean",
"self.linears.append(nn.Linear(hidden_dim, hidden_dim)) self.linears.append(nn.Linear(hidden_dim, output_dim)) for layer in range(num_layers - 1):",
"ARE GRAPH NEURAL NETWORKS? (<NAME>, <NAME>, <NAME> and <NAME>, ICLR",
": boolean flag for batch_norm layer. residual : boolean flag",
"else: raise KeyError('Aggregator type {} not recognized.'.format(aggr_type)) self.graph_norm = graph_norm",
"= nn.BatchNorm1d(out_dim) def forward(self, g, h, snorm_n): h_in = h",
"h + g.ndata['neigh'] if self.apply_func is not None: h =",
"self.input_dim = input_dim if num_layers < 1: raise ValueError(\"number of",
"Required for dropout of output features. graph_norm : boolean flag",
"# to specify whether eps is trainable or not. if",
"== 'mean': self._reducer = fn.mean else: raise KeyError('Aggregator type {}"
] |
[
".fourth import PerfectFourth from .fifth import Tritone from .fifth import",
"MinorSixth from .sixth import MajorSixth from .seventh import MinorSeventh from",
"MinorSeventh from .seventh import MajorSeventh from .eighth import Octave __all__",
"from .third import MinorThird from .third import MajorThird from .fourth",
".third import MajorThird from .fourth import PerfectFourth from .fifth import",
"from .seventh import MajorSeventh from .eighth import Octave __all__ =",
".third import MinorThird from .third import MajorThird from .fourth import",
"import Tritone from .fifth import PerfectFifth from .sixth import MinorSixth",
"import PerfectFifth from .sixth import MinorSixth from .sixth import MajorSixth",
"\"MinorThird\", \"MajorThird\", \"PerfectFourth\", \"Tritone\", \"PerfectFifth\", \"MinorSixth\", \"MajorSixth\", \"MinorSeventh\", \"MajorSeventh\", \"Octave\",",
"from .fifth import PerfectFifth from .sixth import MinorSixth from .sixth",
".second import MajorSecond from .third import MinorThird from .third import",
"MinorSecond from .second import MajorSecond from .third import MinorThird from",
"diatonic intervals. \"\"\" from .second import MinorSecond from .second import",
"from .second import MajorSecond from .third import MinorThird from .third",
"MajorSecond from .third import MinorThird from .third import MajorThird from",
"import MajorThird from .fourth import PerfectFourth from .fifth import Tritone",
"from .sixth import MinorSixth from .sixth import MajorSixth from .seventh",
".second import MinorSecond from .second import MajorSecond from .third import",
".seventh import MinorSeventh from .seventh import MajorSeventh from .eighth import",
"import MinorSeventh from .seventh import MajorSeventh from .eighth import Octave",
"[ \"MinorSecond\", \"MajorSecond\", \"MinorThird\", \"MajorThird\", \"PerfectFourth\", \"Tritone\", \"PerfectFifth\", \"MinorSixth\", \"MajorSixth\",",
"from .second import MinorSecond from .second import MajorSecond from .third",
"import MajorSeventh from .eighth import Octave __all__ = [ \"MinorSecond\",",
"import PerfectFourth from .fifth import Tritone from .fifth import PerfectFifth",
"import MinorSixth from .sixth import MajorSixth from .seventh import MinorSeventh",
".sixth import MajorSixth from .seventh import MinorSeventh from .seventh import",
"PerfectFourth from .fifth import Tritone from .fifth import PerfectFifth from",
"PerfectFifth from .sixth import MinorSixth from .sixth import MajorSixth from",
"from .fourth import PerfectFourth from .fifth import Tritone from .fifth",
"\"MajorThird\", \"PerfectFourth\", \"Tritone\", \"PerfectFifth\", \"MinorSixth\", \"MajorSixth\", \"MinorSeventh\", \"MajorSeventh\", \"Octave\", ]",
"import MinorSecond from .second import MajorSecond from .third import MinorThird",
"from .third import MajorThird from .fourth import PerfectFourth from .fifth",
"__all__ = [ \"MinorSecond\", \"MajorSecond\", \"MinorThird\", \"MajorThird\", \"PerfectFourth\", \"Tritone\", \"PerfectFifth\",",
"import MajorSecond from .third import MinorThird from .third import MajorThird",
"import MinorThird from .third import MajorThird from .fourth import PerfectFourth",
".seventh import MajorSeventh from .eighth import Octave __all__ = [",
".sixth import MinorSixth from .sixth import MajorSixth from .seventh import",
"<filename>music/distance/aural/diatonic/__init__.py \"\"\" *mus . it . dia* The simple diatonic",
". it . dia* The simple diatonic intervals. \"\"\" from",
"intervals. \"\"\" from .second import MinorSecond from .second import MajorSecond",
"MinorThird from .third import MajorThird from .fourth import PerfectFourth from",
"\"\"\" *mus . it . dia* The simple diatonic intervals.",
"dia* The simple diatonic intervals. \"\"\" from .second import MinorSecond",
"\"\"\" from .second import MinorSecond from .second import MajorSecond from",
".fifth import Tritone from .fifth import PerfectFifth from .sixth import",
"Octave __all__ = [ \"MinorSecond\", \"MajorSecond\", \"MinorThird\", \"MajorThird\", \"PerfectFourth\", \"Tritone\",",
"= [ \"MinorSecond\", \"MajorSecond\", \"MinorThird\", \"MajorThird\", \"PerfectFourth\", \"Tritone\", \"PerfectFifth\", \"MinorSixth\",",
".eighth import Octave __all__ = [ \"MinorSecond\", \"MajorSecond\", \"MinorThird\", \"MajorThird\",",
"from .fifth import Tritone from .fifth import PerfectFifth from .sixth",
"from .eighth import Octave __all__ = [ \"MinorSecond\", \"MajorSecond\", \"MinorThird\",",
"\"MajorSecond\", \"MinorThird\", \"MajorThird\", \"PerfectFourth\", \"Tritone\", \"PerfectFifth\", \"MinorSixth\", \"MajorSixth\", \"MinorSeventh\", \"MajorSeventh\",",
". dia* The simple diatonic intervals. \"\"\" from .second import",
"Tritone from .fifth import PerfectFifth from .sixth import MinorSixth from",
"import MajorSixth from .seventh import MinorSeventh from .seventh import MajorSeventh",
"The simple diatonic intervals. \"\"\" from .second import MinorSecond from",
"from .sixth import MajorSixth from .seventh import MinorSeventh from .seventh",
"MajorSeventh from .eighth import Octave __all__ = [ \"MinorSecond\", \"MajorSecond\",",
"import Octave __all__ = [ \"MinorSecond\", \"MajorSecond\", \"MinorThird\", \"MajorThird\", \"PerfectFourth\",",
"*mus . it . dia* The simple diatonic intervals. \"\"\"",
"\"MinorSecond\", \"MajorSecond\", \"MinorThird\", \"MajorThird\", \"PerfectFourth\", \"Tritone\", \"PerfectFifth\", \"MinorSixth\", \"MajorSixth\", \"MinorSeventh\",",
"simple diatonic intervals. \"\"\" from .second import MinorSecond from .second",
".fifth import PerfectFifth from .sixth import MinorSixth from .sixth import",
"MajorSixth from .seventh import MinorSeventh from .seventh import MajorSeventh from",
"from .seventh import MinorSeventh from .seventh import MajorSeventh from .eighth",
"it . dia* The simple diatonic intervals. \"\"\" from .second",
"MajorThird from .fourth import PerfectFourth from .fifth import Tritone from"
] |
[
"return WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) def login(driver, username, password): driver.get(depurl) elem",
"10).until(EC.presence_of_element_located((By.XPATH, xpath))) def login(driver, username, password): driver.get(depurl) elem = getElement(driver,",
"def getElement(driver, xpath): return WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) def login(driver, username,",
"selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from",
"this file holds some common testing functions from selenium.webdriver.support.wait import",
"import By depurl = \"localhost:3000\" def getElement(driver, xpath): return WebDriverWait(driver,",
"functions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as",
"\"//input[@id='username']\") elem.clear() elem.send_keys(username) elem = getElement(driver, \"//input[@id='password']\") elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN)",
"getElement(driver, xpath): return WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) def login(driver, username, password):",
"= getElement(driver, \"//input[@id='username']\") elem.clear() elem.send_keys(username) elem = getElement(driver, \"//input[@id='password']\") elem.clear()",
"expected_conditions as EC from selenium.webdriver.common.by import By depurl = \"localhost:3000\"",
"holds some common testing functions from selenium.webdriver.support.wait import WebDriverWait from",
"xpath): return WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) def login(driver, username, password): driver.get(depurl)",
"elem = getElement(driver, \"//input[@id='username']\") elem.clear() elem.send_keys(username) elem = getElement(driver, \"//input[@id='password']\")",
"elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN) def logout(driver): elem = getElement(driver, \"//a[text()='Logout']\") elem.click()",
"selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By depurl",
"getElement(driver, \"//input[@id='password']\") elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN) def logout(driver): elem = getElement(driver,",
"from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC",
"import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by",
"WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) def login(driver, username, password): driver.get(depurl) elem =",
"xpath))) def login(driver, username, password): driver.get(depurl) elem = getElement(driver, \"//input[@id='username']\")",
"elem.clear() elem.send_keys(username) elem = getElement(driver, \"//input[@id='password']\") elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN) def",
"elem = getElement(driver, \"//input[@id='password']\") elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN) def logout(driver): elem",
"selenium.webdriver.common.by import By depurl = \"localhost:3000\" def getElement(driver, xpath): return",
"some common testing functions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support",
"username, password): driver.get(depurl) elem = getElement(driver, \"//input[@id='username']\") elem.clear() elem.send_keys(username) elem",
"= \"localhost:3000\" def getElement(driver, xpath): return WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) def",
"login(driver, username, password): driver.get(depurl) elem = getElement(driver, \"//input[@id='username']\") elem.clear() elem.send_keys(username)",
"file holds some common testing functions from selenium.webdriver.support.wait import WebDriverWait",
"elem.send_keys(username) elem = getElement(driver, \"//input[@id='password']\") elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN) def logout(driver):",
"driver.get(depurl) elem = getElement(driver, \"//input[@id='username']\") elem.clear() elem.send_keys(username) elem = getElement(driver,",
"\"//input[@id='password']\") elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN) def logout(driver): elem = getElement(driver, \"//a[text()='Logout']\")",
"testing functions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions",
"def login(driver, username, password): driver.get(depurl) elem = getElement(driver, \"//input[@id='username']\") elem.clear()",
"<reponame>AriTheGuitarMan/AriTheGuitarMan.github.io # this file holds some common testing functions from",
"\"localhost:3000\" def getElement(driver, xpath): return WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) def login(driver,",
"from selenium.webdriver.common.by import By depurl = \"localhost:3000\" def getElement(driver, xpath):",
"= getElement(driver, \"//input[@id='password']\") elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN) def logout(driver): elem =",
"getElement(driver, \"//input[@id='username']\") elem.clear() elem.send_keys(username) elem = getElement(driver, \"//input[@id='password']\") elem.clear() elem.send_keys(password)",
"password): driver.get(depurl) elem = getElement(driver, \"//input[@id='username']\") elem.clear() elem.send_keys(username) elem =",
"EC from selenium.webdriver.common.by import By depurl = \"localhost:3000\" def getElement(driver,",
"# this file holds some common testing functions from selenium.webdriver.support.wait",
"common testing functions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import",
"as EC from selenium.webdriver.common.by import By depurl = \"localhost:3000\" def",
"WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import",
"depurl = \"localhost:3000\" def getElement(driver, xpath): return WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))",
"import expected_conditions as EC from selenium.webdriver.common.by import By depurl =",
"from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By",
"By depurl = \"localhost:3000\" def getElement(driver, xpath): return WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH,"
] |
[
"_drawText(self, canvas, text, x, y, font_size=20, center_horizontal=False): draw = ImageDraw.Draw(canvas)",
"draw = ImageDraw.Draw(canvas) font = ImageFont.truetype(self.font_path, font_size) text_draw_size = draw.textsize(text,",
"with open(\"result.jpg\", \"wb\") as fp: canvas.save(fp) print(\"result file saved\") else:",
"__init__(self, rotate=0, font_path=None): if font_path: self.font_path = font_path else: self.font_path",
"code_2_icono['SKY_O13'] = ['27'] code_2_icono['SKY_O14'] = ['28'] code_2_icono['SKY_W00'] = ['38'] code_2_icono['SKY_W01']",
"1 class PapirusRenderer: \"\"\"Renderer for Papirus HAT\"\"\" def __init__(self, rotate=0,",
"def _drawText(self, canvas, text, x, y, font_size=20, center_horizontal=False): draw =",
"= ['12', '40'] code_2_icono['SKY_O05'] = ['13', '41'] code_2_icono['SKY_O06'] = ['14',",
"\" + str(w.max_temperature) self._drawText(canvas, temperature, base_x+80, base_y+28+55*i, font_size=14, center_horizontal=True) #",
"translated, 70,140, font_size=20, center_horizontal=True) base_x,base_y = 145,5 for i,w in",
"if len(l) > 1 and drawNight: cur_hour = time.localtime().tm_hour is_night",
"code_2_icono['SKY_W01'] = ['01', '08'] code_2_icono['SKY_W02'] = ['02', '09'] code_2_icono['SKY_W03'] =",
"\"weather_icons_mod\") if len(l) > 1 and drawNight: cur_hour = time.localtime().tm_hour",
"geticonfname(w.weather_code) self._drawImage(canvas, fname, base_x, base_y+55*i, (50,50)) temperature = str(w.min_temperature) +",
"= x - text_draw_size[0]/2 draw.text( (x, y) , text, font=font,",
"= ['V BAD'] def geticonfname(code, drawNight=False): l = code_2_icono[code] dname",
"base_x,base_y = 145,5 for i,w in enumerate(weather_forecast): fname = geticonfname(w.weather_code)",
"canvas, image_path, x, y, size): image = Image.open(image_path) image =",
"= cur_hour < 5 or cur_hour > 18 if is_night:",
"(264,176) def render(self, weather, weather_forecast): canvas = Image.new('1', self.canvas_size, WHITE)",
"sys reload(sys) sys.setdefaultencoding('utf-8') import os import time import collections from",
"save a image for debugging purpose with open(\"result.jpg\", \"wb\") as",
"'40'] code_2_icono['SKY_O05'] = ['13', '41'] code_2_icono['SKY_O06'] = ['14', '42'] code_2_icono['SKY_O07']",
"code_2_icono['SKY_O08'] = ['21'] code_2_icono['SKY_O09'] = ['32'] code_2_icono['SKY_O10'] = ['04'] code_2_icono['SKY_O11']",
"['V BAD'] def geticonfname(code, drawNight=False): l = code_2_icono[code] dname =",
"font_size=9, center_horizontal=True) if self.papirus == None: # save a image",
"dither=Image.FLOYDSTEINBERG) canvas.paste(image,(x,y)) def _drawText(self, canvas, text, x, y, font_size=20, center_horizontal=False):",
"['28'] code_2_icono['SKY_W00'] = ['38'] code_2_icono['SKY_W01'] = ['01', '08'] code_2_icono['SKY_W02'] =",
"from papirus import Papirus self.papirus = Papirus(rotate=rotate) self.canvas_size = self.papirus.size",
"= ['02', '09'] code_2_icono['SKY_O03'] = ['03', '10'] code_2_icono['SKY_O04'] = ['12',",
"dname = os.path.join(os.path.dirname(__file__), \"resources\", \"weather_icons_mod\") if len(l) > 1 and",
"font_size=14, center_horizontal=True) # update time self._drawText(canvas, time.strftime(\"%Y-%m-%d %H:%M\",time.localtime()), 136, 165,",
"try: from papirus import Papirus self.papirus = Papirus(rotate=rotate) self.canvas_size =",
"else: self.papirus.display(canvas) self.papirus.update() def _drawImage(self, canvas, image_path, x, y, size):",
"len(l) > 1 and drawNight: cur_hour = time.localtime().tm_hour is_night =",
"['13', '41'] code_2_icono['SKY_O06'] = ['14', '42'] code_2_icono['SKY_O07'] = ['18'] code_2_icono['SKY_O08']",
"or cur_hour > 18 if is_night: return os.path.join(dname, l[1] +",
"os.path.join(dname, l[0] + '.png') BLACK = 0 WHITE = 1",
"= ImageDraw.Draw(canvas) font = ImageFont.truetype(self.font_path, font_size) text_draw_size = draw.textsize(text, font=font)",
"= ['38'] code_2_icono['SKY_W01'] = ['01', '08'] code_2_icono['SKY_W02'] = ['02', '09']",
"size : %s\"%str(self.canvas_size)) except ImportError: print(\"papirus import failed\") self.papirus =",
"= ['21'] code_2_icono['SKY_W11'] = ['04'] code_2_icono['SKY_W12'] = ['13', '41'] code_2_icono['SKY_W13']",
"code_2_icono['SKY_O04'] = ['12', '40'] code_2_icono['SKY_O05'] = ['13', '41'] code_2_icono['SKY_O06'] =",
": 'UNKNOWN') code_2_icono['SKY_O00'] = ['38'] code_2_icono['SKY_O01'] = ['01', '08'] code_2_icono['SKY_O02']",
"rotate=0, font_path=None): if font_path: self.font_path = font_path else: self.font_path =",
"code_2_icono['SKY_O01'] = ['01', '08'] code_2_icono['SKY_O02'] = ['02', '09'] code_2_icono['SKY_O03'] =",
"\"/usr/share/fonts/truetype/freefont/FreeMono.ttf\" print(\"rotate:\",rotate) try: from papirus import Papirus self.papirus = Papirus(rotate=rotate)",
"= ['27'] code_2_icono['SKY_O14'] = ['28'] code_2_icono['SKY_W00'] = ['38'] code_2_icono['SKY_W01'] =",
"print(\"rotate:\",rotate) try: from papirus import Papirus self.papirus = Papirus(rotate=rotate) self.canvas_size",
"return os.path.join(dname, l[0] + '.png') BLACK = 0 WHITE =",
"ImageDraw.Draw(canvas) font = ImageFont.truetype(self.font_path, font_size) text_draw_size = draw.textsize(text, font=font) if",
"'10'] code_2_icono['SKY_W04'] = ['18'] code_2_icono['SKY_W07'] = ['21'] code_2_icono['SKY_W09'] = ['12',",
"os.path.join(os.path.dirname(__file__), \"resources\", \"weather_icons_mod\") if len(l) > 1 and drawNight: cur_hour",
"geticonfname(weather.weather_code, drawNight=True) print(\"file:\",fname) self._drawImage(canvas, fname, 20,10,(100,100)) print(\"cur desc : %s\"%str(weather.weather_desc))",
"#-- coding: utf-8 -- import sys reload(sys) sys.setdefaultencoding('utf-8') import os",
"BAD'] def geticonfname(code, drawNight=False): l = code_2_icono[code] dname = os.path.join(os.path.dirname(__file__),",
"Papirus self.papirus = Papirus(rotate=rotate) self.canvas_size = self.papirus.size print(\"papirus size :",
"base_x, base_y+55*i, (50,50)) temperature = str(w.min_temperature) + \" / \"",
"self.papirus == None: # save a image for debugging purpose",
"os.path.join(dname, l[0] + '.png') else: return os.path.join(dname, l[0] + '.png')",
"'.png') else: return os.path.join(dname, l[0] + '.png') else: return os.path.join(dname,",
"code_2_icono['SKY_O06'] = ['14', '42'] code_2_icono['SKY_O07'] = ['18'] code_2_icono['SKY_O08'] = ['21']",
"return os.path.join(dname, l[1] + '.png') else: return os.path.join(dname, l[0] +",
"image = Image.open(image_path) image = ImageOps.grayscale(image) image = image.resize(size) image",
"= image.convert(\"1\", dither=Image.FLOYDSTEINBERG) canvas.paste(image,(x,y)) def _drawText(self, canvas, text, x, y,",
"['NORMAL'] kor_2_eng[u'나쁨'] = ['BAD'] kor_2_eng[u'매우 나쁨'] = ['V BAD'] def",
"kor_2_eng[u'좋음'] = ['GOOD'] kor_2_eng[u'보통'] = ['NORMAL'] kor_2_eng[u'나쁨'] = ['BAD'] kor_2_eng[u'매우",
"size): image = Image.open(image_path) image = ImageOps.grayscale(image) image = image.resize(size)",
"'.png') BLACK = 0 WHITE = 1 class PapirusRenderer: \"\"\"Renderer",
"if self.papirus == None: # save a image for debugging",
"airq : %s\"%str(weather.air_quality)) temperature = str(weather.cur_temperature).split('.')[0] + u\" \\u2103\" self._drawText(canvas,",
": %s\"%str(self.canvas_size)) except ImportError: print(\"papirus import failed\") self.papirus = None",
"print(\"papirus size : %s\"%str(self.canvas_size)) except ImportError: print(\"papirus import failed\") self.papirus",
"image = ImageOps.grayscale(image) image = image.resize(size) image = image.convert(\"1\", dither=Image.FLOYDSTEINBERG)",
"drawNight: cur_hour = time.localtime().tm_hour is_night = cur_hour < 5 or",
"self.canvas_size, WHITE) print(\"font_path:\",self.font_path) fname = geticonfname(weather.weather_code, drawNight=True) print(\"file:\",fname) self._drawImage(canvas, fname,",
"code_2_icono['SKY_O12'] = ['26'] code_2_icono['SKY_O13'] = ['27'] code_2_icono['SKY_O14'] = ['28'] code_2_icono['SKY_W00']",
"136, 165, font_size=9, center_horizontal=True) if self.papirus == None: # save",
"image_path, x, y, size): image = Image.open(image_path) image = ImageOps.grayscale(image)",
"= ['38'] code_2_icono['SKY_O01'] = ['01', '08'] code_2_icono['SKY_O02'] = ['02', '09']",
"fname = geticonfname(w.weather_code) self._drawImage(canvas, fname, base_x, base_y+55*i, (50,50)) temperature =",
"render(self, weather, weather_forecast): canvas = Image.new('1', self.canvas_size, WHITE) print(\"font_path:\",self.font_path) fname",
"'.png') else: return os.path.join(dname, l[0] + '.png') BLACK = 0",
"code_2_icono['SKY_W10'] = ['21'] code_2_icono['SKY_W11'] = ['04'] code_2_icono['SKY_W12'] = ['13', '41']",
"airq translated: %s\"%translated) self._drawText(canvas, translated, 70,140, font_size=20, center_horizontal=True) base_x,base_y =",
"print(\"papirus import failed\") self.papirus = None self.canvas_size = (264,176) def",
"cur_hour = time.localtime().tm_hour is_night = cur_hour < 5 or cur_hour",
"+ '.png') else: return os.path.join(dname, l[0] + '.png') else: return",
"drawNight=True) print(\"file:\",fname) self._drawImage(canvas, fname, 20,10,(100,100)) print(\"cur desc : %s\"%str(weather.weather_desc)) print(\"cur",
"'09'] code_2_icono['SKY_W03'] = ['03', '10'] code_2_icono['SKY_W04'] = ['18'] code_2_icono['SKY_W07'] =",
"= draw.textsize(text, font=font) if center_horizontal: x = x - text_draw_size[0]/2",
"and drawNight: cur_hour = time.localtime().tm_hour is_night = cur_hour < 5",
"\"\"\"Renderer for Papirus HAT\"\"\" def __init__(self, rotate=0, font_path=None): if font_path:",
"['01', '08'] code_2_icono['SKY_O02'] = ['02', '09'] code_2_icono['SKY_O03'] = ['03', '10']",
"= ['26'] code_2_icono['SKY_O13'] = ['27'] code_2_icono['SKY_O14'] = ['28'] code_2_icono['SKY_W00'] =",
"code_2_icono['SKY_W02'] = ['02', '09'] code_2_icono['SKY_W03'] = ['03', '10'] code_2_icono['SKY_W04'] =",
"temperature = str(w.min_temperature) + \" / \" + str(w.max_temperature) self._drawText(canvas,",
"canvas = Image.new('1', self.canvas_size, WHITE) print(\"font_path:\",self.font_path) fname = geticonfname(weather.weather_code, drawNight=True)",
"'40'] code_2_icono['SKY_W10'] = ['21'] code_2_icono['SKY_W11'] = ['04'] code_2_icono['SKY_W12'] = ['13',",
"as fp: canvas.save(fp) print(\"result file saved\") else: self.papirus.display(canvas) self.papirus.update() def",
"= ['04'] code_2_icono['SKY_O11'] = ['29'] code_2_icono['SKY_O12'] = ['26'] code_2_icono['SKY_O13'] =",
"base_y+28+55*i, font_size=14, center_horizontal=True) # update time self._drawText(canvas, time.strftime(\"%Y-%m-%d %H:%M\",time.localtime()), 136,",
"+ str(w.max_temperature) self._drawText(canvas, temperature, base_x+80, base_y+28+55*i, font_size=14, center_horizontal=True) # update",
"center_horizontal=True) if self.papirus == None: # save a image for",
"font_path=None): if font_path: self.font_path = font_path else: self.font_path = \"/usr/share/fonts/truetype/freefont/FreeMono.ttf\"",
"self.papirus = None self.canvas_size = (264,176) def render(self, weather, weather_forecast):",
"'41'] code_2_icono['SKY_W13'] = ['32'] kor_2_eng[u'좋음'] = ['GOOD'] kor_2_eng[u'보통'] = ['NORMAL']",
"= ['14', '42'] code_2_icono['SKY_O07'] = ['18'] code_2_icono['SKY_O08'] = ['21'] code_2_icono['SKY_O09']",
"collections.defaultdict(lambda : '38') kor_2_eng = collections.defaultdict(lambda : 'UNKNOWN') code_2_icono['SKY_O00'] =",
"= ImageFont.truetype(self.font_path, font_size) text_draw_size = draw.textsize(text, font=font) if center_horizontal: x",
"= os.path.join(os.path.dirname(__file__), \"resources\", \"weather_icons_mod\") if len(l) > 1 and drawNight:",
"temperature, 70,115, font_size=20, center_horizontal=True) translated = kor_2_eng[weather.air_quality][0] print(\"cur airq translated:",
"is_night = cur_hour < 5 or cur_hour > 18 if",
"['12', '40'] code_2_icono['SKY_O05'] = ['13', '41'] code_2_icono['SKY_O06'] = ['14', '42']",
"print(\"result file saved\") else: self.papirus.display(canvas) self.papirus.update() def _drawImage(self, canvas, image_path,",
"= Image.new('1', self.canvas_size, WHITE) print(\"font_path:\",self.font_path) fname = geticonfname(weather.weather_code, drawNight=True) print(\"file:\",fname)",
"= collections.defaultdict(lambda : '38') kor_2_eng = collections.defaultdict(lambda : 'UNKNOWN') code_2_icono['SKY_O00']",
"= collections.defaultdict(lambda : 'UNKNOWN') code_2_icono['SKY_O00'] = ['38'] code_2_icono['SKY_O01'] = ['01',",
"self._drawText(canvas, translated, 70,140, font_size=20, center_horizontal=True) base_x,base_y = 145,5 for i,w",
"else: return os.path.join(dname, l[0] + '.png') else: return os.path.join(dname, l[0]",
"['18'] code_2_icono['SKY_O08'] = ['21'] code_2_icono['SKY_O09'] = ['32'] code_2_icono['SKY_O10'] = ['04']",
"for debugging purpose with open(\"result.jpg\", \"wb\") as fp: canvas.save(fp) print(\"result",
"+ '.png') BLACK = 0 WHITE = 1 class PapirusRenderer:",
"canvas.paste(image,(x,y)) def _drawText(self, canvas, text, x, y, font_size=20, center_horizontal=False): draw",
"collections.defaultdict(lambda : 'UNKNOWN') code_2_icono['SKY_O00'] = ['38'] code_2_icono['SKY_O01'] = ['01', '08']",
": '38') kor_2_eng = collections.defaultdict(lambda : 'UNKNOWN') code_2_icono['SKY_O00'] = ['38']",
"= 0 WHITE = 1 class PapirusRenderer: \"\"\"Renderer for Papirus",
"translated = kor_2_eng[weather.air_quality][0] print(\"cur airq translated: %s\"%translated) self._drawText(canvas, translated, 70,140,",
"debugging purpose with open(\"result.jpg\", \"wb\") as fp: canvas.save(fp) print(\"result file",
"== None: # save a image for debugging purpose with",
"in enumerate(weather_forecast): fname = geticonfname(w.weather_code) self._drawImage(canvas, fname, base_x, base_y+55*i, (50,50))",
"l[0] + '.png') BLACK = 0 WHITE = 1 class",
"print(\"cur airq : %s\"%str(weather.air_quality)) temperature = str(weather.cur_temperature).split('.')[0] + u\" \\u2103\"",
"enumerate(weather_forecast): fname = geticonfname(w.weather_code) self._drawImage(canvas, fname, base_x, base_y+55*i, (50,50)) temperature",
"utf-8 -- import sys reload(sys) sys.setdefaultencoding('utf-8') import os import time",
": %s\"%str(weather.weather_desc)) print(\"cur airq : %s\"%str(weather.air_quality)) temperature = str(weather.cur_temperature).split('.')[0] +",
"= ['29'] code_2_icono['SKY_O12'] = ['26'] code_2_icono['SKY_O13'] = ['27'] code_2_icono['SKY_O14'] =",
"# save a image for debugging purpose with open(\"result.jpg\", \"wb\")",
"= self.papirus.size print(\"papirus size : %s\"%str(self.canvas_size)) except ImportError: print(\"papirus import",
"= ['28'] code_2_icono['SKY_W00'] = ['38'] code_2_icono['SKY_W01'] = ['01', '08'] code_2_icono['SKY_W02']",
"cur_hour > 18 if is_night: return os.path.join(dname, l[1] + '.png')",
"y, font_size=20, center_horizontal=False): draw = ImageDraw.Draw(canvas) font = ImageFont.truetype(self.font_path, font_size)",
"code_2_icono['SKY_W03'] = ['03', '10'] code_2_icono['SKY_W04'] = ['18'] code_2_icono['SKY_W07'] = ['21']",
"font_size=20, center_horizontal=True) translated = kor_2_eng[weather.air_quality][0] print(\"cur airq translated: %s\"%translated) self._drawText(canvas,",
"for Papirus HAT\"\"\" def __init__(self, rotate=0, font_path=None): if font_path: self.font_path",
"x, y, font_size=20, center_horizontal=False): draw = ImageDraw.Draw(canvas) font = ImageFont.truetype(self.font_path,",
"import Papirus self.papirus = Papirus(rotate=rotate) self.canvas_size = self.papirus.size print(\"papirus size",
"ImageOps.grayscale(image) image = image.resize(size) image = image.convert(\"1\", dither=Image.FLOYDSTEINBERG) canvas.paste(image,(x,y)) def",
"code_2_icono['SKY_W13'] = ['32'] kor_2_eng[u'좋음'] = ['GOOD'] kor_2_eng[u'보통'] = ['NORMAL'] kor_2_eng[u'나쁨']",
"self.papirus.update() def _drawImage(self, canvas, image_path, x, y, size): image =",
"canvas, text, x, y, font_size=20, center_horizontal=False): draw = ImageDraw.Draw(canvas) font",
"%s\"%str(self.canvas_size)) except ImportError: print(\"papirus import failed\") self.papirus = None self.canvas_size",
"['03', '10'] code_2_icono['SKY_W04'] = ['18'] code_2_icono['SKY_W07'] = ['21'] code_2_icono['SKY_W09'] =",
"WHITE) print(\"font_path:\",self.font_path) fname = geticonfname(weather.weather_code, drawNight=True) print(\"file:\",fname) self._drawImage(canvas, fname, 20,10,(100,100))",
"code_2_icono['SKY_O10'] = ['04'] code_2_icono['SKY_O11'] = ['29'] code_2_icono['SKY_O12'] = ['26'] code_2_icono['SKY_O13']",
"reload(sys) sys.setdefaultencoding('utf-8') import os import time import collections from PIL",
"except ImportError: print(\"papirus import failed\") self.papirus = None self.canvas_size =",
"'08'] code_2_icono['SKY_O02'] = ['02', '09'] code_2_icono['SKY_O03'] = ['03', '10'] code_2_icono['SKY_O04']",
"= ImageOps.grayscale(image) image = image.resize(size) image = image.convert(\"1\", dither=Image.FLOYDSTEINBERG) canvas.paste(image,(x,y))",
"for i,w in enumerate(weather_forecast): fname = geticonfname(w.weather_code) self._drawImage(canvas, fname, base_x,",
"self._drawText(canvas, time.strftime(\"%Y-%m-%d %H:%M\",time.localtime()), 136, 165, font_size=9, center_horizontal=True) if self.papirus ==",
"self.canvas_size = self.papirus.size print(\"papirus size : %s\"%str(self.canvas_size)) except ImportError: print(\"papirus",
"a image for debugging purpose with open(\"result.jpg\", \"wb\") as fp:",
"i,w in enumerate(weather_forecast): fname = geticonfname(w.weather_code) self._drawImage(canvas, fname, base_x, base_y+55*i,",
"self.papirus.display(canvas) self.papirus.update() def _drawImage(self, canvas, image_path, x, y, size): image",
"print(\"cur airq translated: %s\"%translated) self._drawText(canvas, translated, 70,140, font_size=20, center_horizontal=True) base_x,base_y",
"os.path.join(dname, l[1] + '.png') else: return os.path.join(dname, l[0] + '.png')",
"str(w.max_temperature) self._drawText(canvas, temperature, base_x+80, base_y+28+55*i, font_size=14, center_horizontal=True) # update time",
"text_draw_size = draw.textsize(text, font=font) if center_horizontal: x = x -",
"['12', '40'] code_2_icono['SKY_W10'] = ['21'] code_2_icono['SKY_W11'] = ['04'] code_2_icono['SKY_W12'] =",
"l = code_2_icono[code] dname = os.path.join(os.path.dirname(__file__), \"resources\", \"weather_icons_mod\") if len(l)",
"temperature, base_x+80, base_y+28+55*i, font_size=14, center_horizontal=True) # update time self._drawText(canvas, time.strftime(\"%Y-%m-%d",
"= ['04'] code_2_icono['SKY_W12'] = ['13', '41'] code_2_icono['SKY_W13'] = ['32'] kor_2_eng[u'좋음']",
"def geticonfname(code, drawNight=False): l = code_2_icono[code] dname = os.path.join(os.path.dirname(__file__), \"resources\",",
"> 1 and drawNight: cur_hour = time.localtime().tm_hour is_night = cur_hour",
"import collections from PIL import Image, ImageOps, ImageDraw, ImageFont code_2_icono",
"fname, 20,10,(100,100)) print(\"cur desc : %s\"%str(weather.weather_desc)) print(\"cur airq : %s\"%str(weather.air_quality))",
"font=font) if center_horizontal: x = x - text_draw_size[0]/2 draw.text( (x,",
"code_2_icono['SKY_O14'] = ['28'] code_2_icono['SKY_W00'] = ['38'] code_2_icono['SKY_W01'] = ['01', '08']",
"= ['02', '09'] code_2_icono['SKY_W03'] = ['03', '10'] code_2_icono['SKY_W04'] = ['18']",
"= ['13', '41'] code_2_icono['SKY_O06'] = ['14', '42'] code_2_icono['SKY_O07'] = ['18']",
"+ u\" \\u2103\" self._drawText(canvas, temperature, 70,115, font_size=20, center_horizontal=True) translated =",
"file saved\") else: self.papirus.display(canvas) self.papirus.update() def _drawImage(self, canvas, image_path, x,",
"['BAD'] kor_2_eng[u'매우 나쁨'] = ['V BAD'] def geticonfname(code, drawNight=False): l",
"= 145,5 for i,w in enumerate(weather_forecast): fname = geticonfname(w.weather_code) self._drawImage(canvas,",
"code_2_icono['SKY_O11'] = ['29'] code_2_icono['SKY_O12'] = ['26'] code_2_icono['SKY_O13'] = ['27'] code_2_icono['SKY_O14']",
"1 and drawNight: cur_hour = time.localtime().tm_hour is_night = cur_hour <",
"self._drawImage(canvas, fname, 20,10,(100,100)) print(\"cur desc : %s\"%str(weather.weather_desc)) print(\"cur airq :",
"purpose with open(\"result.jpg\", \"wb\") as fp: canvas.save(fp) print(\"result file saved\")",
"image.convert(\"1\", dither=Image.FLOYDSTEINBERG) canvas.paste(image,(x,y)) def _drawText(self, canvas, text, x, y, font_size=20,",
"= ['01', '08'] code_2_icono['SKY_O02'] = ['02', '09'] code_2_icono['SKY_O03'] = ['03',",
"['27'] code_2_icono['SKY_O14'] = ['28'] code_2_icono['SKY_W00'] = ['38'] code_2_icono['SKY_W01'] = ['01',",
"['21'] code_2_icono['SKY_W11'] = ['04'] code_2_icono['SKY_W12'] = ['13', '41'] code_2_icono['SKY_W13'] =",
"time self._drawText(canvas, time.strftime(\"%Y-%m-%d %H:%M\",time.localtime()), 136, 165, font_size=9, center_horizontal=True) if self.papirus",
"kor_2_eng[weather.air_quality][0] print(\"cur airq translated: %s\"%translated) self._drawText(canvas, translated, 70,140, font_size=20, center_horizontal=True)",
"ImageFont.truetype(self.font_path, font_size) text_draw_size = draw.textsize(text, font=font) if center_horizontal: x =",
"'UNKNOWN') code_2_icono['SKY_O00'] = ['38'] code_2_icono['SKY_O01'] = ['01', '08'] code_2_icono['SKY_O02'] =",
"x - text_draw_size[0]/2 draw.text( (x, y) , text, font=font, fill=BLACK)",
"base_x+80, base_y+28+55*i, font_size=14, center_horizontal=True) # update time self._drawText(canvas, time.strftime(\"%Y-%m-%d %H:%M\",time.localtime()),",
"fname = geticonfname(weather.weather_code, drawNight=True) print(\"file:\",fname) self._drawImage(canvas, fname, 20,10,(100,100)) print(\"cur desc",
"\" / \" + str(w.max_temperature) self._drawText(canvas, temperature, base_x+80, base_y+28+55*i, font_size=14,",
"x, y, size): image = Image.open(image_path) image = ImageOps.grayscale(image) image",
"> 18 if is_night: return os.path.join(dname, l[1] + '.png') else:",
"image for debugging purpose with open(\"result.jpg\", \"wb\") as fp: canvas.save(fp)",
"font = ImageFont.truetype(self.font_path, font_size) text_draw_size = draw.textsize(text, font=font) if center_horizontal:",
"text, x, y, font_size=20, center_horizontal=False): draw = ImageDraw.Draw(canvas) font =",
"BLACK = 0 WHITE = 1 class PapirusRenderer: \"\"\"Renderer for",
"is_night: return os.path.join(dname, l[1] + '.png') else: return os.path.join(dname, l[0]",
"+ '.png') else: return os.path.join(dname, l[0] + '.png') BLACK =",
"%H:%M\",time.localtime()), 136, 165, font_size=9, center_horizontal=True) if self.papirus == None: #",
"l[0] + '.png') else: return os.path.join(dname, l[0] + '.png') BLACK",
"= ['GOOD'] kor_2_eng[u'보통'] = ['NORMAL'] kor_2_eng[u'나쁨'] = ['BAD'] kor_2_eng[u'매우 나쁨']",
"= ['21'] code_2_icono['SKY_O09'] = ['32'] code_2_icono['SKY_O10'] = ['04'] code_2_icono['SKY_O11'] =",
"= ['32'] kor_2_eng[u'좋음'] = ['GOOD'] kor_2_eng[u'보통'] = ['NORMAL'] kor_2_eng[u'나쁨'] =",
"= str(w.min_temperature) + \" / \" + str(w.max_temperature) self._drawText(canvas, temperature,",
"= kor_2_eng[weather.air_quality][0] print(\"cur airq translated: %s\"%translated) self._drawText(canvas, translated, 70,140, font_size=20,",
"str(w.min_temperature) + \" / \" + str(w.max_temperature) self._drawText(canvas, temperature, base_x+80,",
"canvas.save(fp) print(\"result file saved\") else: self.papirus.display(canvas) self.papirus.update() def _drawImage(self, canvas,",
"ImageFont code_2_icono = collections.defaultdict(lambda : '38') kor_2_eng = collections.defaultdict(lambda :",
"\"wb\") as fp: canvas.save(fp) print(\"result file saved\") else: self.papirus.display(canvas) self.papirus.update()",
"20,10,(100,100)) print(\"cur desc : %s\"%str(weather.weather_desc)) print(\"cur airq : %s\"%str(weather.air_quality)) temperature",
"fp: canvas.save(fp) print(\"result file saved\") else: self.papirus.display(canvas) self.papirus.update() def _drawImage(self,",
"Papirus(rotate=rotate) self.canvas_size = self.papirus.size print(\"papirus size : %s\"%str(self.canvas_size)) except ImportError:",
"time.localtime().tm_hour is_night = cur_hour < 5 or cur_hour > 18",
"x = x - text_draw_size[0]/2 draw.text( (x, y) , text,",
"code_2_icono['SKY_W00'] = ['38'] code_2_icono['SKY_W01'] = ['01', '08'] code_2_icono['SKY_W02'] = ['02',",
"= Papirus(rotate=rotate) self.canvas_size = self.papirus.size print(\"papirus size : %s\"%str(self.canvas_size)) except",
"return os.path.join(dname, l[0] + '.png') else: return os.path.join(dname, l[0] +",
"%s\"%str(weather.weather_desc)) print(\"cur airq : %s\"%str(weather.air_quality)) temperature = str(weather.cur_temperature).split('.')[0] + u\"",
"+ \" / \" + str(w.max_temperature) self._drawText(canvas, temperature, base_x+80, base_y+28+55*i,",
"self.font_path = \"/usr/share/fonts/truetype/freefont/FreeMono.ttf\" print(\"rotate:\",rotate) try: from papirus import Papirus self.papirus",
"papirus import Papirus self.papirus = Papirus(rotate=rotate) self.canvas_size = self.papirus.size print(\"papirus",
"70,140, font_size=20, center_horizontal=True) base_x,base_y = 145,5 for i,w in enumerate(weather_forecast):",
"ImageDraw, ImageFont code_2_icono = collections.defaultdict(lambda : '38') kor_2_eng = collections.defaultdict(lambda",
"= image.resize(size) image = image.convert(\"1\", dither=Image.FLOYDSTEINBERG) canvas.paste(image,(x,y)) def _drawText(self, canvas,",
"['21'] code_2_icono['SKY_O09'] = ['32'] code_2_icono['SKY_O10'] = ['04'] code_2_icono['SKY_O11'] = ['29']",
"['32'] code_2_icono['SKY_O10'] = ['04'] code_2_icono['SKY_O11'] = ['29'] code_2_icono['SKY_O12'] = ['26']",
"%s\"%str(weather.air_quality)) temperature = str(weather.cur_temperature).split('.')[0] + u\" \\u2103\" self._drawText(canvas, temperature, 70,115,",
": %s\"%str(weather.air_quality)) temperature = str(weather.cur_temperature).split('.')[0] + u\" \\u2103\" self._drawText(canvas, temperature,",
"draw.textsize(text, font=font) if center_horizontal: x = x - text_draw_size[0]/2 draw.text(",
"image.resize(size) image = image.convert(\"1\", dither=Image.FLOYDSTEINBERG) canvas.paste(image,(x,y)) def _drawText(self, canvas, text,",
"= 1 class PapirusRenderer: \"\"\"Renderer for Papirus HAT\"\"\" def __init__(self,",
"self.font_path = font_path else: self.font_path = \"/usr/share/fonts/truetype/freefont/FreeMono.ttf\" print(\"rotate:\",rotate) try: from",
"time.strftime(\"%Y-%m-%d %H:%M\",time.localtime()), 136, 165, font_size=9, center_horizontal=True) if self.papirus == None:",
"self.papirus = Papirus(rotate=rotate) self.canvas_size = self.papirus.size print(\"papirus size : %s\"%str(self.canvas_size))",
"code_2_icono['SKY_O07'] = ['18'] code_2_icono['SKY_O08'] = ['21'] code_2_icono['SKY_O09'] = ['32'] code_2_icono['SKY_O10']",
"kor_2_eng[u'매우 나쁨'] = ['V BAD'] def geticonfname(code, drawNight=False): l =",
"coding: utf-8 -- import sys reload(sys) sys.setdefaultencoding('utf-8') import os import",
"0 WHITE = 1 class PapirusRenderer: \"\"\"Renderer for Papirus HAT\"\"\"",
"print(\"cur desc : %s\"%str(weather.weather_desc)) print(\"cur airq : %s\"%str(weather.air_quality)) temperature =",
"weather_forecast): canvas = Image.new('1', self.canvas_size, WHITE) print(\"font_path:\",self.font_path) fname = geticonfname(weather.weather_code,",
"['02', '09'] code_2_icono['SKY_W03'] = ['03', '10'] code_2_icono['SKY_W04'] = ['18'] code_2_icono['SKY_W07']",
"weather, weather_forecast): canvas = Image.new('1', self.canvas_size, WHITE) print(\"font_path:\",self.font_path) fname =",
"class PapirusRenderer: \"\"\"Renderer for Papirus HAT\"\"\" def __init__(self, rotate=0, font_path=None):",
"(50,50)) temperature = str(w.min_temperature) + \" / \" + str(w.max_temperature)",
"70,115, font_size=20, center_horizontal=True) translated = kor_2_eng[weather.air_quality][0] print(\"cur airq translated: %s\"%translated)",
"str(weather.cur_temperature).split('.')[0] + u\" \\u2103\" self._drawText(canvas, temperature, 70,115, font_size=20, center_horizontal=True) translated",
"font_path: self.font_path = font_path else: self.font_path = \"/usr/share/fonts/truetype/freefont/FreeMono.ttf\" print(\"rotate:\",rotate) try:",
"= None self.canvas_size = (264,176) def render(self, weather, weather_forecast): canvas",
"['26'] code_2_icono['SKY_O13'] = ['27'] code_2_icono['SKY_O14'] = ['28'] code_2_icono['SKY_W00'] = ['38']",
"code_2_icono = collections.defaultdict(lambda : '38') kor_2_eng = collections.defaultdict(lambda : 'UNKNOWN')",
"'10'] code_2_icono['SKY_O04'] = ['12', '40'] code_2_icono['SKY_O05'] = ['13', '41'] code_2_icono['SKY_O06']",
"os import time import collections from PIL import Image, ImageOps,",
"= (264,176) def render(self, weather, weather_forecast): canvas = Image.new('1', self.canvas_size,",
"import sys reload(sys) sys.setdefaultencoding('utf-8') import os import time import collections",
"['03', '10'] code_2_icono['SKY_O04'] = ['12', '40'] code_2_icono['SKY_O05'] = ['13', '41']",
"self._drawImage(canvas, fname, base_x, base_y+55*i, (50,50)) temperature = str(w.min_temperature) + \"",
"'38') kor_2_eng = collections.defaultdict(lambda : 'UNKNOWN') code_2_icono['SKY_O00'] = ['38'] code_2_icono['SKY_O01']",
"def _drawImage(self, canvas, image_path, x, y, size): image = Image.open(image_path)",
"saved\") else: self.papirus.display(canvas) self.papirus.update() def _drawImage(self, canvas, image_path, x, y,",
"None self.canvas_size = (264,176) def render(self, weather, weather_forecast): canvas =",
"temperature = str(weather.cur_temperature).split('.')[0] + u\" \\u2103\" self._drawText(canvas, temperature, 70,115, font_size=20,",
"def __init__(self, rotate=0, font_path=None): if font_path: self.font_path = font_path else:",
"['21'] code_2_icono['SKY_W09'] = ['12', '40'] code_2_icono['SKY_W10'] = ['21'] code_2_icono['SKY_W11'] =",
"translated: %s\"%translated) self._drawText(canvas, translated, 70,140, font_size=20, center_horizontal=True) base_x,base_y = 145,5",
"Image, ImageOps, ImageDraw, ImageFont code_2_icono = collections.defaultdict(lambda : '38') kor_2_eng",
"['38'] code_2_icono['SKY_W01'] = ['01', '08'] code_2_icono['SKY_W02'] = ['02', '09'] code_2_icono['SKY_W03']",
"if font_path: self.font_path = font_path else: self.font_path = \"/usr/share/fonts/truetype/freefont/FreeMono.ttf\" print(\"rotate:\",rotate)",
"\\u2103\" self._drawText(canvas, temperature, 70,115, font_size=20, center_horizontal=True) translated = kor_2_eng[weather.air_quality][0] print(\"cur",
"['01', '08'] code_2_icono['SKY_W02'] = ['02', '09'] code_2_icono['SKY_W03'] = ['03', '10']",
"'42'] code_2_icono['SKY_O07'] = ['18'] code_2_icono['SKY_O08'] = ['21'] code_2_icono['SKY_O09'] = ['32']",
"= ['NORMAL'] kor_2_eng[u'나쁨'] = ['BAD'] kor_2_eng[u'매우 나쁨'] = ['V BAD']",
"_drawImage(self, canvas, image_path, x, y, size): image = Image.open(image_path) image",
"['32'] kor_2_eng[u'좋음'] = ['GOOD'] kor_2_eng[u'보통'] = ['NORMAL'] kor_2_eng[u'나쁨'] = ['BAD']",
"'08'] code_2_icono['SKY_W02'] = ['02', '09'] code_2_icono['SKY_W03'] = ['03', '10'] code_2_icono['SKY_W04']",
"%s\"%translated) self._drawText(canvas, translated, 70,140, font_size=20, center_horizontal=True) base_x,base_y = 145,5 for",
"ImportError: print(\"papirus import failed\") self.papirus = None self.canvas_size = (264,176)",
"else: return os.path.join(dname, l[0] + '.png') BLACK = 0 WHITE",
"PIL import Image, ImageOps, ImageDraw, ImageFont code_2_icono = collections.defaultdict(lambda :",
"y, size): image = Image.open(image_path) image = ImageOps.grayscale(image) image =",
"= ['18'] code_2_icono['SKY_W07'] = ['21'] code_2_icono['SKY_W09'] = ['12', '40'] code_2_icono['SKY_W10']",
"= ['01', '08'] code_2_icono['SKY_W02'] = ['02', '09'] code_2_icono['SKY_W03'] = ['03',",
"font_size) text_draw_size = draw.textsize(text, font=font) if center_horizontal: x = x",
"self._drawText(canvas, temperature, 70,115, font_size=20, center_horizontal=True) translated = kor_2_eng[weather.air_quality][0] print(\"cur airq",
"= ['32'] code_2_icono['SKY_O10'] = ['04'] code_2_icono['SKY_O11'] = ['29'] code_2_icono['SKY_O12'] =",
"['13', '41'] code_2_icono['SKY_W13'] = ['32'] kor_2_eng[u'좋음'] = ['GOOD'] kor_2_eng[u'보통'] =",
"ImageOps, ImageDraw, ImageFont code_2_icono = collections.defaultdict(lambda : '38') kor_2_eng =",
"code_2_icono['SKY_W09'] = ['12', '40'] code_2_icono['SKY_W10'] = ['21'] code_2_icono['SKY_W11'] = ['04']",
"center_horizontal=True) # update time self._drawText(canvas, time.strftime(\"%Y-%m-%d %H:%M\",time.localtime()), 136, 165, font_size=9,",
"kor_2_eng[u'나쁨'] = ['BAD'] kor_2_eng[u'매우 나쁨'] = ['V BAD'] def geticonfname(code,",
"code_2_icono['SKY_W12'] = ['13', '41'] code_2_icono['SKY_W13'] = ['32'] kor_2_eng[u'좋음'] = ['GOOD']",
"import time import collections from PIL import Image, ImageOps, ImageDraw,",
"None: # save a image for debugging purpose with open(\"result.jpg\",",
"code_2_icono['SKY_W07'] = ['21'] code_2_icono['SKY_W09'] = ['12', '40'] code_2_icono['SKY_W10'] = ['21']",
"font_size=20, center_horizontal=False): draw = ImageDraw.Draw(canvas) font = ImageFont.truetype(self.font_path, font_size) text_draw_size",
"code_2_icono['SKY_W11'] = ['04'] code_2_icono['SKY_W12'] = ['13', '41'] code_2_icono['SKY_W13'] = ['32']",
"def render(self, weather, weather_forecast): canvas = Image.new('1', self.canvas_size, WHITE) print(\"font_path:\",self.font_path)",
"/ \" + str(w.max_temperature) self._drawText(canvas, temperature, base_x+80, base_y+28+55*i, font_size=14, center_horizontal=True)",
"'09'] code_2_icono['SKY_O03'] = ['03', '10'] code_2_icono['SKY_O04'] = ['12', '40'] code_2_icono['SKY_O05']",
"failed\") self.papirus = None self.canvas_size = (264,176) def render(self, weather,",
"collections from PIL import Image, ImageOps, ImageDraw, ImageFont code_2_icono =",
"u\" \\u2103\" self._drawText(canvas, temperature, 70,115, font_size=20, center_horizontal=True) translated = kor_2_eng[weather.air_quality][0]",
"나쁨'] = ['V BAD'] def geticonfname(code, drawNight=False): l = code_2_icono[code]",
"code_2_icono['SKY_O00'] = ['38'] code_2_icono['SKY_O01'] = ['01', '08'] code_2_icono['SKY_O02'] = ['02',",
"= str(weather.cur_temperature).split('.')[0] + u\" \\u2103\" self._drawText(canvas, temperature, 70,115, font_size=20, center_horizontal=True)",
"import os import time import collections from PIL import Image,",
"update time self._drawText(canvas, time.strftime(\"%Y-%m-%d %H:%M\",time.localtime()), 136, 165, font_size=9, center_horizontal=True) if",
"['18'] code_2_icono['SKY_W07'] = ['21'] code_2_icono['SKY_W09'] = ['12', '40'] code_2_icono['SKY_W10'] =",
"\"resources\", \"weather_icons_mod\") if len(l) > 1 and drawNight: cur_hour =",
"= time.localtime().tm_hour is_night = cur_hour < 5 or cur_hour >",
"= geticonfname(weather.weather_code, drawNight=True) print(\"file:\",fname) self._drawImage(canvas, fname, 20,10,(100,100)) print(\"cur desc :",
"['04'] code_2_icono['SKY_W12'] = ['13', '41'] code_2_icono['SKY_W13'] = ['32'] kor_2_eng[u'좋음'] =",
"= ['18'] code_2_icono['SKY_O08'] = ['21'] code_2_icono['SKY_O09'] = ['32'] code_2_icono['SKY_O10'] =",
"HAT\"\"\" def __init__(self, rotate=0, font_path=None): if font_path: self.font_path = font_path",
"Image.open(image_path) image = ImageOps.grayscale(image) image = image.resize(size) image = image.convert(\"1\",",
"Image.new('1', self.canvas_size, WHITE) print(\"font_path:\",self.font_path) fname = geticonfname(weather.weather_code, drawNight=True) print(\"file:\",fname) self._drawImage(canvas,",
"165, font_size=9, center_horizontal=True) if self.papirus == None: # save a",
"145,5 for i,w in enumerate(weather_forecast): fname = geticonfname(w.weather_code) self._drawImage(canvas, fname,",
"WHITE = 1 class PapirusRenderer: \"\"\"Renderer for Papirus HAT\"\"\" def",
"center_horizontal=False): draw = ImageDraw.Draw(canvas) font = ImageFont.truetype(self.font_path, font_size) text_draw_size =",
"print(\"font_path:\",self.font_path) fname = geticonfname(weather.weather_code, drawNight=True) print(\"file:\",fname) self._drawImage(canvas, fname, 20,10,(100,100)) print(\"cur",
"if center_horizontal: x = x - text_draw_size[0]/2 draw.text( (x, y)",
"code_2_icono['SKY_O03'] = ['03', '10'] code_2_icono['SKY_O04'] = ['12', '40'] code_2_icono['SKY_O05'] =",
"font_size=20, center_horizontal=True) base_x,base_y = 145,5 for i,w in enumerate(weather_forecast): fname",
"open(\"result.jpg\", \"wb\") as fp: canvas.save(fp) print(\"result file saved\") else: self.papirus.display(canvas)",
"-- import sys reload(sys) sys.setdefaultencoding('utf-8') import os import time import",
"fname, base_x, base_y+55*i, (50,50)) temperature = str(w.min_temperature) + \" /",
"< 5 or cur_hour > 18 if is_night: return os.path.join(dname,",
"= code_2_icono[code] dname = os.path.join(os.path.dirname(__file__), \"resources\", \"weather_icons_mod\") if len(l) >",
"base_y+55*i, (50,50)) temperature = str(w.min_temperature) + \" / \" +",
"print(\"file:\",fname) self._drawImage(canvas, fname, 20,10,(100,100)) print(\"cur desc : %s\"%str(weather.weather_desc)) print(\"cur airq",
"import Image, ImageOps, ImageDraw, ImageFont code_2_icono = collections.defaultdict(lambda : '38')",
"code_2_icono[code] dname = os.path.join(os.path.dirname(__file__), \"resources\", \"weather_icons_mod\") if len(l) > 1",
"drawNight=False): l = code_2_icono[code] dname = os.path.join(os.path.dirname(__file__), \"resources\", \"weather_icons_mod\") if",
"kor_2_eng = collections.defaultdict(lambda : 'UNKNOWN') code_2_icono['SKY_O00'] = ['38'] code_2_icono['SKY_O01'] =",
"= \"/usr/share/fonts/truetype/freefont/FreeMono.ttf\" print(\"rotate:\",rotate) try: from papirus import Papirus self.papirus =",
"Papirus HAT\"\"\" def __init__(self, rotate=0, font_path=None): if font_path: self.font_path =",
"['29'] code_2_icono['SKY_O12'] = ['26'] code_2_icono['SKY_O13'] = ['27'] code_2_icono['SKY_O14'] = ['28']",
"18 if is_night: return os.path.join(dname, l[1] + '.png') else: return",
"import failed\") self.papirus = None self.canvas_size = (264,176) def render(self,",
"['38'] code_2_icono['SKY_O01'] = ['01', '08'] code_2_icono['SKY_O02'] = ['02', '09'] code_2_icono['SKY_O03']",
"= ['12', '40'] code_2_icono['SKY_W10'] = ['21'] code_2_icono['SKY_W11'] = ['04'] code_2_icono['SKY_W12']",
"['04'] code_2_icono['SKY_O11'] = ['29'] code_2_icono['SKY_O12'] = ['26'] code_2_icono['SKY_O13'] = ['27']",
"= font_path else: self.font_path = \"/usr/share/fonts/truetype/freefont/FreeMono.ttf\" print(\"rotate:\",rotate) try: from papirus",
"center_horizontal=True) translated = kor_2_eng[weather.air_quality][0] print(\"cur airq translated: %s\"%translated) self._drawText(canvas, translated,",
"desc : %s\"%str(weather.weather_desc)) print(\"cur airq : %s\"%str(weather.air_quality)) temperature = str(weather.cur_temperature).split('.')[0]",
"['02', '09'] code_2_icono['SKY_O03'] = ['03', '10'] code_2_icono['SKY_O04'] = ['12', '40']",
"font_path else: self.font_path = \"/usr/share/fonts/truetype/freefont/FreeMono.ttf\" print(\"rotate:\",rotate) try: from papirus import",
"= ['13', '41'] code_2_icono['SKY_W13'] = ['32'] kor_2_eng[u'좋음'] = ['GOOD'] kor_2_eng[u'보통']",
"['14', '42'] code_2_icono['SKY_O07'] = ['18'] code_2_icono['SKY_O08'] = ['21'] code_2_icono['SKY_O09'] =",
"kor_2_eng[u'보통'] = ['NORMAL'] kor_2_eng[u'나쁨'] = ['BAD'] kor_2_eng[u'매우 나쁨'] = ['V",
"= ['03', '10'] code_2_icono['SKY_W04'] = ['18'] code_2_icono['SKY_W07'] = ['21'] code_2_icono['SKY_W09']",
"image = image.resize(size) image = image.convert(\"1\", dither=Image.FLOYDSTEINBERG) canvas.paste(image,(x,y)) def _drawText(self,",
"self.papirus.size print(\"papirus size : %s\"%str(self.canvas_size)) except ImportError: print(\"papirus import failed\")",
"= geticonfname(w.weather_code) self._drawImage(canvas, fname, base_x, base_y+55*i, (50,50)) temperature = str(w.min_temperature)",
"code_2_icono['SKY_W04'] = ['18'] code_2_icono['SKY_W07'] = ['21'] code_2_icono['SKY_W09'] = ['12', '40']",
"sys.setdefaultencoding('utf-8') import os import time import collections from PIL import",
"code_2_icono['SKY_O05'] = ['13', '41'] code_2_icono['SKY_O06'] = ['14', '42'] code_2_icono['SKY_O07'] =",
"l[1] + '.png') else: return os.path.join(dname, l[0] + '.png') else:",
"cur_hour < 5 or cur_hour > 18 if is_night: return",
"if is_night: return os.path.join(dname, l[1] + '.png') else: return os.path.join(dname,",
"from PIL import Image, ImageOps, ImageDraw, ImageFont code_2_icono = collections.defaultdict(lambda",
"= ['21'] code_2_icono['SKY_W09'] = ['12', '40'] code_2_icono['SKY_W10'] = ['21'] code_2_icono['SKY_W11']",
"code_2_icono['SKY_O09'] = ['32'] code_2_icono['SKY_O10'] = ['04'] code_2_icono['SKY_O11'] = ['29'] code_2_icono['SKY_O12']",
"self.canvas_size = (264,176) def render(self, weather, weather_forecast): canvas = Image.new('1',",
"time import collections from PIL import Image, ImageOps, ImageDraw, ImageFont",
"self._drawText(canvas, temperature, base_x+80, base_y+28+55*i, font_size=14, center_horizontal=True) # update time self._drawText(canvas,",
"= ['03', '10'] code_2_icono['SKY_O04'] = ['12', '40'] code_2_icono['SKY_O05'] = ['13',",
"center_horizontal: x = x - text_draw_size[0]/2 draw.text( (x, y) ,",
"# update time self._drawText(canvas, time.strftime(\"%Y-%m-%d %H:%M\",time.localtime()), 136, 165, font_size=9, center_horizontal=True)",
"= Image.open(image_path) image = ImageOps.grayscale(image) image = image.resize(size) image =",
"= ['BAD'] kor_2_eng[u'매우 나쁨'] = ['V BAD'] def geticonfname(code, drawNight=False):",
"5 or cur_hour > 18 if is_night: return os.path.join(dname, l[1]",
"code_2_icono['SKY_O02'] = ['02', '09'] code_2_icono['SKY_O03'] = ['03', '10'] code_2_icono['SKY_O04'] =",
"geticonfname(code, drawNight=False): l = code_2_icono[code] dname = os.path.join(os.path.dirname(__file__), \"resources\", \"weather_icons_mod\")",
"PapirusRenderer: \"\"\"Renderer for Papirus HAT\"\"\" def __init__(self, rotate=0, font_path=None): if",
"image = image.convert(\"1\", dither=Image.FLOYDSTEINBERG) canvas.paste(image,(x,y)) def _drawText(self, canvas, text, x,",
"center_horizontal=True) base_x,base_y = 145,5 for i,w in enumerate(weather_forecast): fname =",
"'41'] code_2_icono['SKY_O06'] = ['14', '42'] code_2_icono['SKY_O07'] = ['18'] code_2_icono['SKY_O08'] =",
"['GOOD'] kor_2_eng[u'보통'] = ['NORMAL'] kor_2_eng[u'나쁨'] = ['BAD'] kor_2_eng[u'매우 나쁨'] =",
"else: self.font_path = \"/usr/share/fonts/truetype/freefont/FreeMono.ttf\" print(\"rotate:\",rotate) try: from papirus import Papirus"
] |
[] |
[
"import keras import keras2onnx if __name__ == \"__main__\": \"\"\" Lightweight",
"passing an input numpy path\") args = parser.parse_args() # load",
"parser = argparse.ArgumentParser(\"Data Augmentation\") parser.add_argument('keras_model_path', help=\"Path of the input keras",
"(C) Copyright 1996- ECMWF. # # This software is licensed",
"onnx model\") parser.add_argument(\"--verify_with\", help=\"Check the model by passing an input",
"Apache Licence Version 2.0 # which can be obtained at",
"# This software is licensed under the terms of the",
"keras2onnx if __name__ == \"__main__\": \"\"\" Lightweight script to convert",
"the output onnx model\") parser.add_argument(\"--verify_with\", help=\"Check the model by passing",
"model into a TFlite model \"\"\" parser = argparse.ArgumentParser(\"Data Augmentation\")",
"= parser.parse_args() # load the keras model model = keras.models.load_model(args.keras_model_path)",
"1996- ECMWF. # # This software is licensed under the",
"keras import keras2onnx if __name__ == \"__main__\": \"\"\" Lightweight script",
"is licensed under the terms of the Apache Licence Version",
"it submit to any jurisdiction. # import os import numpy",
"of the input keras model\") parser.add_argument('onnx_model_path', help=\"Path of the output",
"which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this",
"\"__main__\": \"\"\" Lightweight script to convert a keras model into",
"== \"__main__\": \"\"\" Lightweight script to convert a keras model",
"parser.add_argument('keras_model_path', help=\"Path of the input keras model\") parser.add_argument('onnx_model_path', help=\"Path of",
"to any jurisdiction. # import os import numpy as np",
"of the Apache Licence Version 2.0 # which can be",
"\"\"\" Lightweight script to convert a keras model into a",
"do the conversion onnx_model = keras2onnx.convert_keras(model, model.name) # write to",
"2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In",
"This software is licensed under the terms of the Apache",
"Lightweight script to convert a keras model into a TFlite",
"np import argparse import keras import keras2onnx if __name__ ==",
"import os import numpy as np import argparse import keras",
"virtue of its status as an intergovernmental organisation # nor",
"http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive",
"licensed under the terms of the Apache Licence Version 2.0",
"convert a keras model into a TFlite model \"\"\" parser",
"model\") parser.add_argument(\"--verify_with\", help=\"Check the model by passing an input numpy",
"keras model model = keras.models.load_model(args.keras_model_path) model.summary() # do the conversion",
"immunities # granted to it by virtue of its status",
"of its status as an intergovernmental organisation # nor does",
"status as an intergovernmental organisation # nor does it submit",
"onnx_model = keras2onnx.convert_keras(model, model.name) # write to file file =",
"\"\"\" parser = argparse.ArgumentParser(\"Data Augmentation\") parser.add_argument('keras_model_path', help=\"Path of the input",
"can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence,",
"if __name__ == \"__main__\": \"\"\" Lightweight script to convert a",
"of the output onnx model\") parser.add_argument(\"--verify_with\", help=\"Check the model by",
"os import numpy as np import argparse import keras import",
"does not waive the privileges and immunities # granted to",
"terms of the Apache Licence Version 2.0 # which can",
"import keras2onnx if __name__ == \"__main__\": \"\"\" Lightweight script to",
"<reponame>ecmwf-lab/infero # # (C) Copyright 1996- ECMWF. # # This",
"script to convert a keras model into a TFlite model",
"licence, ECMWF does not waive the privileges and immunities #",
"= keras.models.load_model(args.keras_model_path) model.summary() # do the conversion onnx_model = keras2onnx.convert_keras(model,",
"the model by passing an input numpy path\") args =",
"load the keras model model = keras.models.load_model(args.keras_model_path) model.summary() # do",
"keras.models.load_model(args.keras_model_path) model.summary() # do the conversion onnx_model = keras2onnx.convert_keras(model, model.name)",
"into a TFlite model \"\"\" parser = argparse.ArgumentParser(\"Data Augmentation\") parser.add_argument('keras_model_path',",
"# load the keras model model = keras.models.load_model(args.keras_model_path) model.summary() #",
"obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does",
"does it submit to any jurisdiction. # import os import",
"model.summary() # do the conversion onnx_model = keras2onnx.convert_keras(model, model.name) #",
"applying this licence, ECMWF does not waive the privileges and",
"keras2onnx.convert_keras(model, model.name) # write to file file = open(args.onnx_model_path, \"wb\")",
"help=\"Path of the output onnx model\") parser.add_argument(\"--verify_with\", help=\"Check the model",
"# do the conversion onnx_model = keras2onnx.convert_keras(model, model.name) # write",
"granted to it by virtue of its status as an",
"waive the privileges and immunities # granted to it by",
"Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.",
"a keras model into a TFlite model \"\"\" parser =",
"the terms of the Apache Licence Version 2.0 # which",
"this licence, ECMWF does not waive the privileges and immunities",
"input numpy path\") args = parser.parse_args() # load the keras",
"ECMWF does not waive the privileges and immunities # granted",
"by virtue of its status as an intergovernmental organisation #",
"an input numpy path\") args = parser.parse_args() # load the",
"model.name) # write to file file = open(args.onnx_model_path, \"wb\") file.write(onnx_model.SerializeToString())",
"numpy path\") args = parser.parse_args() # load the keras model",
"at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not",
"and immunities # granted to it by virtue of its",
"ECMWF. # # This software is licensed under the terms",
"conversion onnx_model = keras2onnx.convert_keras(model, model.name) # write to file file",
"# # This software is licensed under the terms of",
"input keras model\") parser.add_argument('onnx_model_path', help=\"Path of the output onnx model\")",
"# # (C) Copyright 1996- ECMWF. # # This software",
"# granted to it by virtue of its status as",
"the keras model model = keras.models.load_model(args.keras_model_path) model.summary() # do the",
"the privileges and immunities # granted to it by virtue",
"# (C) Copyright 1996- ECMWF. # # This software is",
"nor does it submit to any jurisdiction. # import os",
"intergovernmental organisation # nor does it submit to any jurisdiction.",
"parser.add_argument('onnx_model_path', help=\"Path of the output onnx model\") parser.add_argument(\"--verify_with\", help=\"Check the",
"a TFlite model \"\"\" parser = argparse.ArgumentParser(\"Data Augmentation\") parser.add_argument('keras_model_path', help=\"Path",
"In applying this licence, ECMWF does not waive the privileges",
"# write to file file = open(args.onnx_model_path, \"wb\") file.write(onnx_model.SerializeToString()) file.close()",
"its status as an intergovernmental organisation # nor does it",
"submit to any jurisdiction. # import os import numpy as",
"TFlite model \"\"\" parser = argparse.ArgumentParser(\"Data Augmentation\") parser.add_argument('keras_model_path', help=\"Path of",
"# nor does it submit to any jurisdiction. # import",
"an intergovernmental organisation # nor does it submit to any",
"keras model into a TFlite model \"\"\" parser = argparse.ArgumentParser(\"Data",
"help=\"Check the model by passing an input numpy path\") args",
"privileges and immunities # granted to it by virtue of",
"numpy as np import argparse import keras import keras2onnx if",
"__name__ == \"__main__\": \"\"\" Lightweight script to convert a keras",
"argparse import keras import keras2onnx if __name__ == \"__main__\": \"\"\"",
"model model = keras.models.load_model(args.keras_model_path) model.summary() # do the conversion onnx_model",
"organisation # nor does it submit to any jurisdiction. #",
"import numpy as np import argparse import keras import keras2onnx",
"software is licensed under the terms of the Apache Licence",
"Copyright 1996- ECMWF. # # This software is licensed under",
"help=\"Path of the input keras model\") parser.add_argument('onnx_model_path', help=\"Path of the",
"parser.add_argument(\"--verify_with\", help=\"Check the model by passing an input numpy path\")",
"= keras2onnx.convert_keras(model, model.name) # write to file file = open(args.onnx_model_path,",
"to it by virtue of its status as an intergovernmental",
"# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying",
"= argparse.ArgumentParser(\"Data Augmentation\") parser.add_argument('keras_model_path', help=\"Path of the input keras model\")",
"argparse.ArgumentParser(\"Data Augmentation\") parser.add_argument('keras_model_path', help=\"Path of the input keras model\") parser.add_argument('onnx_model_path',",
"output onnx model\") parser.add_argument(\"--verify_with\", help=\"Check the model by passing an",
"to convert a keras model into a TFlite model \"\"\"",
"the Apache Licence Version 2.0 # which can be obtained",
"parser.parse_args() # load the keras model model = keras.models.load_model(args.keras_model_path) model.summary()",
"under the terms of the Apache Licence Version 2.0 #",
"the conversion onnx_model = keras2onnx.convert_keras(model, model.name) # write to file",
"any jurisdiction. # import os import numpy as np import",
"Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. #",
"model \"\"\" parser = argparse.ArgumentParser(\"Data Augmentation\") parser.add_argument('keras_model_path', help=\"Path of the",
"Augmentation\") parser.add_argument('keras_model_path', help=\"Path of the input keras model\") parser.add_argument('onnx_model_path', help=\"Path",
"args = parser.parse_args() # load the keras model model =",
"be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF",
"model by passing an input numpy path\") args = parser.parse_args()",
"# In applying this licence, ECMWF does not waive the",
"the input keras model\") parser.add_argument('onnx_model_path', help=\"Path of the output onnx",
"by passing an input numpy path\") args = parser.parse_args() #",
"model\") parser.add_argument('onnx_model_path', help=\"Path of the output onnx model\") parser.add_argument(\"--verify_with\", help=\"Check",
"jurisdiction. # import os import numpy as np import argparse",
"model = keras.models.load_model(args.keras_model_path) model.summary() # do the conversion onnx_model =",
"it by virtue of its status as an intergovernmental organisation",
"not waive the privileges and immunities # granted to it",
"as np import argparse import keras import keras2onnx if __name__",
"keras model\") parser.add_argument('onnx_model_path', help=\"Path of the output onnx model\") parser.add_argument(\"--verify_with\",",
"as an intergovernmental organisation # nor does it submit to",
"path\") args = parser.parse_args() # load the keras model model",
"import argparse import keras import keras2onnx if __name__ == \"__main__\":",
"# import os import numpy as np import argparse import"
] |
[
"factor. Defaults to 10/3. Returns ------- \"\"\" for param_group in",
"# classification self.stats.training.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item() if",
"spike count if ``count_log`` is enabled \"\"\" self.net.train() if self.device",
"expected to return the accumulated loss as second argument. It",
"self.optimizer.param_groups: print('\\nLearning rate reduction from', param_group['lr']) param_group['lr'] /= factor def",
"error self.optimizer = optimizer self.classifier = classifier self.stats = stats",
"_ = self.net(input) loss = self.error(output, target) if self.stats is",
"loss = self.error(output, target) if self.stats is not None: self.stats.validation.num_samples",
"output.shape[0] if self.classifier is not None: # classification self.stats.validation.correct_samples +=",
"p in self.net.parameters(): self.device = p.device break device = self.device",
"lambda an error object or a lambda function that evaluates",
"in self.net.parameters(): self.device = p.device break device = self.device input",
"error : object or lambda an error object or a",
"\"\"\"Reduces the learning rate of the optimizer by ``factor``. Parameters",
"lagrangian to merge network layer based loss. None means no",
"None: # classification self.stats.training.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item()",
"None: output, count = self.net(input) else: output, net_loss, count =",
"or None the main device memory where network is placed.",
"None: return output return output, count def test(self, input, target):",
"not None: # classification self.stats.training.correct_samples += torch.sum( self.classifier(output) == target",
"self.stats = stats self.count_log = count_log self.lam = lam self.device",
"is not None: # classification self.stats.validation.correct_samples += torch.sum( self.classifier(output) ==",
"\"\"\" self.net.eval() with torch.no_grad(): device = self.net.device input = input.to(device)",
"rate reduction factor. Defaults to 10/3. Returns ------- \"\"\" for",
"count = self.net(input) else: output, _, count = self.net(input) else:",
"enable count log. Defaults to False. lam : float lagrangian",
"torch optimizer the learning optimizer. stats : slayer.utils.stats learning stats",
"= self.net(input) else: if self.lam is None: output = self.net(input)",
"slayer.classifier or lambda classifier object or lambda function that takes",
"is expected to take ``(output, target)`` | ``(output, label)`` as",
"device = self.device with torch.no_grad(): input = input.to(device) target =",
"None: return output return output, count def valid(self, input, target):",
"net is expected to return the accumulated loss as second",
"self.device with torch.no_grad(): input = input.to(device) target = target.to(device) count",
"= lam self.device = None def reduce_lr(self, factor=10 / 3):",
"None: self.stats.training.num_samples += input.shape[0] self.stats.training.loss_sum += loss.cpu().data.item() \\ * output.shape[0]",
"if self.lam is None: self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0]",
"\"\"\"Validation assistant. Parameters ---------- input : torch tensor input tensor.",
"slayer.utils.stats learning stats logger. If None, stats will not be",
"is not None: # classification self.stats.training.correct_samples += torch.sum( self.classifier(output) ==",
"steps are bypassed. Defaults to None. count_log : bool flag",
"None: self.stats.testing.num_samples += input.shape[0] self.stats.testing.loss_sum += loss.cpu().data.item() \\ * output.shape[0]",
"output return output, count def test(self, input, target): \"\"\"Testing assistant.",
"not at start and gets initialized on the first call.",
"self.lam is None: output = self.net(input) else: output, net_loss =",
"argument. It is intended to be used with layer wise",
"self.stats.testing.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if self.classifier is not",
"flag to enable count log. Defaults to False. lam :",
"rate of the optimizer by ``factor``. Parameters ---------- factor :",
"net_loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() if count is None: return output",
").cpu().data.item() if count is None: return output return output, count",
"from', param_group['lr']) param_group['lr'] /= factor def train(self, input, target): \"\"\"Training",
"``count_log`` is enabled \"\"\" self.net.eval() if self.device is None: for",
"= error self.optimizer = optimizer self.classifier = classifier self.stats =",
"= self.error(output, target) if self.stats is not None: self.stats.testing.num_samples +=",
"if self.lam is None: output = self.net(input) else: output, net_loss",
"is not None: self.stats.testing.num_samples += input.shape[0] self.stats.testing.loss_sum += loss.cpu().data.item() \\",
"optimizer. stats : slayer.utils.stats learning stats logger. If None, stats",
"target = target.to(device) count = None if self.count_log is True:",
"network prediction. None means regression mode. Classification steps are bypassed.",
"output, _ = self.net(input) loss = self.error(output, target) if self.stats",
"self.stats.validation.num_samples += input.shape[0] if self.lam is None: self.stats.validation.loss_sum += loss.cpu().data.item()",
"that bundles training, validation and testing workflow. Parameters ---------- net",
"is None: output, count = self.net(input) else: output, net_loss, count",
"object or lambda function that takes output and returns the",
"self.stats.training.num_samples += input.shape[0] self.stats.training.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if",
"torch tensor ground truth or label. Returns ------- output network's",
"= self.device with torch.no_grad(): input = input.to(device) target = target.to(device)",
"= self.net.device input = input.to(device) target = target.to(device) count =",
"None. classifier : slayer.classifier or lambda classifier object or lambda",
"be used with layer wise sparsity loss. Defaults to None.",
"an error object or a lambda function that evaluates error.",
": torch tensor ground truth or label. Returns ------- output",
"``count_log`` is enabled \"\"\" self.net.train() if self.device is None: for",
"net_loss, count = self.net(input) else: if self.lam is None: output",
"self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if self.classifier is not",
"output network's output. count : optional spike count if ``count_log``",
"network from network description.\"\"\" import torch class Assistant: \"\"\"Assistant that",
"is None: output = self.net(input) else: output, net_loss = self.net(input)",
"torch.no_grad(): device = self.net.device input = input.to(device) target = target.to(device)",
"net self.error = error self.optimizer = optimizer self.classifier = classifier",
"to None. count_log : bool flag to enable count log.",
"lam self.device = None def reduce_lr(self, factor=10 / 3): \"\"\"Reduces",
"self.net(input) else: output, net_loss, count = self.net(input) else: if self.lam",
"step loss += self.lam * net_loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() if",
"self.lam is None: output = self.net(input) else: output, _ =",
"else: output, net_loss, count = self.net(input) else: if self.lam is",
"for param_group in self.optimizer.param_groups: print('\\nLearning rate reduction from', param_group['lr']) param_group['lr']",
"at start and gets initialized on the first call. \"\"\"",
"output and returns the network prediction. None means regression mode.",
"self.stats.testing.num_samples += input.shape[0] self.stats.testing.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if",
"---------- net error optimizer stats classifier count_log lam device :",
"the optimizer by ``factor``. Parameters ---------- factor : float learning",
"with torch.no_grad(): input = input.to(device) target = target.to(device) count =",
"return output, count def test(self, input, target): \"\"\"Testing assistant. Parameters",
"# add net_loss before backward step loss += self.lam *",
"input tensor. target : torch tensor ground truth or label.",
"if self.classifier is not None: # classification self.stats.validation.correct_samples += torch.sum(",
"torch tensor input tensor. target : torch tensor ground truth",
"add net_loss before backward step loss += self.lam * net_loss",
"target) if self.stats is not None: self.stats.validation.num_samples += input.shape[0] if",
"to return the accumulated loss as second argument. It is",
"_, count = self.net(input) else: if self.lam is None: output",
"count is None: return output return output, count def valid(self,",
"Defaults to 10/3. Returns ------- \"\"\" for param_group in self.optimizer.param_groups:",
"Defaults to None. classifier : slayer.classifier or lambda classifier object",
"if ``count_log`` is enabled \"\"\" self.net.eval() if self.device is None:",
"if self.device is None: for p in self.net.parameters(): self.device =",
"count if ``count_log`` is enabled \"\"\" self.net.train() if self.device is",
"classification self.stats.training.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item() if self.lam",
"as it's argument and return a scalar value. optimizer :",
"in self.optimizer.param_groups: print('\\nLearning rate reduction from', param_group['lr']) param_group['lr'] /= factor",
"output.shape[0] if self.classifier is not None: # classification self.stats.training.correct_samples +=",
"self.optimizer = optimizer self.classifier = classifier self.stats = stats self.count_log",
"evaluates error. It is expected to take ``(output, target)`` |",
"to 10/3. Returns ------- \"\"\" for param_group in self.optimizer.param_groups: print('\\nLearning",
"``(output, label)`` as it's argument and return a scalar value.",
"backward step loss += self.lam * net_loss self.optimizer.zero_grad() loss.backward() self.optimizer.step()",
"spike count if ``count_log`` is enabled \"\"\" self.net.eval() with torch.no_grad():",
"``(output, target)`` | ``(output, label)`` as it's argument and return",
"bypassed. Defaults to None. count_log : bool flag to enable",
"optional spike count if ``count_log`` is enabled \"\"\" self.net.train() if",
"input = input.to(device) target = target.to(device) count = None if",
"is True: if self.lam is None: output, count = self.net(input)",
"+= loss.cpu().data.item() \\ * output.shape[0] if self.classifier is not None:",
"used with layer wise sparsity loss. Defaults to None. Attributes",
"(C) 2022 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause \"\"\"Assistant utility for",
"class Assistant: \"\"\"Assistant that bundles training, validation and testing workflow.",
"Parameters ---------- factor : float learning rate reduction factor. Defaults",
"optimizer stats classifier count_log lam device : torch.device or None",
": bool flag to enable count log. Defaults to False.",
"= self.device input = input.to(device) target = target.to(device) count =",
"log. Defaults to False. lam : float lagrangian to merge",
"None. Attributes ---------- net error optimizer stats classifier count_log lam",
"in self.net.parameters(): self.device = p.device break device = self.device with",
"self.net(input) loss = self.error(output, target) if self.stats is not None:",
"= count_log self.lam = lam self.device = None def reduce_lr(self,",
"and gets initialized on the first call. \"\"\" def __init__(",
"merge network layer based loss. None means no such additional",
"== target ).cpu().data.item() if self.lam is not None: # add",
"the network prediction. None means regression mode. Classification steps are",
"reduce_lr(self, factor=10 / 3): \"\"\"Reduces the learning rate of the",
"loss.backward() self.optimizer.step() if count is None: return output return output,",
"test(self, input, target): \"\"\"Testing assistant. Parameters ---------- input : torch",
"---------- factor : float learning rate reduction factor. Defaults to",
"if count is None: return output return output, count def",
"not None, net is expected to return the accumulated loss",
"optimizer the learning optimizer. stats : slayer.utils.stats learning stats logger.",
"function that evaluates error. It is expected to take ``(output,",
"first call. \"\"\" def __init__( self, net, error, optimizer, stats=None,",
"lam=None ): self.net = net self.error = error self.optimizer =",
"self.lam = lam self.device = None def reduce_lr(self, factor=10 /",
"stats : slayer.utils.stats learning stats logger. If None, stats will",
"self.lam * net_loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() if count is None:",
"classifier : slayer.classifier or lambda classifier object or lambda function",
"def train(self, input, target): \"\"\"Training assistant. Parameters ---------- input :",
"input.shape[0] self.stats.training.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if self.classifier is",
"self.net(input) else: if self.lam is None: output = self.net(input) else:",
"\"\"\"Assistant that bundles training, validation and testing workflow. Parameters ----------",
"not be logged. Defaults to None. classifier : slayer.classifier or",
"None: output = self.net(input) else: output, net_loss = self.net(input) loss",
"Classification steps are bypassed. Defaults to None. count_log : bool",
"Defaults to None. Attributes ---------- net error optimizer stats classifier",
"takes output and returns the network prediction. None means regression",
"from network description.\"\"\" import torch class Assistant: \"\"\"Assistant that bundles",
"or lambda function that takes output and returns the network",
"# SPDX-License-Identifier: BSD-3-Clause \"\"\"Assistant utility for automatically load network from",
"* net_loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() if count is None: return",
"object or a lambda function that evaluates error. It is",
"by ``factor``. Parameters ---------- factor : float learning rate reduction",
"label)`` as it's argument and return a scalar value. optimizer",
"output, count def test(self, input, target): \"\"\"Testing assistant. Parameters ----------",
"stats=None, classifier=None, count_log=False, lam=None ): self.net = net self.error =",
"self.classifier is not None: # classification self.stats.testing.correct_samples += torch.sum( self.classifier(output)",
"self.error(output, target) if self.stats is not None: self.stats.training.num_samples += input.shape[0]",
"is enabled \"\"\" self.net.eval() if self.device is None: for p",
"is not None: self.stats.training.num_samples += input.shape[0] self.stats.training.loss_sum += loss.cpu().data.item() \\",
"output = self.net(input) else: output, net_loss = self.net(input) loss =",
"tensor input tensor. target : torch tensor ground truth or",
"``count_log`` is enabled \"\"\" self.net.eval() with torch.no_grad(): device = self.net.device",
"returns the network prediction. None means regression mode. Classification steps",
"return the accumulated loss as second argument. It is intended",
"import torch class Assistant: \"\"\"Assistant that bundles training, validation and",
"are bypassed. Defaults to None. count_log : bool flag to",
"description.\"\"\" import torch class Assistant: \"\"\"Assistant that bundles training, validation",
"target : torch tensor ground truth or label. Returns -------",
"None means regression mode. Classification steps are bypassed. Defaults to",
": slayer.utils.stats learning stats logger. If None, stats will not",
"to merge network layer based loss. None means no such",
"memory where network is placed. It is not at start",
"if self.stats is not None: self.stats.testing.num_samples += input.shape[0] self.stats.testing.loss_sum +=",
"output, net_loss, count = self.net(input) else: if self.lam is None:",
"break device = self.device with torch.no_grad(): input = input.to(device) target",
"return output, count def valid(self, input, target): \"\"\"Validation assistant. Parameters",
": torch.nn.Module network to train. error : object or lambda",
"that evaluates error. It is expected to take ``(output, target)``",
"logged. Defaults to None. classifier : slayer.classifier or lambda classifier",
"such additional loss. If not None, net is expected to",
"optimizer : torch optimizer the learning optimizer. stats : slayer.utils.stats",
"if self.lam is None: output, count = self.net(input) else: output,",
"+= input.shape[0] self.stats.training.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if self.classifier",
"self.stats is not None: self.stats.validation.num_samples += input.shape[0] if self.lam is",
"Parameters ---------- input : torch tensor input tensor. target :",
"additional loss. If not None, net is expected to return",
"self.lam is None: output, count = self.net(input) else: output, _,",
"utility for automatically load network from network description.\"\"\" import torch",
"is not at start and gets initialized on the first",
"target ).cpu().data.item() if count is None: return output return output,",
"---------- input : torch tensor input tensor. target : torch",
"self.net(input) else: output, _, count = self.net(input) else: if self.lam",
"Returns ------- \"\"\" for param_group in self.optimizer.param_groups: print('\\nLearning rate reduction",
"optimizer by ``factor``. Parameters ---------- factor : float learning rate",
"input.shape[0] if self.lam is None: self.stats.validation.loss_sum += loss.cpu().data.item() \\ *",
"call. \"\"\" def __init__( self, net, error, optimizer, stats=None, classifier=None,",
"False. lam : float lagrangian to merge network layer based",
"object or lambda an error object or a lambda function",
"count = None if self.count_log is True: if self.lam is",
"= self.net(input) else: output, net_loss, count = self.net(input) else: if",
"\\ * output.shape[0] if self.classifier is not None: # classification",
"as second argument. It is intended to be used with",
"self.optimizer.zero_grad() loss.backward() self.optimizer.step() if count is None: return output return",
"* output.shape[0] if self.classifier is not None: # classification self.stats.validation.correct_samples",
"None means no such additional loss. If not None, net",
"| ``(output, label)`` as it's argument and return a scalar",
"stats logger. If None, stats will not be logged. Defaults",
"is not None: # add net_loss before backward step loss",
": float lagrangian to merge network layer based loss. None",
"if self.lam is not None: # add net_loss before backward",
": optional spike count if ``count_log`` is enabled \"\"\" self.net.train()",
"output, count = self.net(input) else: output, net_loss, count = self.net(input)",
"output.shape[0] if self.classifier is not None: # classification self.stats.testing.correct_samples +=",
"torch.sum( self.classifier(output) == target ).cpu().data.item() if self.lam is not None:",
"or label. Returns ------- output network's output. count : optional",
"is not None: # classification self.stats.testing.correct_samples += torch.sum( self.classifier(output) ==",
"network to train. error : object or lambda an error",
"mode. Classification steps are bypassed. Defaults to None. count_log :",
"is placed. It is not at start and gets initialized",
"torch.sum( self.classifier(output) == target ).cpu().data.item() if count is None: return",
"net : torch.nn.Module network to train. error : object or",
"None: output = self.net(input) else: output, _ = self.net(input) loss",
"param_group in self.optimizer.param_groups: print('\\nLearning rate reduction from', param_group['lr']) param_group['lr'] /=",
"self.net.train() if self.device is None: for p in self.net.parameters(): self.device",
"self.device = p.device break device = self.device input = input.to(device)",
"not None: self.stats.testing.num_samples += input.shape[0] self.stats.testing.loss_sum += loss.cpu().data.item() \\ *",
"factor : float learning rate reduction factor. Defaults to 10/3.",
"Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause \"\"\"Assistant utility",
"+= torch.sum( self.classifier(output) == target ).cpu().data.item() if self.lam is not",
"output, count def valid(self, input, target): \"\"\"Validation assistant. Parameters ----------",
"means no such additional loss. If not None, net is",
"placed. It is not at start and gets initialized on",
"enabled \"\"\" self.net.eval() if self.device is None: for p in",
"lambda function that takes output and returns the network prediction.",
"error object or a lambda function that evaluates error. It",
"None: output, count = self.net(input) else: output, _, count =",
"# classification self.stats.validation.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item() if",
"self.classifier is not None: # classification self.stats.training.correct_samples += torch.sum( self.classifier(output)",
"if self.classifier is not None: # classification self.stats.testing.correct_samples += torch.sum(",
"self.count_log = count_log self.lam = lam self.device = None def",
"SPDX-License-Identifier: BSD-3-Clause \"\"\"Assistant utility for automatically load network from network",
"and return a scalar value. optimizer : torch optimizer the",
"print('\\nLearning rate reduction from', param_group['lr']) param_group['lr'] /= factor def train(self,",
"target.to(device) count = None if self.count_log is True: if self.lam",
"loss as second argument. It is intended to be used",
"second argument. It is intended to be used with layer",
"else: output, _, count = self.net(input) else: if self.lam is",
"output, net_loss = self.net(input) loss = self.error(output, target) if self.stats",
"= input.to(device) target = target.to(device) count = None if self.count_log",
"if self.lam is None: output = self.net(input) else: output, _",
"True: if self.lam is None: output, count = self.net(input) else:",
"argument and return a scalar value. optimizer : torch optimizer",
"3): \"\"\"Reduces the learning rate of the optimizer by ``factor``.",
"testing workflow. Parameters ---------- net : torch.nn.Module network to train.",
"= self.net(input) else: output, _, count = self.net(input) else: if",
"None: # classification self.stats.validation.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item()",
"= None if self.count_log is True: if self.lam is None:",
"classification self.stats.validation.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item() if count",
"error optimizer stats classifier count_log lam device : torch.device or",
"= classifier self.stats = stats self.count_log = count_log self.lam =",
"be logged. Defaults to None. classifier : slayer.classifier or lambda",
"/ 3): \"\"\"Reduces the learning rate of the optimizer by",
"loss = self.error(output, target) if self.stats is not None: self.stats.training.num_samples",
"self.stats is not None: self.stats.testing.num_samples += input.shape[0] self.stats.testing.loss_sum += loss.cpu().data.item()",
"None, net is expected to return the accumulated loss as",
"optional spike count if ``count_log`` is enabled \"\"\" self.net.eval() with",
"\"\"\" for param_group in self.optimizer.param_groups: print('\\nLearning rate reduction from', param_group['lr'])",
"self.net.eval() if self.device is None: for p in self.net.parameters(): self.device",
"None, stats will not be logged. Defaults to None. classifier",
"is expected to return the accumulated loss as second argument.",
"is None: return output return output, count def valid(self, input,",
"None: # add net_loss before backward step loss += self.lam",
"automatically load network from network description.\"\"\" import torch class Assistant:",
"Corporation # SPDX-License-Identifier: BSD-3-Clause \"\"\"Assistant utility for automatically load network",
"\"\"\" self.net.train() if self.device is None: for p in self.net.parameters():",
"self.classifier is not None: # classification self.stats.validation.correct_samples += torch.sum( self.classifier(output)",
"train(self, input, target): \"\"\"Training assistant. Parameters ---------- input : torch",
"self.stats.training.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if self.classifier is not",
"if self.classifier is not None: # classification self.stats.training.correct_samples += torch.sum(",
"the learning optimizer. stats : slayer.utils.stats learning stats logger. If",
"None: self.stats.validation.num_samples += input.shape[0] if self.lam is None: self.stats.validation.loss_sum +=",
"the main device memory where network is placed. It is",
"value. optimizer : torch optimizer the learning optimizer. stats :",
"is intended to be used with layer wise sparsity loss.",
"count_log self.lam = lam self.device = None def reduce_lr(self, factor=10",
"It is intended to be used with layer wise sparsity",
"def valid(self, input, target): \"\"\"Validation assistant. Parameters ---------- input :",
"the first call. \"\"\" def __init__( self, net, error, optimizer,",
"is enabled \"\"\" self.net.train() if self.device is None: for p",
"enabled \"\"\" self.net.train() if self.device is None: for p in",
"if self.stats is not None: self.stats.validation.num_samples += input.shape[0] if self.lam",
"intended to be used with layer wise sparsity loss. Defaults",
"self.net.parameters(): self.device = p.device break device = self.device input =",
"count def valid(self, input, target): \"\"\"Validation assistant. Parameters ---------- input",
": torch tensor input tensor. target : torch tensor ground",
"is None: output = self.net(input) else: output, _ = self.net(input)",
"reduction factor. Defaults to 10/3. Returns ------- \"\"\" for param_group",
"= net self.error = error self.optimizer = optimizer self.classifier =",
"None. count_log : bool flag to enable count log. Defaults",
"device : torch.device or None the main device memory where",
"self.classifier(output) == target ).cpu().data.item() if self.lam is not None: #",
"assistant. Parameters ---------- input : torch tensor input tensor. target",
"\"\"\" self.net.eval() if self.device is None: for p in self.net.parameters():",
"to train. error : object or lambda an error object",
"a scalar value. optimizer : torch optimizer the learning optimizer.",
"\"\"\"Training assistant. Parameters ---------- input : torch tensor input tensor.",
"lam device : torch.device or None the main device memory",
"* output.shape[0] if self.classifier is not None: # classification self.stats.training.correct_samples",
"error. It is expected to take ``(output, target)`` | ``(output,",
"net_loss = self.net(input) loss = self.error(output, target) if self.stats is",
"def __init__( self, net, error, optimizer, stats=None, classifier=None, count_log=False, lam=None",
"count = self.net(input) else: output, net_loss, count = self.net(input) else:",
"self.error = error self.optimizer = optimizer self.classifier = classifier self.stats",
"or lambda an error object or a lambda function that",
"torch.nn.Module network to train. error : object or lambda an",
"target)`` | ``(output, label)`` as it's argument and return a",
"BSD-3-Clause \"\"\"Assistant utility for automatically load network from network description.\"\"\"",
"loss = self.error(output, target) if self.stats is not None: self.stats.testing.num_samples",
"optimizer, stats=None, classifier=None, count_log=False, lam=None ): self.net = net self.error",
"on the first call. \"\"\" def __init__( self, net, error,",
"/= factor def train(self, input, target): \"\"\"Training assistant. Parameters ----------",
"\"\"\"Testing assistant. Parameters ---------- input : torch tensor input tensor.",
"no such additional loss. If not None, net is expected",
"prediction. None means regression mode. Classification steps are bypassed. Defaults",
"tensor ground truth or label. Returns ------- output network's output.",
"* output.shape[0] else: self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if",
"take ``(output, target)`` | ``(output, label)`` as it's argument and",
"lambda function that evaluates error. It is expected to take",
"spike count if ``count_log`` is enabled \"\"\" self.net.eval() if self.device",
"to be used with layer wise sparsity loss. Defaults to",
"param_group['lr'] /= factor def train(self, input, target): \"\"\"Training assistant. Parameters",
"output = self.net(input) else: output, _ = self.net(input) loss =",
"Intel Corporation # SPDX-License-Identifier: BSD-3-Clause \"\"\"Assistant utility for automatically load",
"loss += self.lam * net_loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() if count",
"truth or label. Returns ------- output network's output. count :",
"count if ``count_log`` is enabled \"\"\" self.net.eval() if self.device is",
"loss.cpu().data.item() \\ * output.shape[0] else: self.stats.validation.loss_sum += loss.cpu().data.item() \\ *",
"and returns the network prediction. None means regression mode. Classification",
"and testing workflow. Parameters ---------- net : torch.nn.Module network to",
"stats will not be logged. Defaults to None. classifier :",
"Parameters ---------- net : torch.nn.Module network to train. error :",
"to None. classifier : slayer.classifier or lambda classifier object or",
"of the optimizer by ``factor``. Parameters ---------- factor : float",
"Returns ------- output network's output. count : optional spike count",
"loss.cpu().data.item() \\ * output.shape[0] if self.classifier is not None: #",
"network description.\"\"\" import torch class Assistant: \"\"\"Assistant that bundles training,",
"classification self.stats.testing.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item() if count",
"is not None: self.stats.validation.num_samples += input.shape[0] if self.lam is None:",
"``factor``. Parameters ---------- factor : float learning rate reduction factor.",
"regression mode. Classification steps are bypassed. Defaults to None. count_log",
"device = self.net.device input = input.to(device) target = target.to(device) count",
"target): \"\"\"Validation assistant. Parameters ---------- input : torch tensor input",
"not None: self.stats.validation.num_samples += input.shape[0] if self.lam is None: self.stats.validation.loss_sum",
"target): \"\"\"Training assistant. Parameters ---------- input : torch tensor input",
"output, count = self.net(input) else: output, _, count = self.net(input)",
"bool flag to enable count log. Defaults to False. lam",
"== target ).cpu().data.item() if count is None: return output return",
"input, target): \"\"\"Validation assistant. Parameters ---------- input : torch tensor",
"a lambda function that evaluates error. It is expected to",
"p.device break device = self.device input = input.to(device) target =",
"input, target): \"\"\"Testing assistant. Parameters ---------- input : torch tensor",
"input.shape[0] self.stats.testing.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if self.classifier is",
"device = self.device input = input.to(device) target = target.to(device) count",
"def test(self, input, target): \"\"\"Testing assistant. Parameters ---------- input :",
"if ``count_log`` is enabled \"\"\" self.net.eval() with torch.no_grad(): device =",
"target): \"\"\"Testing assistant. Parameters ---------- input : torch tensor input",
"self.device = None def reduce_lr(self, factor=10 / 3): \"\"\"Reduces the",
"classifier=None, count_log=False, lam=None ): self.net = net self.error = error",
"for p in self.net.parameters(): self.device = p.device break device =",
"None if self.count_log is True: if self.lam is None: output,",
"self.lam is None: self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0] else:",
": torch optimizer the learning optimizer. stats : slayer.utils.stats learning",
"will not be logged. Defaults to None. classifier : slayer.classifier",
"learning optimizer. stats : slayer.utils.stats learning stats logger. If None,",
"self, net, error, optimizer, stats=None, classifier=None, count_log=False, lam=None ): self.net",
"not None: self.stats.training.num_samples += input.shape[0] self.stats.training.loss_sum += loss.cpu().data.item() \\ *",
"for automatically load network from network description.\"\"\" import torch class",
"if ``count_log`` is enabled \"\"\" self.net.train() if self.device is None:",
"start and gets initialized on the first call. \"\"\" def",
"self.net.eval() with torch.no_grad(): device = self.net.device input = input.to(device) target",
"network's output. count : optional spike count if ``count_log`` is",
"train. error : object or lambda an error object or",
"count def test(self, input, target): \"\"\"Testing assistant. Parameters ---------- input",
"= target.to(device) count = None if self.count_log is True: if",
": torch.device or None the main device memory where network",
": slayer.classifier or lambda classifier object or lambda function that",
"\\ * output.shape[0] else: self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0]",
"bundles training, validation and testing workflow. Parameters ---------- net :",
"that takes output and returns the network prediction. None means",
"input : torch tensor input tensor. target : torch tensor",
"self.net.parameters(): self.device = p.device break device = self.device with torch.no_grad():",
"self.net(input) else: output, net_loss = self.net(input) loss = self.error(output, target)",
"self.stats.validation.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item() if count is",
"def reduce_lr(self, factor=10 / 3): \"\"\"Reduces the learning rate of",
"if self.count_log is True: if self.lam is None: output, count",
"optional spike count if ``count_log`` is enabled \"\"\" self.net.eval() if",
"None: self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0] else: self.stats.validation.loss_sum +=",
"means regression mode. Classification steps are bypassed. Defaults to None.",
"* output.shape[0] if self.classifier is not None: # classification self.stats.testing.correct_samples",
"count_log=False, lam=None ): self.net = net self.error = error self.optimizer",
"None: for p in self.net.parameters(): self.device = p.device break device",
"self.optimizer.step() if count is None: return output return output, count",
"the learning rate of the optimizer by ``factor``. Parameters ----------",
"else: output, net_loss = self.net(input) loss = self.error(output, target) if",
"= self.net(input) else: output, _ = self.net(input) loss = self.error(output,",
"loss. None means no such additional loss. If not None,",
"before backward step loss += self.lam * net_loss self.optimizer.zero_grad() loss.backward()",
"classifier count_log lam device : torch.device or None the main",
"target) if self.stats is not None: self.stats.testing.num_samples += input.shape[0] self.stats.testing.loss_sum",
"where network is placed. It is not at start and",
"+= torch.sum( self.classifier(output) == target ).cpu().data.item() if count is None:",
"target ).cpu().data.item() if self.lam is not None: # add net_loss",
"network layer based loss. None means no such additional loss.",
"output, _, count = self.net(input) else: if self.lam is None:",
"+= input.shape[0] self.stats.testing.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if self.classifier",
"Attributes ---------- net error optimizer stats classifier count_log lam device",
"It is not at start and gets initialized on the",
"= self.error(output, target) if self.stats is not None: self.stats.validation.num_samples +=",
"based loss. None means no such additional loss. If not",
"None def reduce_lr(self, factor=10 / 3): \"\"\"Reduces the learning rate",
"learning rate reduction factor. Defaults to 10/3. Returns ------- \"\"\"",
"Assistant: \"\"\"Assistant that bundles training, validation and testing workflow. Parameters",
"+= self.lam * net_loss self.optimizer.zero_grad() loss.backward() self.optimizer.step() if count is",
"self.count_log is True: if self.lam is None: output, count =",
"count if ``count_log`` is enabled \"\"\" self.net.eval() with torch.no_grad(): device",
"return output return output, count def valid(self, input, target): \"\"\"Validation",
"): self.net = net self.error = error self.optimizer = optimizer",
"optimizer self.classifier = classifier self.stats = stats self.count_log = count_log",
"input, target): \"\"\"Training assistant. Parameters ---------- input : torch tensor",
"Defaults to None. count_log : bool flag to enable count",
"is None: for p in self.net.parameters(): self.device = p.device break",
"count log. Defaults to False. lam : float lagrangian to",
"p.device break device = self.device with torch.no_grad(): input = input.to(device)",
"It is expected to take ``(output, target)`` | ``(output, label)``",
"self.classifier = classifier self.stats = stats self.count_log = count_log self.lam",
"validation and testing workflow. Parameters ---------- net : torch.nn.Module network",
"wise sparsity loss. Defaults to None. Attributes ---------- net error",
"torch.no_grad(): input = input.to(device) target = target.to(device) count = None",
"self.lam is None: output, count = self.net(input) else: output, net_loss,",
"is None: return output return output, count def test(self, input,",
"self.classifier(output) == target ).cpu().data.item() if count is None: return output",
"------- output network's output. count : optional spike count if",
"loss. Defaults to None. Attributes ---------- net error optimizer stats",
"accumulated loss as second argument. It is intended to be",
"= p.device break device = self.device with torch.no_grad(): input =",
"load network from network description.\"\"\" import torch class Assistant: \"\"\"Assistant",
"network is placed. It is not at start and gets",
"------- \"\"\" for param_group in self.optimizer.param_groups: print('\\nLearning rate reduction from',",
"count : optional spike count if ``count_log`` is enabled \"\"\"",
"to None. Attributes ---------- net error optimizer stats classifier count_log",
"self.stats is not None: self.stats.training.num_samples += input.shape[0] self.stats.training.loss_sum += loss.cpu().data.item()",
"is enabled \"\"\" self.net.eval() with torch.no_grad(): device = self.net.device input",
"tensor. target : torch tensor ground truth or label. Returns",
"+= loss.cpu().data.item() \\ * output.shape[0] else: self.stats.validation.loss_sum += loss.cpu().data.item() \\",
"torch.device or None the main device memory where network is",
"float learning rate reduction factor. Defaults to 10/3. Returns -------",
"= self.net(input) else: output, net_loss = self.net(input) loss = self.error(output,",
"loss. If not None, net is expected to return the",
"= stats self.count_log = count_log self.lam = lam self.device =",
"expected to take ``(output, target)`` | ``(output, label)`` as it's",
"Defaults to False. lam : float lagrangian to merge network",
"10/3. Returns ------- \"\"\" for param_group in self.optimizer.param_groups: print('\\nLearning rate",
"main device memory where network is placed. It is not",
"= optimizer self.classifier = classifier self.stats = stats self.count_log =",
"self.device = p.device break device = self.device with torch.no_grad(): input",
"not None: # add net_loss before backward step loss +=",
"to False. lam : float lagrangian to merge network layer",
"self.net(input) else: output, _ = self.net(input) loss = self.error(output, target)",
"float lagrangian to merge network layer based loss. None means",
"= self.net(input) loss = self.error(output, target) if self.stats is not",
"output. count : optional spike count if ``count_log`` is enabled",
"# classification self.stats.testing.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item() if",
"None the main device memory where network is placed. It",
"lambda classifier object or lambda function that takes output and",
"self.error(output, target) if self.stats is not None: self.stats.testing.num_samples += input.shape[0]",
").cpu().data.item() if self.lam is not None: # add net_loss before",
"self.stats.testing.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item() if count is",
"\"\"\" def __init__( self, net, error, optimizer, stats=None, classifier=None, count_log=False,",
"self.stats.training.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item() if self.lam is",
"else: if self.lam is None: output = self.net(input) else: output,",
"2022 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause \"\"\"Assistant utility for automatically",
"initialized on the first call. \"\"\" def __init__( self, net,",
"learning stats logger. If None, stats will not be logged.",
"the accumulated loss as second argument. It is intended to",
"it's argument and return a scalar value. optimizer : torch",
"count = self.net(input) else: if self.lam is None: output =",
"lam : float lagrangian to merge network layer based loss.",
"classifier object or lambda function that takes output and returns",
"return output return output, count def test(self, input, target): \"\"\"Testing",
"self.lam is not None: # add net_loss before backward step",
"to enable count log. Defaults to False. lam : float",
"scalar value. optimizer : torch optimizer the learning optimizer. stats",
"factor=10 / 3): \"\"\"Reduces the learning rate of the optimizer",
"classifier self.stats = stats self.count_log = count_log self.lam = lam",
"input.to(device) target = target.to(device) count = None if self.count_log is",
"not None: # classification self.stats.testing.correct_samples += torch.sum( self.classifier(output) == target",
"count is None: return output return output, count def test(self,",
"error, optimizer, stats=None, classifier=None, count_log=False, lam=None ): self.net = net",
"label. Returns ------- output network's output. count : optional spike",
"to take ``(output, target)`` | ``(output, label)`` as it's argument",
"count_log : bool flag to enable count log. Defaults to",
"layer wise sparsity loss. Defaults to None. Attributes ---------- net",
"net_loss before backward step loss += self.lam * net_loss self.optimizer.zero_grad()",
": float learning rate reduction factor. Defaults to 10/3. Returns",
"self.device is None: for p in self.net.parameters(): self.device = p.device",
"sparsity loss. Defaults to None. Attributes ---------- net error optimizer",
"is None: self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0] else: self.stats.validation.loss_sum",
"rate reduction from', param_group['lr']) param_group['lr'] /= factor def train(self, input,",
"else: self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if self.classifier is",
"\"\"\"Assistant utility for automatically load network from network description.\"\"\" import",
"logger. If None, stats will not be logged. Defaults to",
"self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0] else: self.stats.validation.loss_sum += loss.cpu().data.item()",
"count_log lam device : torch.device or None the main device",
"not None: # classification self.stats.validation.correct_samples += torch.sum( self.classifier(output) == target",
"break device = self.device input = input.to(device) target = target.to(device)",
"or lambda classifier object or lambda function that takes output",
"return a scalar value. optimizer : torch optimizer the learning",
"layer based loss. None means no such additional loss. If",
"stats classifier count_log lam device : torch.device or None the",
"self.error(output, target) if self.stats is not None: self.stats.validation.num_samples += input.shape[0]",
"or a lambda function that evaluates error. It is expected",
"self.net = net self.error = error self.optimizer = optimizer self.classifier",
"= None def reduce_lr(self, factor=10 / 3): \"\"\"Reduces the learning",
"If not None, net is expected to return the accumulated",
"If None, stats will not be logged. Defaults to None.",
"torch class Assistant: \"\"\"Assistant that bundles training, validation and testing",
"enabled \"\"\" self.net.eval() with torch.no_grad(): device = self.net.device input =",
"# Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause \"\"\"Assistant",
"net, error, optimizer, stats=None, classifier=None, count_log=False, lam=None ): self.net =",
"= p.device break device = self.device input = input.to(device) target",
"target) if self.stats is not None: self.stats.training.num_samples += input.shape[0] self.stats.training.loss_sum",
"with layer wise sparsity loss. Defaults to None. Attributes ----------",
"---------- net : torch.nn.Module network to train. error : object",
"= self.error(output, target) if self.stats is not None: self.stats.training.num_samples +=",
"function that takes output and returns the network prediction. None",
"factor def train(self, input, target): \"\"\"Training assistant. Parameters ---------- input",
"stats self.count_log = count_log self.lam = lam self.device = None",
"reduction from', param_group['lr']) param_group['lr'] /= factor def train(self, input, target):",
"is None: output, count = self.net(input) else: output, _, count",
"param_group['lr']) param_group['lr'] /= factor def train(self, input, target): \"\"\"Training assistant.",
"self.net.device input = input.to(device) target = target.to(device) count = None",
"workflow. Parameters ---------- net : torch.nn.Module network to train. error",
"device memory where network is placed. It is not at",
"gets initialized on the first call. \"\"\" def __init__( self,",
"self.device input = input.to(device) target = target.to(device) count = None",
"training, validation and testing workflow. Parameters ---------- net : torch.nn.Module",
"net error optimizer stats classifier count_log lam device : torch.device",
"None: # classification self.stats.testing.correct_samples += torch.sum( self.classifier(output) == target ).cpu().data.item()",
"with torch.no_grad(): device = self.net.device input = input.to(device) target =",
"output return output, count def valid(self, input, target): \"\"\"Validation assistant.",
"else: output, _ = self.net(input) loss = self.error(output, target) if",
"learning rate of the optimizer by ``factor``. Parameters ---------- factor",
"ground truth or label. Returns ------- output network's output. count",
"__init__( self, net, error, optimizer, stats=None, classifier=None, count_log=False, lam=None ):",
"if self.stats is not None: self.stats.training.num_samples += input.shape[0] self.stats.training.loss_sum +=",
"output.shape[0] else: self.stats.validation.loss_sum += loss.cpu().data.item() \\ * output.shape[0] if self.classifier",
": optional spike count if ``count_log`` is enabled \"\"\" self.net.eval()",
"valid(self, input, target): \"\"\"Validation assistant. Parameters ---------- input : torch",
"+= input.shape[0] if self.lam is None: self.stats.validation.loss_sum += loss.cpu().data.item() \\",
": object or lambda an error object or a lambda"
] |
[
"'b') plt.subplot(312) plt.title(\"Predicted Signal\") plt.plot(predicted[:len(y_test)], 'g') plt.subplot(313) plt.title(\"Squared Error\") mse",
"t_rider = arange(0.0, 0.5, 0.01) wave3 = sin(10 * pi",
"wave3 = sin(10 * pi * t_rider) print(\"wave3\", len(wave3)) insert",
"= [] for index in range(test_start, test_end - sequence_length): result.append(data[index:",
"\"Creating train data...\" result = [] for index in range(train_start,",
"y_test = data print '\\nData Loaded. Compiling...\\n' if model is",
"print(\"Reshaping predicted\") predicted = np.reshape(predicted, (predicted.size,)) except KeyboardInterrupt: print(\"prediction exception\")",
"index in range(test_start, test_end - sequence_length): result.append(data[index: index + sequence_length])",
"in range(test_start, test_end - sequence_length): result.append(data[index: index + sequence_length]) result",
"X_train, y_train, X_test, y_test = get_split_prep_data(0, 700, 500, 1000) else:",
"from keras.layers.recurrent import LSTM from keras.models import Sequential from numpy",
"2 * pi * t) noise = random.normal(0, 0.1, len(t))",
"0.5, 0.01) wave3 = sin(10 * pi * t_rider) print(\"wave3\",",
"predicted = model.predict(X_test) print(\"Reshaping predicted\") predicted = np.reshape(predicted, (predicted.size,)) except",
"= 1 batch_size = 50 def dropin(X, y): \"\"\" The",
"= data print '\\nData Loaded. Compiling...\\n' if model is None:",
"y_train, X_test, y_test = data print '\\nData Loaded. Compiling...\\n' if",
"str(e) print 'Training duration (s) : ', time.time() - global_start_time",
"# each sample randomly duplicated between 0 and 9 times,",
"+ wave3 return wave1 + wave2 def z_norm(result): result_mean =",
"import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models",
"Uses the TensorFlow backend The basic idea is to detect",
"next 300 samples (has anomaly) X_train, y_train, X_test, y_test =",
"print(\"prediction exception\") print 'Training duration (s) : ', time.time() -",
"import Sequential from numpy import arange, sin, pi, random np.random.seed(1234)",
"50] + wave3 return wave1 + wave2 def z_norm(result): result_mean",
"in range(0, np.random.random_integers(0, random_data_dup)): X_hat.append(X[i, :]) y_hat.append(y[i]) return np.asarray(X_hat), np.asarray(y_hat)",
"keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from",
"len(wave1)) wave2 = sin(2 * pi * t) print(\"wave2\", len(wave2))",
"detect anomalies in a time-series. \"\"\" import matplotlib.pyplot as plt",
"data...\" result = [] for index in range(train_start, train_end -",
"Compiling...\\n' if model is None: model = build_model() try: print(\"Training...\")",
"exception\") print str(e) print 'Training duration (s) : ', time.time()",
"= dropin(X_train, y_train) # test data print \"Creating test data...\"",
"plt.plot(predicted[:len(y_test)], 'g') plt.subplot(313) plt.title(\"Squared Error\") mse = ((y_test - predicted)",
"dropin(X_train, y_train) # test data print \"Creating test data...\" result",
"data print '\\nData Loaded. Compiling...\\n' if model is None: model",
"wave1[insert:insert + 50] + wave3 return wave1 + wave2 def",
"duplicated between 0 and 9 times, see dropin function epochs",
"result_mean def get_split_prep_data(train_start, train_end, test_start, test_end): data = gen_wave() print(\"Length",
"print \"Mean of train data : \", result_mean print \"Train",
"a few sine waves and some noise :return: the final",
"dropout, i.e. adding more samples. See Data Augmentation section at",
"y \"\"\" print(\"X shape:\", X.shape) print(\"y shape:\", y.shape) X_hat =",
"print(\"Shape X_train\", np.shape(X_train)) print(\"Shape X_test\", np.shape(X_test)) X_train = np.reshape(X_train, (X_train.shape[0],",
"is None: print 'Loading data... ' # train on first",
"X_hat = [] y_hat = [] for i in range(0,",
"= train[:, :-1] y_train = train[:, -1] X_train, y_train =",
"Test Signal w/Anomalies\") plt.plot(y_test[:len(y_test)], 'b') plt.subplot(312) plt.title(\"Predicted Signal\") plt.plot(predicted[:len(y_test)], 'g')",
"plt.subplot(313) plt.title(\"Squared Error\") mse = ((y_test - predicted) ** 2)",
"def dropin(X, y): \"\"\" The name suggests the inverse of",
"= z_norm(result) print \"Mean of test data : \", result_mean",
"random np.random.seed(1234) # Global hyper-parameters sequence_length = 100 random_data_dup =",
"np.shape(X_test)) X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) X_test = np.reshape(X_test,",
"Data\", len(data)) # train data print \"Creating train data...\" result",
"of train data : \", result_mean print \"Train data shape",
"range(test_start, test_end - sequence_length): result.append(data[index: index + sequence_length]) result =",
"z_norm(result): result_mean = result.mean() result_std = result.std() result -= result_mean",
"* t) print(\"wave2\", len(wave2)) t_rider = arange(0.0, 0.5, 0.01) wave3",
"model def run_network(model=None, data=None): global_start_time = time.time() if data is",
"\"\"\" print(\"X shape:\", X.shape) print(\"y shape:\", y.shape) X_hat = []",
"in range(train_start, train_end - sequence_length): result.append(data[index: index + sequence_length]) result",
"of test data : \", result_mean print \"Test data shape",
"KeyboardInterrupt: print(\"prediction exception\") print 'Training duration (s) : ', time.time()",
"matplotlib.pyplot as plt import numpy as np import time from",
"sin(2 * 2 * pi * t) noise = random.normal(0,",
"100, 'output': 1} model.add(LSTM( input_length=sequence_length - 1, input_dim=layers['input'], output_dim=layers['hidden1'], return_sequences=True))",
"= 10 # each sample randomly duplicated between 0 and",
"in range(0, len(X)): for j in range(0, np.random.random_integers(0, random_data_dup)): X_hat.append(X[i,",
"sequence_length]) result = np.array(result) # shape (samples, sequence_length) result, result_mean",
"and test on next 300 samples (has anomaly) X_train, y_train,",
"model, y_test, 0 try: plt.figure(1) plt.subplot(311) plt.title(\"Actual Test Signal w/Anomalies\")",
"data=None): global_start_time = time.time() if data is None: print 'Loading",
"augmented X, y \"\"\" print(\"X shape:\", X.shape) print(\"y shape:\", y.shape)",
"np import time from keras.layers.core import Dense, Activation, Dropout from",
"print(\"Shape X_test\", np.shape(X_test)) X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) X_test",
"sequence_length): result.append(data[index: index + sequence_length]) result = np.array(result) # shape",
"w/Anomalies\") plt.plot(y_test[:len(y_test)], 'b') plt.subplot(312) plt.title(\"Predicted Signal\") plt.plot(predicted[:len(y_test)], 'g') plt.subplot(313) plt.title(\"Squared",
"will later predict :return: new augmented X, y \"\"\" print(\"X",
":-1] y_train = train[:, -1] X_train, y_train = dropin(X_train, y_train)",
"sequence_length) result, result_mean = z_norm(result) print \"Mean of test data",
"noise print(\"wave1\", len(wave1)) wave2 = sin(2 * pi * t)",
"\"\"\" The name suggests the inverse of dropout, i.e. adding",
":]) y_hat.append(y[i]) return np.asarray(X_hat), np.asarray(y_hat) def gen_wave(): \"\"\" Generate a",
"X_test, y_test = get_split_prep_data(0, 700, 500, 1000) else: X_train, y_train,",
"result[:, -1] print(\"Shape X_train\", np.shape(X_train)) print(\"Shape X_test\", np.shape(X_test)) X_train =",
": ', time.time() - global_start_time return model, y_test, 0 try:",
"print str(e) print 'Training duration (s) : ', time.time() -",
"(X_train.shape[0], X_train.shape[1], 1)) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) return",
"wave1 + noise print(\"wave1\", len(wave1)) wave2 = sin(2 * pi",
"http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param X: Each row is a training sequence :param",
"len(t)) wave1[insert:insert + 50] = wave1[insert:insert + 50] + wave3",
"\"Compilation Time : \", time.time() - start return model def",
"of dropout, i.e. adding more samples. See Data Augmentation section",
"/= result_std return result, result_mean def get_split_prep_data(train_start, train_end, test_start, test_end):",
"section at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param X: Each row is a training",
"50] = wave1[insert:insert + 50] + wave3 return wave1 +",
"exception\") print 'Training duration (s) : ', time.time() - global_start_time",
"wave2 = sin(2 * pi * t) print(\"wave2\", len(wave2)) t_rider",
"final wave \"\"\" t = np.arange(0.0, 10.0, 0.01) wave1 =",
"(s) : ', time.time() - global_start_time return model, y_test, 0",
"duration (s) : ', time.time() - global_start_time return model, y_test,",
"= time.time() model.compile(loss=\"mse\", optimizer=\"rmsprop\") print \"Compilation Time : \", time.time()",
"numpy import arange, sin, pi, random np.random.seed(1234) # Global hyper-parameters",
"predicted\") predicted = np.reshape(predicted, (predicted.size,)) except KeyboardInterrupt: print(\"prediction exception\") print",
"t_rider) print(\"wave3\", len(wave3)) insert = round(0.8 * len(t)) wave1[insert:insert +",
"time from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import",
"time.time() - start return model def run_network(model=None, data=None): global_start_time =",
"result_std = result.std() result -= result_mean result /= result_std return",
"= model.predict(X_test) print(\"Reshaping predicted\") predicted = np.reshape(predicted, (predicted.size,)) except KeyboardInterrupt:",
"X_train = train[:, :-1] y_train = train[:, -1] X_train, y_train",
"shape (samples, sequence_length) result, result_mean = z_norm(result) print \"Mean of",
"y_test = result[:, -1] print(\"Shape X_train\", np.shape(X_train)) print(\"Shape X_test\", np.shape(X_test))",
"return wave1 + wave2 def z_norm(result): result_mean = result.mean() result_std",
"data shape : \", result.shape train = result[train_start:train_end, :] np.random.shuffle(train)",
"model.add(Dropout(0.2)) model.add(Dense( output_dim=layers['output'])) model.add(Activation(\"linear\")) start = time.time() model.compile(loss=\"mse\", optimizer=\"rmsprop\") print",
"= wave1[insert:insert + 50] + wave3 return wave1 + wave2",
"function epochs = 1 batch_size = 50 def dropin(X, y):",
"test data...\" result = [] for index in range(test_start, test_end",
"\"\"\" t = np.arange(0.0, 10.0, 0.01) wave1 = sin(2 *",
"random_data_dup)): X_hat.append(X[i, :]) y_hat.append(y[i]) return np.asarray(X_hat), np.asarray(y_hat) def gen_wave(): \"\"\"",
"1)) return X_train, y_train, X_test, y_test def build_model(): model =",
":] np.random.shuffle(train) # shuffles in-place X_train = train[:, :-1] y_train",
"gen_wave(): \"\"\" Generate a synthetic wave by adding up a",
"model.add(Dense( output_dim=layers['output'])) model.add(Activation(\"linear\")) start = time.time() model.compile(loss=\"mse\", optimizer=\"rmsprop\") print \"Compilation",
"print(\"Predicting...\") predicted = model.predict(X_test) print(\"Reshaping predicted\") predicted = np.reshape(predicted, (predicted.size,))",
"up a few sine waves and some noise :return: the",
"Each row is a training sequence :param y: Tne target",
"= sin(2 * pi * t) print(\"wave2\", len(wave2)) t_rider =",
"shape : \", result.shape X_test = result[:, :-1] y_test =",
"epochs = 1 batch_size = 50 def dropin(X, y): \"\"\"",
"1, 'hidden1': 64, 'hidden2': 256, 'hidden3': 100, 'output': 1} model.add(LSTM(",
"later predict :return: new augmented X, y \"\"\" print(\"X shape:\",",
"np.shape(X_train)) print(\"Shape X_test\", np.shape(X_test)) X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))",
"return np.asarray(X_hat), np.asarray(y_hat) def gen_wave(): \"\"\" Generate a synthetic wave",
"in-place X_train = train[:, :-1] y_train = train[:, -1] X_train,",
"Sequential() layers = {'input': 1, 'hidden1': 64, 'hidden2': 256, 'hidden3':",
"= result.std() result -= result_mean result /= result_std return result,",
"mse = ((y_test - predicted) ** 2) plt.plot(mse, 'r') plt.show()",
"= gen_wave() print(\"Length of Data\", len(data)) # train data print",
"np.asarray(X_hat), np.asarray(y_hat) def gen_wave(): \"\"\" Generate a synthetic wave by",
"test_end - sequence_length): result.append(data[index: index + sequence_length]) result = np.array(result)",
"= arange(0.0, 0.5, 0.01) wave3 = sin(10 * pi *",
"X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) return X_train, y_train, X_test,",
"plt.plot(mse, 'r') plt.show() except Exception as e: print(\"plotting exception\") print",
"1)) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) return X_train, y_train,",
"import arange, sin, pi, random np.random.seed(1234) # Global hyper-parameters sequence_length",
"result_std return result, result_mean def get_split_prep_data(train_start, train_end, test_start, test_end): data",
"def get_split_prep_data(train_start, train_end, test_start, test_end): data = gen_wave() print(\"Length of",
"return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden3'], return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense( output_dim=layers['output'])) model.add(Activation(\"linear\")) start",
"train = result[train_start:train_end, :] np.random.shuffle(train) # shuffles in-place X_train =",
"Augmentation section at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param X: Each row is a",
"Inspired by example from https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent Uses the TensorFlow backend The",
"= np.array(result) # shape (samples, sequence_length) result, result_mean = z_norm(result)",
"= random.normal(0, 0.1, len(t)) wave1 = wave1 + noise print(\"wave1\",",
"noise = random.normal(0, 0.1, len(t)) wave1 = wave1 + noise",
"result -= result_mean result /= result_std return result, result_mean def",
"i in range(0, len(X)): for j in range(0, np.random.random_integers(0, random_data_dup)):",
"result, result_mean = z_norm(result) print \"Mean of test data :",
": ', time.time() - global_start_time return model, y_test, predicted run_network()",
"10 # each sample randomly duplicated between 0 and 9",
"+ 50] + wave3 return wave1 + wave2 def z_norm(result):",
"plt.title(\"Predicted Signal\") plt.plot(predicted[:len(y_test)], 'g') plt.subplot(313) plt.title(\"Squared Error\") mse = ((y_test",
"X_test, y_test = data print '\\nData Loaded. Compiling...\\n' if model",
"import LSTM from keras.models import Sequential from numpy import arange,",
"wave3 return wave1 + wave2 def z_norm(result): result_mean = result.mean()",
"LSTM from keras.models import Sequential from numpy import arange, sin,",
": \", result.shape X_test = result[:, :-1] y_test = result[:,",
"result = [] for index in range(train_start, train_end - sequence_length):",
"= sin(10 * pi * t_rider) print(\"wave3\", len(wave3)) insert =",
"data print \"Creating test data...\" result = [] for index",
"samples. See Data Augmentation section at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param X: Each",
"sample randomly duplicated between 0 and 9 times, see dropin",
"256, 'hidden3': 100, 'output': 1} model.add(LSTM( input_length=sequence_length - 1, input_dim=layers['input'],",
"to detect anomalies in a time-series. \"\"\" import matplotlib.pyplot as",
"import matplotlib.pyplot as plt import numpy as np import time",
"time.time() if data is None: print 'Loading data... ' #",
"data : \", result_mean print \"Test data shape : \",",
"X_test, y_test def build_model(): model = Sequential() layers = {'input':",
"inverse of dropout, i.e. adding more samples. See Data Augmentation",
"[] for index in range(train_start, train_end - sequence_length): result.append(data[index: index",
"data...\" result = [] for index in range(test_start, test_end -",
"1000) else: X_train, y_train, X_test, y_test = data print '\\nData",
"X.shape) print(\"y shape:\", y.shape) X_hat = [] y_hat = []",
"wave1[insert:insert + 50] = wave1[insert:insert + 50] + wave3 return",
"10.0, 0.01) wave1 = sin(2 * 2 * pi *",
"\", result_mean print \"Train data shape : \", result.shape train",
"((y_test - predicted) ** 2) plt.plot(mse, 'r') plt.show() except Exception",
"a time-series. \"\"\" import matplotlib.pyplot as plt import numpy as",
"plt.title(\"Squared Error\") mse = ((y_test - predicted) ** 2) plt.plot(mse,",
"start = time.time() model.compile(loss=\"mse\", optimizer=\"rmsprop\") print \"Compilation Time : \",",
"= round(0.8 * len(t)) wave1[insert:insert + 50] = wave1[insert:insert +",
"sequence_length) result, result_mean = z_norm(result) print \"Mean of train data",
": \", result.shape train = result[train_start:train_end, :] np.random.shuffle(train) # shuffles",
"return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense( output_dim=layers['output'])) model.add(Activation(\"linear\")) start = time.time() model.compile(loss=\"mse\", optimizer=\"rmsprop\")",
"y_train = dropin(X_train, y_train) # test data print \"Creating test",
"anomaly) X_train, y_train, X_test, y_test = get_split_prep_data(0, 700, 500, 1000)",
"train and will later predict :return: new augmented X, y",
"Exception as e: print(\"plotting exception\") print str(e) print 'Training duration",
"'Loading data... ' # train on first 700 samples and",
"if data is None: print 'Loading data... ' # train",
"time-series. \"\"\" import matplotlib.pyplot as plt import numpy as np",
"pi, random np.random.seed(1234) # Global hyper-parameters sequence_length = 100 random_data_dup",
"output_dim=layers['output'])) model.add(Activation(\"linear\")) start = time.time() model.compile(loss=\"mse\", optimizer=\"rmsprop\") print \"Compilation Time",
"\"Creating test data...\" result = [] for index in range(test_start,",
"\", result_mean print \"Test data shape : \", result.shape X_test",
"y_train = train[:, -1] X_train, y_train = dropin(X_train, y_train) #",
"def run_network(model=None, data=None): global_start_time = time.time() if data is None:",
"get_split_prep_data(0, 700, 500, 1000) else: X_train, y_train, X_test, y_test =",
"100 random_data_dup = 10 # each sample randomly duplicated between",
"return model, y_test, 0 try: plt.figure(1) plt.subplot(311) plt.title(\"Actual Test Signal",
"= wave1 + noise print(\"wave1\", len(wave1)) wave2 = sin(2 *",
"batch_size = 50 def dropin(X, y): \"\"\" The name suggests",
"result_mean print \"Train data shape : \", result.shape train =",
"numpy as np import time from keras.layers.core import Dense, Activation,",
"except Exception as e: print(\"plotting exception\") print str(e) print 'Training",
"= time.time() if data is None: print 'Loading data... '",
": \", result_mean print \"Train data shape : \", result.shape",
"'g') plt.subplot(313) plt.title(\"Squared Error\") mse = ((y_test - predicted) **",
"from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM",
"= [] y_hat = [] for i in range(0, len(X)):",
"range(0, np.random.random_integers(0, random_data_dup)): X_hat.append(X[i, :]) y_hat.append(y[i]) return np.asarray(X_hat), np.asarray(y_hat) def",
"Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import",
"run_network(model=None, data=None): global_start_time = time.time() if data is None: print",
"X_train, y_train, X_test, y_test def build_model(): model = Sequential() layers",
"time.time() - global_start_time return model, y_test, 0 try: plt.figure(1) plt.subplot(311)",
"some noise :return: the final wave \"\"\" t = np.arange(0.0,",
"X_train.shape[1], 1)) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) return X_train,",
"keras.layers.recurrent import LSTM from keras.models import Sequential from numpy import",
"+ noise print(\"wave1\", len(wave1)) wave2 = sin(2 * pi *",
"np.asarray(y_hat) def gen_wave(): \"\"\" Generate a synthetic wave by adding",
"[] for i in range(0, len(X)): for j in range(0,",
"t) noise = random.normal(0, 0.1, len(t)) wave1 = wave1 +",
"print \"Compilation Time : \", time.time() - start return model",
"result_mean = z_norm(result) print \"Mean of train data : \",",
"model.add(LSTM( layers['hidden2'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden3'], return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense( output_dim=layers['output']))",
"500, 1000) else: X_train, y_train, X_test, y_test = data print",
"y_test, 0 try: plt.figure(1) plt.subplot(311) plt.title(\"Actual Test Signal w/Anomalies\") plt.plot(y_test[:len(y_test)],",
"basic idea is to detect anomalies in a time-series. \"\"\"",
"# shuffles in-place X_train = train[:, :-1] y_train = train[:,",
"= result[:, :-1] y_test = result[:, -1] print(\"Shape X_train\", np.shape(X_train))",
"random.normal(0, 0.1, len(t)) wave1 = wave1 + noise print(\"wave1\", len(wave1))",
"* pi * t) noise = random.normal(0, 0.1, len(t)) wave1",
"# shape (samples, sequence_length) result, result_mean = z_norm(result) print \"Mean",
"index + sequence_length]) result = np.array(result) # shape (samples, sequence_length)",
"build_model() try: print(\"Training...\") model.fit( X_train, y_train, batch_size=batch_size, nb_epoch=epochs, validation_split=0.05) print(\"Predicting...\")",
"data... ' # train on first 700 samples and test",
"Sequential from numpy import arange, sin, pi, random np.random.seed(1234) #",
"get_split_prep_data(train_start, train_end, test_start, test_end): data = gen_wave() print(\"Length of Data\",",
"result, result_mean = z_norm(result) print \"Mean of train data :",
":param X: Each row is a training sequence :param y:",
"def z_norm(result): result_mean = result.mean() result_std = result.std() result -=",
"result.shape X_test = result[:, :-1] y_test = result[:, -1] print(\"Shape",
"e: print(\"plotting exception\") print str(e) print 'Training duration (s) :",
"0.01) wave1 = sin(2 * 2 * pi * t)",
"'hidden1': 64, 'hidden2': 256, 'hidden3': 100, 'output': 1} model.add(LSTM( input_length=sequence_length",
"[] y_hat = [] for i in range(0, len(X)): for",
"target we train and will later predict :return: new augmented",
"model.add(Dropout(0.2)) model.add(LSTM( layers['hidden2'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden3'], return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense(",
"on first 700 samples and test on next 300 samples",
"first 700 samples and test on next 300 samples (has",
":param y: Tne target we train and will later predict",
"result = np.array(result) # shape (samples, sequence_length) result, result_mean =",
"', time.time() - global_start_time return model, y_test, 0 try: plt.figure(1)",
"= [] for i in range(0, len(X)): for j in",
"result_mean result /= result_std return result, result_mean def get_split_prep_data(train_start, train_end,",
"= get_split_prep_data(0, 700, 500, 1000) else: X_train, y_train, X_test, y_test",
"plt.subplot(312) plt.title(\"Predicted Signal\") plt.plot(predicted[:len(y_test)], 'g') plt.subplot(313) plt.title(\"Squared Error\") mse =",
"result /= result_std return result, result_mean def get_split_prep_data(train_start, train_end, test_start,",
":return: new augmented X, y \"\"\" print(\"X shape:\", X.shape) print(\"y",
"# train data print \"Creating train data...\" result = []",
"64, 'hidden2': 256, 'hidden3': 100, 'output': 1} model.add(LSTM( input_length=sequence_length -",
"plt import numpy as np import time from keras.layers.core import",
"wave1 = wave1 + noise print(\"wave1\", len(wave1)) wave2 = sin(2",
"return result, result_mean def get_split_prep_data(train_start, train_end, test_start, test_end): data =",
"j in range(0, np.random.random_integers(0, random_data_dup)): X_hat.append(X[i, :]) y_hat.append(y[i]) return np.asarray(X_hat),",
"https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent Uses the TensorFlow backend The basic idea is to",
"the TensorFlow backend The basic idea is to detect anomalies",
"* pi * t) print(\"wave2\", len(wave2)) t_rider = arange(0.0, 0.5,",
"print(\"wave2\", len(wave2)) t_rider = arange(0.0, 0.5, 0.01) wave3 = sin(10",
"-= result_mean result /= result_std return result, result_mean def get_split_prep_data(train_start,",
"build_model(): model = Sequential() layers = {'input': 1, 'hidden1': 64,",
": \", time.time() - start return model def run_network(model=None, data=None):",
"nb_epoch=epochs, validation_split=0.05) print(\"Predicting...\") predicted = model.predict(X_test) print(\"Reshaping predicted\") predicted =",
"import time from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent",
"train_end, test_start, test_end): data = gen_wave() print(\"Length of Data\", len(data))",
"return model def run_network(model=None, data=None): global_start_time = time.time() if data",
"each sample randomly duplicated between 0 and 9 times, see",
"dropin(X, y): \"\"\" The name suggests the inverse of dropout,",
"layers['hidden3'], return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense( output_dim=layers['output'])) model.add(Activation(\"linear\")) start = time.time() model.compile(loss=\"mse\",",
"arange(0.0, 0.5, 0.01) wave3 = sin(10 * pi * t_rider)",
"plt.title(\"Actual Test Signal w/Anomalies\") plt.plot(y_test[:len(y_test)], 'b') plt.subplot(312) plt.title(\"Predicted Signal\") plt.plot(predicted[:len(y_test)],",
"y_hat.append(y[i]) return np.asarray(X_hat), np.asarray(y_hat) def gen_wave(): \"\"\" Generate a synthetic",
"* pi * t_rider) print(\"wave3\", len(wave3)) insert = round(0.8 *",
"700 samples and test on next 300 samples (has anomaly)",
"plt.figure(1) plt.subplot(311) plt.title(\"Actual Test Signal w/Anomalies\") plt.plot(y_test[:len(y_test)], 'b') plt.subplot(312) plt.title(\"Predicted",
"for i in range(0, len(X)): for j in range(0, np.random.random_integers(0,",
"# Global hyper-parameters sequence_length = 100 random_data_dup = 10 #",
"result.std() result -= result_mean result /= result_std return result, result_mean",
"result.mean() result_std = result.std() result -= result_mean result /= result_std",
"pi * t) noise = random.normal(0, 0.1, len(t)) wave1 =",
"range(0, len(X)): for j in range(0, np.random.random_integers(0, random_data_dup)): X_hat.append(X[i, :])",
"z_norm(result) print \"Mean of train data : \", result_mean print",
"'r') plt.show() except Exception as e: print(\"plotting exception\") print str(e)",
"Time : \", time.time() - start return model def run_network(model=None,",
"= result.mean() result_std = result.std() result -= result_mean result /=",
"X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) X_test = np.reshape(X_test, (X_test.shape[0],",
"model.add(Activation(\"linear\")) start = time.time() model.compile(loss=\"mse\", optimizer=\"rmsprop\") print \"Compilation Time :",
"at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param X: Each row is a training sequence",
"index in range(train_start, train_end - sequence_length): result.append(data[index: index + sequence_length])",
"as e: print(\"plotting exception\") print str(e) print 'Training duration (s)",
"700, 500, 1000) else: X_train, y_train, X_test, y_test = data",
"y_test = get_split_prep_data(0, 700, 500, 1000) else: X_train, y_train, X_test,",
"pi * t_rider) print(\"wave3\", len(wave3)) insert = round(0.8 * len(t))",
":return: the final wave \"\"\" t = np.arange(0.0, 10.0, 0.01)",
"we train and will later predict :return: new augmented X,",
"\"Mean of train data : \", result_mean print \"Train data",
"print \"Mean of test data : \", result_mean print \"Test",
"+ 50] = wave1[insert:insert + 50] + wave3 return wave1",
"result[train_start:train_end, :] np.random.shuffle(train) # shuffles in-place X_train = train[:, :-1]",
"synthetic wave by adding up a few sine waves and",
"shape:\", X.shape) print(\"y shape:\", y.shape) X_hat = [] y_hat =",
"np.arange(0.0, 10.0, 0.01) wave1 = sin(2 * 2 * pi",
"'hidden3': 100, 'output': 1} model.add(LSTM( input_length=sequence_length - 1, input_dim=layers['input'], output_dim=layers['hidden1'],",
"i.e. adding more samples. See Data Augmentation section at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/",
"print \"Creating test data...\" result = [] for index in",
"result_mean = z_norm(result) print \"Mean of test data : \",",
"and 9 times, see dropin function epochs = 1 batch_size",
"predicted) ** 2) plt.plot(mse, 'r') plt.show() except Exception as e:",
"result, result_mean def get_split_prep_data(train_start, train_end, test_start, test_end): data = gen_wave()",
"try: print(\"Training...\") model.fit( X_train, y_train, batch_size=batch_size, nb_epoch=epochs, validation_split=0.05) print(\"Predicting...\") predicted",
"keras.models import Sequential from numpy import arange, sin, pi, random",
"np.random.seed(1234) # Global hyper-parameters sequence_length = 100 random_data_dup = 10",
"Loaded. Compiling...\\n' if model is None: model = build_model() try:",
"random_data_dup = 10 # each sample randomly duplicated between 0",
"y_train, X_test, y_test def build_model(): model = Sequential() layers =",
"t) print(\"wave2\", len(wave2)) t_rider = arange(0.0, 0.5, 0.01) wave3 =",
"is a training sequence :param y: Tne target we train",
"adding up a few sine waves and some noise :return:",
"example from https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent Uses the TensorFlow backend The basic idea",
"0 and 9 times, see dropin function epochs = 1",
"= z_norm(result) print \"Mean of train data : \", result_mean",
"result = [] for index in range(test_start, test_end - sequence_length):",
"anomalies in a time-series. \"\"\" import matplotlib.pyplot as plt import",
"z_norm(result) print \"Mean of test data : \", result_mean print",
"model.add(LSTM( layers['hidden3'], return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense( output_dim=layers['output'])) model.add(Activation(\"linear\")) start = time.time()",
"= 100 random_data_dup = 10 # each sample randomly duplicated",
"data shape : \", result.shape X_test = result[:, :-1] y_test",
"else: X_train, y_train, X_test, y_test = data print '\\nData Loaded.",
"range(train_start, train_end - sequence_length): result.append(data[index: index + sequence_length]) result =",
"return X_train, y_train, X_test, y_test def build_model(): model = Sequential()",
"(samples, sequence_length) result, result_mean = z_norm(result) print \"Mean of train",
"data is None: print 'Loading data... ' # train on",
"X_hat.append(X[i, :]) y_hat.append(y[i]) return np.asarray(X_hat), np.asarray(y_hat) def gen_wave(): \"\"\" Generate",
"train_end - sequence_length): result.append(data[index: index + sequence_length]) result = np.array(result)",
"model.add(Dropout(0.2)) model.add(LSTM( layers['hidden3'], return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense( output_dim=layers['output'])) model.add(Activation(\"linear\")) start =",
"300 samples (has anomaly) X_train, y_train, X_test, y_test = get_split_prep_data(0,",
"'Training duration (s) : ', time.time() - global_start_time return model,",
"+ sequence_length]) result = np.array(result) # shape (samples, sequence_length) result,",
"as plt import numpy as np import time from keras.layers.core",
"times, see dropin function epochs = 1 batch_size = 50",
"print(\"wave1\", len(wave1)) wave2 = sin(2 * pi * t) print(\"wave2\",",
"0 try: plt.figure(1) plt.subplot(311) plt.title(\"Actual Test Signal w/Anomalies\") plt.plot(y_test[:len(y_test)], 'b')",
"training sequence :param y: Tne target we train and will",
"as np import time from keras.layers.core import Dense, Activation, Dropout",
"np.array(result) # shape (samples, sequence_length) result, result_mean = z_norm(result) print",
"between 0 and 9 times, see dropin function epochs =",
"the inverse of dropout, i.e. adding more samples. See Data",
"Data Augmentation section at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param X: Each row is",
"is None: model = build_model() try: print(\"Training...\") model.fit( X_train, y_train,",
"y: Tne target we train and will later predict :return:",
"model = build_model() try: print(\"Training...\") model.fit( X_train, y_train, batch_size=batch_size, nb_epoch=epochs,",
"suggests the inverse of dropout, i.e. adding more samples. See",
"Signal w/Anomalies\") plt.plot(y_test[:len(y_test)], 'b') plt.subplot(312) plt.title(\"Predicted Signal\") plt.plot(predicted[:len(y_test)], 'g') plt.subplot(313)",
"None: model = build_model() try: print(\"Training...\") model.fit( X_train, y_train, batch_size=batch_size,",
"X: Each row is a training sequence :param y: Tne",
"= ((y_test - predicted) ** 2) plt.plot(mse, 'r') plt.show() except",
"test data print \"Creating test data...\" result = [] for",
"{'input': 1, 'hidden1': 64, 'hidden2': 256, 'hidden3': 100, 'output': 1}",
"\"Mean of test data : \", result_mean print \"Test data",
"= 50 def dropin(X, y): \"\"\" The name suggests the",
"len(X)): for j in range(0, np.random.random_integers(0, random_data_dup)): X_hat.append(X[i, :]) y_hat.append(y[i])",
"= {'input': 1, 'hidden1': 64, 'hidden2': 256, 'hidden3': 100, 'output':",
"insert = round(0.8 * len(t)) wave1[insert:insert + 50] = wave1[insert:insert",
"np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) return X_train, y_train, X_test, y_test def",
"samples (has anomaly) X_train, y_train, X_test, y_test = get_split_prep_data(0, 700,",
"print(\"plotting exception\") print str(e) print 'Training duration (s) : ',",
"* t_rider) print(\"wave3\", len(wave3)) insert = round(0.8 * len(t)) wave1[insert:insert",
"return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden2'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden3'], return_sequences=False)) model.add(Dropout(0.2))",
"- 1, input_dim=layers['input'], output_dim=layers['hidden1'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden2'], return_sequences=True)) model.add(Dropout(0.2))",
"result[:, :-1] y_test = result[:, -1] print(\"Shape X_train\", np.shape(X_train)) print(\"Shape",
"0.1, len(t)) wave1 = wave1 + noise print(\"wave1\", len(wave1)) wave2",
"name suggests the inverse of dropout, i.e. adding more samples.",
"(X_test.shape[0], X_test.shape[1], 1)) return X_train, y_train, X_test, y_test def build_model():",
"pi * t) print(\"wave2\", len(wave2)) t_rider = arange(0.0, 0.5, 0.01)",
"= np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1],",
"noise :return: the final wave \"\"\" t = np.arange(0.0, 10.0,",
"print \"Train data shape : \", result.shape train = result[train_start:train_end,",
"shape:\", y.shape) X_hat = [] y_hat = [] for i",
"result.append(data[index: index + sequence_length]) result = np.array(result) # shape (samples,",
"len(t)) wave1 = wave1 + noise print(\"wave1\", len(wave1)) wave2 =",
"X_train, y_train, X_test, y_test = data print '\\nData Loaded. Compiling...\\n'",
"model.fit( X_train, y_train, batch_size=batch_size, nb_epoch=epochs, validation_split=0.05) print(\"Predicting...\") predicted = model.predict(X_test)",
"train on first 700 samples and test on next 300",
"from keras.models import Sequential from numpy import arange, sin, pi,",
"global_start_time = time.time() if data is None: print 'Loading data...",
"from numpy import arange, sin, pi, random np.random.seed(1234) # Global",
"is to detect anomalies in a time-series. \"\"\" import matplotlib.pyplot",
"import numpy as np import time from keras.layers.core import Dense,",
"shuffles in-place X_train = train[:, :-1] y_train = train[:, -1]",
"X_train\", np.shape(X_train)) print(\"Shape X_test\", np.shape(X_test)) X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1],",
"print 'Loading data... ' # train on first 700 samples",
"idea is to detect anomalies in a time-series. \"\"\" import",
"output_dim=layers['hidden1'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden2'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden3'], return_sequences=False))",
": \", result_mean print \"Test data shape : \", result.shape",
"np.reshape(predicted, (predicted.size,)) except KeyboardInterrupt: print(\"prediction exception\") print 'Training duration (s)",
"plt.show() except Exception as e: print(\"plotting exception\") print str(e) print",
"wave2 def z_norm(result): result_mean = result.mean() result_std = result.std() result",
"result_mean = result.mean() result_std = result.std() result -= result_mean result",
"waves and some noise :return: the final wave \"\"\" t",
"wave \"\"\" t = np.arange(0.0, 10.0, 0.01) wave1 = sin(2",
"* len(t)) wave1[insert:insert + 50] = wave1[insert:insert + 50] +",
"test_end): data = gen_wave() print(\"Length of Data\", len(data)) # train",
"X, y \"\"\" print(\"X shape:\", X.shape) print(\"y shape:\", y.shape) X_hat",
"-1] print(\"Shape X_train\", np.shape(X_train)) print(\"Shape X_test\", np.shape(X_test)) X_train = np.reshape(X_train,",
"* 2 * pi * t) noise = random.normal(0, 0.1,",
"print(\"Length of Data\", len(data)) # train data print \"Creating train",
"print \"Creating train data...\" result = [] for index in",
"\", result.shape train = result[train_start:train_end, :] np.random.shuffle(train) # shuffles in-place",
"gen_wave() print(\"Length of Data\", len(data)) # train data print \"Creating",
"layers['hidden2'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden3'], return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense( output_dim=layers['output'])) model.add(Activation(\"linear\"))",
"Signal\") plt.plot(predicted[:len(y_test)], 'g') plt.subplot(313) plt.title(\"Squared Error\") mse = ((y_test -",
"np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))",
":-1] y_test = result[:, -1] print(\"Shape X_train\", np.shape(X_train)) print(\"Shape X_test\",",
"predicted = np.reshape(predicted, (predicted.size,)) except KeyboardInterrupt: print(\"prediction exception\") print 'Training",
"train[:, -1] X_train, y_train = dropin(X_train, y_train) # test data",
"Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential",
"on next 300 samples (has anomaly) X_train, y_train, X_test, y_test",
"def build_model(): model = Sequential() layers = {'input': 1, 'hidden1':",
"9 times, see dropin function epochs = 1 batch_size =",
"by example from https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent Uses the TensorFlow backend The basic",
"50 def dropin(X, y): \"\"\" The name suggests the inverse",
"optimizer=\"rmsprop\") print \"Compilation Time : \", time.time() - start return",
"input_dim=layers['input'], output_dim=layers['hidden1'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden2'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden3'],",
"len(data)) # train data print \"Creating train data...\" result =",
"- predicted) ** 2) plt.plot(mse, 'r') plt.show() except Exception as",
"\"Test data shape : \", result.shape X_test = result[:, :-1]",
"y.shape) X_hat = [] y_hat = [] for i in",
"sin, pi, random np.random.seed(1234) # Global hyper-parameters sequence_length = 100",
"train data...\" result = [] for index in range(train_start, train_end",
"np.random.random_integers(0, random_data_dup)): X_hat.append(X[i, :]) y_hat.append(y[i]) return np.asarray(X_hat), np.asarray(y_hat) def gen_wave():",
"layers = {'input': 1, 'hidden1': 64, 'hidden2': 256, 'hidden3': 100,",
"The name suggests the inverse of dropout, i.e. adding more",
"Global hyper-parameters sequence_length = 100 random_data_dup = 10 # each",
"and some noise :return: the final wave \"\"\" t =",
"shape : \", result.shape train = result[train_start:train_end, :] np.random.shuffle(train) #",
"= np.arange(0.0, 10.0, 0.01) wave1 = sin(2 * 2 *",
"X_test\", np.shape(X_test)) X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) X_test =",
"hyper-parameters sequence_length = 100 random_data_dup = 10 # each sample",
"'\\nData Loaded. Compiling...\\n' if model is None: model = build_model()",
"-1] X_train, y_train = dropin(X_train, y_train) # test data print",
"in a time-series. \"\"\" import matplotlib.pyplot as plt import numpy",
"for j in range(0, np.random.random_integers(0, random_data_dup)): X_hat.append(X[i, :]) y_hat.append(y[i]) return",
"time.time() model.compile(loss=\"mse\", optimizer=\"rmsprop\") print \"Compilation Time : \", time.time() -",
"0.01) wave3 = sin(10 * pi * t_rider) print(\"wave3\", len(wave3))",
"= Sequential() layers = {'input': 1, 'hidden1': 64, 'hidden2': 256,",
"the final wave \"\"\" t = np.arange(0.0, 10.0, 0.01) wave1",
"y_train, X_test, y_test = get_split_prep_data(0, 700, 500, 1000) else: X_train,",
"model.compile(loss=\"mse\", optimizer=\"rmsprop\") print \"Compilation Time : \", time.time() - start",
"\"\"\" import matplotlib.pyplot as plt import numpy as np import",
"for index in range(train_start, train_end - sequence_length): result.append(data[index: index +",
"except KeyboardInterrupt: print(\"prediction exception\") print 'Training duration (s) : ',",
"y_test def build_model(): model = Sequential() layers = {'input': 1,",
"data = gen_wave() print(\"Length of Data\", len(data)) # train data",
"<reponame>cse-icon-dataAnalytics/lstm-anomaly-detect \"\"\" Inspired by example from https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent Uses the TensorFlow",
"(has anomaly) X_train, y_train, X_test, y_test = get_split_prep_data(0, 700, 500,",
"test on next 300 samples (has anomaly) X_train, y_train, X_test,",
"y): \"\"\" The name suggests the inverse of dropout, i.e.",
"test data : \", result_mean print \"Test data shape :",
"and will later predict :return: new augmented X, y \"\"\"",
"data print \"Creating train data...\" result = [] for index",
"print(\"X shape:\", X.shape) print(\"y shape:\", y.shape) X_hat = [] y_hat",
"y_train) # test data print \"Creating test data...\" result =",
"print '\\nData Loaded. Compiling...\\n' if model is None: model =",
"def gen_wave(): \"\"\" Generate a synthetic wave by adding up",
"TensorFlow backend The basic idea is to detect anomalies in",
"train[:, :-1] y_train = train[:, -1] X_train, y_train = dropin(X_train,",
"model = Sequential() layers = {'input': 1, 'hidden1': 64, 'hidden2':",
"row is a training sequence :param y: Tne target we",
"Generate a synthetic wave by adding up a few sine",
"try: plt.figure(1) plt.subplot(311) plt.title(\"Actual Test Signal w/Anomalies\") plt.plot(y_test[:len(y_test)], 'b') plt.subplot(312)",
"data : \", result_mean print \"Train data shape : \",",
"- start return model def run_network(model=None, data=None): global_start_time = time.time()",
"(s) : ', time.time() - global_start_time return model, y_test, predicted",
"adding more samples. See Data Augmentation section at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param",
"plt.plot(y_test[:len(y_test)], 'b') plt.subplot(312) plt.title(\"Predicted Signal\") plt.plot(predicted[:len(y_test)], 'g') plt.subplot(313) plt.title(\"Squared Error\")",
"+ wave2 def z_norm(result): result_mean = result.mean() result_std = result.std()",
"= build_model() try: print(\"Training...\") model.fit( X_train, y_train, batch_size=batch_size, nb_epoch=epochs, validation_split=0.05)",
"= np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) return X_train, y_train, X_test, y_test",
"input_length=sequence_length - 1, input_dim=layers['input'], output_dim=layers['hidden1'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden2'], return_sequences=True))",
"more samples. See Data Augmentation section at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param X:",
"len(wave3)) insert = round(0.8 * len(t)) wave1[insert:insert + 50] =",
"See Data Augmentation section at http://simaaron.github.io/Estimating-rainfall-from-weather-radar-readings-using-recurrent-neural-networks/ :param X: Each row",
"X_test.shape[1], 1)) return X_train, y_train, X_test, y_test def build_model(): model",
"1 batch_size = 50 def dropin(X, y): \"\"\" The name",
"Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential from",
"arange, sin, pi, random np.random.seed(1234) # Global hyper-parameters sequence_length =",
"The basic idea is to detect anomalies in a time-series.",
"print(\"y shape:\", y.shape) X_hat = [] y_hat = [] for",
"round(0.8 * len(t)) wave1[insert:insert + 50] = wave1[insert:insert + 50]",
"new augmented X, y \"\"\" print(\"X shape:\", X.shape) print(\"y shape:\",",
"wave1 + wave2 def z_norm(result): result_mean = result.mean() result_std =",
"None: print 'Loading data... ' # train on first 700",
"sine waves and some noise :return: the final wave \"\"\"",
"1} model.add(LSTM( input_length=sequence_length - 1, input_dim=layers['input'], output_dim=layers['hidden1'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(",
"[] for index in range(test_start, test_end - sequence_length): result.append(data[index: index",
"result_mean print \"Test data shape : \", result.shape X_test =",
"X_train, y_train, batch_size=batch_size, nb_epoch=epochs, validation_split=0.05) print(\"Predicting...\") predicted = model.predict(X_test) print(\"Reshaping",
"= sin(2 * 2 * pi * t) noise =",
"wave by adding up a few sine waves and some",
"model is None: model = build_model() try: print(\"Training...\") model.fit( X_train,",
"' # train on first 700 samples and test on",
"- global_start_time return model, y_test, 0 try: plt.figure(1) plt.subplot(311) plt.title(\"Actual",
"np.random.shuffle(train) # shuffles in-place X_train = train[:, :-1] y_train =",
"y_hat = [] for i in range(0, len(X)): for j",
"model.predict(X_test) print(\"Reshaping predicted\") predicted = np.reshape(predicted, (predicted.size,)) except KeyboardInterrupt: print(\"prediction",
"global_start_time return model, y_test, 0 try: plt.figure(1) plt.subplot(311) plt.title(\"Actual Test",
"for index in range(test_start, test_end - sequence_length): result.append(data[index: index +",
"dropin function epochs = 1 batch_size = 50 def dropin(X,",
"\", result.shape X_test = result[:, :-1] y_test = result[:, -1]",
"plt.subplot(311) plt.title(\"Actual Test Signal w/Anomalies\") plt.plot(y_test[:len(y_test)], 'b') plt.subplot(312) plt.title(\"Predicted Signal\")",
"a training sequence :param y: Tne target we train and",
"sin(10 * pi * t_rider) print(\"wave3\", len(wave3)) insert = round(0.8",
"\"Train data shape : \", result.shape train = result[train_start:train_end, :]",
"(samples, sequence_length) result, result_mean = z_norm(result) print \"Mean of test",
"# test data print \"Creating test data...\" result = []",
"* t) noise = random.normal(0, 0.1, len(t)) wave1 = wave1",
"= train[:, -1] X_train, y_train = dropin(X_train, y_train) # test",
"\"\"\" Inspired by example from https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent Uses the TensorFlow backend",
"y_train, batch_size=batch_size, nb_epoch=epochs, validation_split=0.05) print(\"Predicting...\") predicted = model.predict(X_test) print(\"Reshaping predicted\")",
"len(wave2)) t_rider = arange(0.0, 0.5, 0.01) wave3 = sin(10 *",
"result.shape train = result[train_start:train_end, :] np.random.shuffle(train) # shuffles in-place X_train",
"= [] for index in range(train_start, train_end - sequence_length): result.append(data[index:",
"wave1 = sin(2 * 2 * pi * t) noise",
"print \"Test data shape : \", result.shape X_test = result[:,",
"predict :return: new augmented X, y \"\"\" print(\"X shape:\", X.shape)",
"t = np.arange(0.0, 10.0, 0.01) wave1 = sin(2 * 2",
"sin(2 * pi * t) print(\"wave2\", len(wave2)) t_rider = arange(0.0,",
"samples and test on next 300 samples (has anomaly) X_train,",
"of Data\", len(data)) # train data print \"Creating train data...\"",
"batch_size=batch_size, nb_epoch=epochs, validation_split=0.05) print(\"Predicting...\") predicted = model.predict(X_test) print(\"Reshaping predicted\") predicted",
"= result[:, -1] print(\"Shape X_train\", np.shape(X_train)) print(\"Shape X_test\", np.shape(X_test)) X_train",
"'hidden2': 256, 'hidden3': 100, 'output': 1} model.add(LSTM( input_length=sequence_length - 1,",
"validation_split=0.05) print(\"Predicting...\") predicted = model.predict(X_test) print(\"Reshaping predicted\") predicted = np.reshape(predicted,",
"# train on first 700 samples and test on next",
"Tne target we train and will later predict :return: new",
"sequence :param y: Tne target we train and will later",
"randomly duplicated between 0 and 9 times, see dropin function",
"2) plt.plot(mse, 'r') plt.show() except Exception as e: print(\"plotting exception\")",
"= result[train_start:train_end, :] np.random.shuffle(train) # shuffles in-place X_train = train[:,",
"\", time.time() - start return model def run_network(model=None, data=None): global_start_time",
"sequence_length = 100 random_data_dup = 10 # each sample randomly",
"see dropin function epochs = 1 batch_size = 50 def",
"few sine waves and some noise :return: the final wave",
"\"\"\" Generate a synthetic wave by adding up a few",
"if model is None: model = build_model() try: print(\"Training...\") model.fit(",
"a synthetic wave by adding up a few sine waves",
"Error\") mse = ((y_test - predicted) ** 2) plt.plot(mse, 'r')",
"print(\"wave3\", len(wave3)) insert = round(0.8 * len(t)) wave1[insert:insert + 50]",
"backend The basic idea is to detect anomalies in a",
"start return model def run_network(model=None, data=None): global_start_time = time.time() if",
"train data print \"Creating train data...\" result = [] for",
"1, input_dim=layers['input'], output_dim=layers['hidden1'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden2'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(",
"print(\"Training...\") model.fit( X_train, y_train, batch_size=batch_size, nb_epoch=epochs, validation_split=0.05) print(\"Predicting...\") predicted =",
"** 2) plt.plot(mse, 'r') plt.show() except Exception as e: print(\"plotting",
"- sequence_length): result.append(data[index: index + sequence_length]) result = np.array(result) #",
"by adding up a few sine waves and some noise",
"X_train, y_train = dropin(X_train, y_train) # test data print \"Creating",
"(predicted.size,)) except KeyboardInterrupt: print(\"prediction exception\") print 'Training duration (s) :",
"test_start, test_end): data = gen_wave() print(\"Length of Data\", len(data)) #",
"model.add(LSTM( input_length=sequence_length - 1, input_dim=layers['input'], output_dim=layers['hidden1'], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers['hidden2'],",
"'output': 1} model.add(LSTM( input_length=sequence_length - 1, input_dim=layers['input'], output_dim=layers['hidden1'], return_sequences=True)) model.add(Dropout(0.2))",
"= np.reshape(predicted, (predicted.size,)) except KeyboardInterrupt: print(\"prediction exception\") print 'Training duration",
"train data : \", result_mean print \"Train data shape :",
"print 'Training duration (s) : ', time.time() - global_start_time return",
"from https://github.com/Vict0rSch/deep_learning/tree/master/keras/recurrent Uses the TensorFlow backend The basic idea is",
"X_test = result[:, :-1] y_test = result[:, -1] print(\"Shape X_train\","
] |
[
"from __future__ import unicode_literals from django.db import models, migrations import",
"b'SALA 1'), (b'SALA 2', b'SALA 2'), (b'SALA 3', b'SALA 3'),",
"] operations = [ migrations.AlterField( model_name='historias', name='fecha_ingreso', field=models.DateField(default=datetime.datetime(2015, 4, 25,",
"b'SALA 2'), (b'SALA 3', b'SALA 3'), (b'SALA 4', b'SALA 4'),",
"(b'GAURDIA', b'GAURDIA'), (b'NEO', b'NEO'), (b'UTI', b'UTI'), (b'UCO', b'UCO'), (b'PRE PARTO',",
"Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='historias', name='hora_ingreso', field=models.TimeField(default=datetime.datetime(2015, 4, 25, 14,",
"b'UTI'), (b'UCO', b'UCO'), (b'PRE PARTO', b'PRE PARTO')]), preserve_default=True, ), ]",
"coding: utf-8 -*- from __future__ import unicode_literals from django.db import",
"verbose_name='Fecha de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='historias', name='hora_ingreso', field=models.TimeField(default=datetime.datetime(2015, 4,",
"preserve_default=True, ), migrations.AlterField( model_name='historias', name='hora_ingreso', field=models.TimeField(default=datetime.datetime(2015, 4, 25, 14, 59,",
"b'SALA 5'), (b'GAURDIA', b'GAURDIA'), (b'NEO', b'NEO'), (b'UTI', b'UTI'), (b'UCO', b'UCO'),",
"migrations.AlterField( model_name='historias', name='hora_ingreso', field=models.TimeField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468307),",
"(b'SALA 5', b'SALA 5'), (b'GAURDIA', b'GAURDIA'), (b'NEO', b'NEO'), (b'UTI', b'UTI'),",
"2', b'SALA 2'), (b'SALA 3', b'SALA 3'), (b'SALA 4', b'SALA",
"2'), (b'SALA 3', b'SALA 3'), (b'SALA 4', b'SALA 4'), (b'SALA",
"migrations.AlterField( model_name='ubicaciones', name='sala', field=models.CharField(max_length=10, choices=[(b'SALA 1', b'SALA 1'), (b'SALA 2',",
"14, 59, 14, 468307), help_text='Formato: hh:mm', verbose_name='Hora de Ingreso'), preserve_default=True,",
"dependencies = [ ('historias', '0006_auto_20150413_0001'), ] operations = [ migrations.AlterField(",
"import models, migrations import datetime class Migration(migrations.Migration): dependencies = [",
"name='fecha_ingreso', field=models.DateField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468359), help_text='Formato: dd/mm/yyyy',",
"= [ ('historias', '0006_auto_20150413_0001'), ] operations = [ migrations.AlterField( model_name='historias',",
"b'GAURDIA'), (b'NEO', b'NEO'), (b'UTI', b'UTI'), (b'UCO', b'UCO'), (b'PRE PARTO', b'PRE",
"4, 25, 14, 59, 14, 468359), help_text='Formato: dd/mm/yyyy', verbose_name='Fecha de",
"[ ('historias', '0006_auto_20150413_0001'), ] operations = [ migrations.AlterField( model_name='historias', name='fecha_ingreso',",
"datetime class Migration(migrations.Migration): dependencies = [ ('historias', '0006_auto_20150413_0001'), ] operations",
"(b'UTI', b'UTI'), (b'UCO', b'UCO'), (b'PRE PARTO', b'PRE PARTO')]), preserve_default=True, ),",
"'0006_auto_20150413_0001'), ] operations = [ migrations.AlterField( model_name='historias', name='fecha_ingreso', field=models.DateField(default=datetime.datetime(2015, 4,",
"25, 14, 59, 14, 468307), help_text='Formato: hh:mm', verbose_name='Hora de Ingreso'),",
"field=models.DateField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468359), help_text='Formato: dd/mm/yyyy', verbose_name='Fecha",
"468307), help_text='Formato: hh:mm', verbose_name='Hora de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='ubicaciones',",
"59, 14, 468359), help_text='Formato: dd/mm/yyyy', verbose_name='Fecha de Ingreso'), preserve_default=True, ),",
"(b'NEO', b'NEO'), (b'UTI', b'UTI'), (b'UCO', b'UCO'), (b'PRE PARTO', b'PRE PARTO')]),",
"django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies =",
"field=models.TimeField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468307), help_text='Formato: hh:mm', verbose_name='Hora",
"b'SALA 3'), (b'SALA 4', b'SALA 4'), (b'SALA 5', b'SALA 5'),",
"unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration):",
"# -*- coding: utf-8 -*- from __future__ import unicode_literals from",
"('historias', '0006_auto_20150413_0001'), ] operations = [ migrations.AlterField( model_name='historias', name='fecha_ingreso', field=models.DateField(default=datetime.datetime(2015,",
"dd/mm/yyyy', verbose_name='Fecha de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='historias', name='hora_ingreso', field=models.TimeField(default=datetime.datetime(2015,",
"b'NEO'), (b'UTI', b'UTI'), (b'UCO', b'UCO'), (b'PRE PARTO', b'PRE PARTO')]), preserve_default=True,",
"migrations.AlterField( model_name='historias', name='fecha_ingreso', field=models.DateField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468359),",
"(b'SALA 3', b'SALA 3'), (b'SALA 4', b'SALA 4'), (b'SALA 5',",
"__future__ import unicode_literals from django.db import models, migrations import datetime",
"-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db",
"14, 59, 14, 468359), help_text='Formato: dd/mm/yyyy', verbose_name='Fecha de Ingreso'), preserve_default=True,",
"de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='ubicaciones', name='sala', field=models.CharField(max_length=10, choices=[(b'SALA 1',",
"468359), help_text='Formato: dd/mm/yyyy', verbose_name='Fecha de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='historias',",
"(b'SALA 2', b'SALA 2'), (b'SALA 3', b'SALA 3'), (b'SALA 4',",
"hh:mm', verbose_name='Hora de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='ubicaciones', name='sala', field=models.CharField(max_length=10,",
"help_text='Formato: dd/mm/yyyy', verbose_name='Fecha de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='historias', name='hora_ingreso',",
"= [ migrations.AlterField( model_name='historias', name='fecha_ingreso', field=models.DateField(default=datetime.datetime(2015, 4, 25, 14, 59,",
"), migrations.AlterField( model_name='ubicaciones', name='sala', field=models.CharField(max_length=10, choices=[(b'SALA 1', b'SALA 1'), (b'SALA",
"verbose_name='Hora de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='ubicaciones', name='sala', field=models.CharField(max_length=10, choices=[(b'SALA",
"class Migration(migrations.Migration): dependencies = [ ('historias', '0006_auto_20150413_0001'), ] operations =",
"utf-8 -*- from __future__ import unicode_literals from django.db import models,",
"choices=[(b'SALA 1', b'SALA 1'), (b'SALA 2', b'SALA 2'), (b'SALA 3',",
"[ migrations.AlterField( model_name='historias', name='fecha_ingreso', field=models.DateField(default=datetime.datetime(2015, 4, 25, 14, 59, 14,",
"3'), (b'SALA 4', b'SALA 4'), (b'SALA 5', b'SALA 5'), (b'GAURDIA',",
"Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='ubicaciones', name='sala', field=models.CharField(max_length=10, choices=[(b'SALA 1', b'SALA",
"help_text='Formato: hh:mm', verbose_name='Hora de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='ubicaciones', name='sala',",
"import unicode_literals from django.db import models, migrations import datetime class",
"4, 25, 14, 59, 14, 468307), help_text='Formato: hh:mm', verbose_name='Hora de",
"-*- from __future__ import unicode_literals from django.db import models, migrations",
"operations = [ migrations.AlterField( model_name='historias', name='fecha_ingreso', field=models.DateField(default=datetime.datetime(2015, 4, 25, 14,",
"model_name='historias', name='fecha_ingreso', field=models.DateField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468359), help_text='Formato:",
"de Ingreso'), preserve_default=True, ), migrations.AlterField( model_name='historias', name='hora_ingreso', field=models.TimeField(default=datetime.datetime(2015, 4, 25,",
"models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('historias',",
"14, 468307), help_text='Formato: hh:mm', verbose_name='Hora de Ingreso'), preserve_default=True, ), migrations.AlterField(",
"14, 468359), help_text='Formato: dd/mm/yyyy', verbose_name='Fecha de Ingreso'), preserve_default=True, ), migrations.AlterField(",
"4'), (b'SALA 5', b'SALA 5'), (b'GAURDIA', b'GAURDIA'), (b'NEO', b'NEO'), (b'UTI',",
"), migrations.AlterField( model_name='historias', name='hora_ingreso', field=models.TimeField(default=datetime.datetime(2015, 4, 25, 14, 59, 14,",
"migrations import datetime class Migration(migrations.Migration): dependencies = [ ('historias', '0006_auto_20150413_0001'),",
"b'SALA 4'), (b'SALA 5', b'SALA 5'), (b'GAURDIA', b'GAURDIA'), (b'NEO', b'NEO'),",
"import datetime class Migration(migrations.Migration): dependencies = [ ('historias', '0006_auto_20150413_0001'), ]",
"preserve_default=True, ), migrations.AlterField( model_name='ubicaciones', name='sala', field=models.CharField(max_length=10, choices=[(b'SALA 1', b'SALA 1'),",
"1'), (b'SALA 2', b'SALA 2'), (b'SALA 3', b'SALA 3'), (b'SALA",
"name='hora_ingreso', field=models.TimeField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468307), help_text='Formato: hh:mm',",
"field=models.CharField(max_length=10, choices=[(b'SALA 1', b'SALA 1'), (b'SALA 2', b'SALA 2'), (b'SALA",
"5', b'SALA 5'), (b'GAURDIA', b'GAURDIA'), (b'NEO', b'NEO'), (b'UTI', b'UTI'), (b'UCO',",
"Migration(migrations.Migration): dependencies = [ ('historias', '0006_auto_20150413_0001'), ] operations = [",
"3', b'SALA 3'), (b'SALA 4', b'SALA 4'), (b'SALA 5', b'SALA",
"4', b'SALA 4'), (b'SALA 5', b'SALA 5'), (b'GAURDIA', b'GAURDIA'), (b'NEO',",
"25, 14, 59, 14, 468359), help_text='Formato: dd/mm/yyyy', verbose_name='Fecha de Ingreso'),",
"(b'SALA 4', b'SALA 4'), (b'SALA 5', b'SALA 5'), (b'GAURDIA', b'GAURDIA'),",
"model_name='historias', name='hora_ingreso', field=models.TimeField(default=datetime.datetime(2015, 4, 25, 14, 59, 14, 468307), help_text='Formato:",
"from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies",
"5'), (b'GAURDIA', b'GAURDIA'), (b'NEO', b'NEO'), (b'UTI', b'UTI'), (b'UCO', b'UCO'), (b'PRE",
"model_name='ubicaciones', name='sala', field=models.CharField(max_length=10, choices=[(b'SALA 1', b'SALA 1'), (b'SALA 2', b'SALA",
"59, 14, 468307), help_text='Formato: hh:mm', verbose_name='Hora de Ingreso'), preserve_default=True, ),",
"name='sala', field=models.CharField(max_length=10, choices=[(b'SALA 1', b'SALA 1'), (b'SALA 2', b'SALA 2'),",
"1', b'SALA 1'), (b'SALA 2', b'SALA 2'), (b'SALA 3', b'SALA"
] |
[
"__author_email__ = '<EMAIL>' __license__ = 'Apache-2.0' __copyright__ = 'Copyright 2017",
"= 'Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.' __url__",
"__author__ = 'debugtalk' __author_email__ = '<EMAIL>' __license__ = 'Apache-2.0' __copyright__",
"HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case' __version__ = '0.2.0' __author__ = 'debugtalk'",
"= '<EMAIL>' __license__ = 'Apache-2.0' __copyright__ = 'Copyright 2017 debugtalk'",
"= 'https://github.com/HttpRunner/har2case' __version__ = '0.2.0' __author__ = 'debugtalk' __author_email__ =",
"= 'debugtalk' __author_email__ = '<EMAIL>' __license__ = 'Apache-2.0' __copyright__ =",
"'har2case' __description__ = 'Convert HAR(HTTP Archive) to YAML/JSON testcases for",
"for HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case' __version__ = '0.2.0' __author__ =",
"__version__ = '0.2.0' __author__ = 'debugtalk' __author_email__ = '<EMAIL>' __license__",
"'debugtalk' __author_email__ = '<EMAIL>' __license__ = 'Apache-2.0' __copyright__ = 'Copyright",
"'Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.' __url__ =",
"= 'har2case' __description__ = 'Convert HAR(HTTP Archive) to YAML/JSON testcases",
"to YAML/JSON testcases for HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case' __version__ =",
"testcases for HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case' __version__ = '0.2.0' __author__",
"= '0.2.0' __author__ = 'debugtalk' __author_email__ = '<EMAIL>' __license__ =",
"__description__ = 'Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.'",
"'https://github.com/HttpRunner/har2case' __version__ = '0.2.0' __author__ = 'debugtalk' __author_email__ = '<EMAIL>'",
"__url__ = 'https://github.com/HttpRunner/har2case' __version__ = '0.2.0' __author__ = 'debugtalk' __author_email__",
"HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case'",
"YAML/JSON testcases for HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case' __version__ = '0.2.0'",
"'0.2.0' __author__ = 'debugtalk' __author_email__ = '<EMAIL>' __license__ = 'Apache-2.0'",
"Archive) to YAML/JSON testcases for HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case' __version__",
"__title__ = 'har2case' __description__ = 'Convert HAR(HTTP Archive) to YAML/JSON"
] |
[
"open(output_file_name, \"w\", encoding=\"utf8\") as f: for app_id in app_ids: f.write(\"{}\\n\".format(app_id))",
"if output_file_name is None: output_file_name = get_frozen_app_ids_filename() with open(output_file_name, \"w\",",
"except FileNotFoundError: print(\"Creating {}\".format(get_frozen_app_ids_filename())) frozen_app_ids = list_app_ids(is_horizontal_banner=is_horizontal_banner) freeze_app_ids(frozen_app_ids) return frozen_app_ids",
"def load_frozen_app_ids(input_file_name=None): if input_file_name is None: input_file_name = get_frozen_app_ids_filename() with",
"get_image_extension()) app_ids = [image_filename_to_app_id(filename) for filename in image_filenames] app_ids =",
"try: frozen_app_ids = load_frozen_app_ids() except FileNotFoundError: print(\"Creating {}\".format(get_frozen_app_ids_filename())) frozen_app_ids =",
"Path from data_utils import get_data_path, get_image_data_path, get_image_extension def app_id_to_image_filename(app_id, is_horizontal_banner=False):",
"\"r\", encoding=\"utf8\") as f: # Do not convert to a",
"want to keep the list order as it is. #",
"filename in image_filenames] app_ids = sorted(app_ids, key=int) return app_ids def",
"frozen_app_ids = load_frozen_app_ids() except FileNotFoundError: print(\"Creating {}\".format(get_frozen_app_ids_filename())) frozen_app_ids = list_app_ids(is_horizontal_banner=is_horizontal_banner)",
"# Just read the list from the file. That is",
"is. # Just read the list from the file. That",
"get_frozen_app_ids(is_horizontal_banner=False): try: frozen_app_ids = load_frozen_app_ids() except FileNotFoundError: print(\"Creating {}\".format(get_frozen_app_ids_filename())) frozen_app_ids",
"= [app_id.strip() for app_id in f.readlines()] return frozen_app_ids def get_frozen_app_ids(is_horizontal_banner=False):",
"as f: # Do not convert to a set object,",
"def freeze_app_ids(app_ids, output_file_name=None): if output_file_name is None: output_file_name = get_frozen_app_ids_filename()",
"import get_data_path, get_image_data_path, get_image_extension def app_id_to_image_filename(app_id, is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner)",
"return image_filename def image_filename_to_app_id(image_filename): base_name = os.path.basename(image_filename) app_id = base_name.strip(get_image_extension())",
"= sorted(app_ids, key=int) return app_ids def get_frozen_app_ids_filename(): frozen_app_ids_filename = get_data_path()",
"open(input_file_name, \"r\", encoding=\"utf8\") as f: # Do not convert to",
"output_file_name = get_frozen_app_ids_filename() with open(output_file_name, \"w\", encoding=\"utf8\") as f: for",
"get_image_data_path, get_image_extension def app_id_to_image_filename(app_id, is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filename =",
"encoding=\"utf8\") as f: for app_id in app_ids: f.write(\"{}\\n\".format(app_id)) return def",
"image_filename_to_app_id(image_filename): base_name = os.path.basename(image_filename) app_id = base_name.strip(get_image_extension()) return app_id def",
"in app_ids: f.write(\"{}\\n\".format(app_id)) return def load_frozen_app_ids(input_file_name=None): if input_file_name is None:",
"input_file_name = get_frozen_app_ids_filename() with open(input_file_name, \"r\", encoding=\"utf8\") as f: #",
"encoding=\"utf8\") as f: # Do not convert to a set",
"app_id in f.readlines()] return frozen_app_ids def get_frozen_app_ids(is_horizontal_banner=False): try: frozen_app_ids =",
"None: input_file_name = get_frozen_app_ids_filename() with open(input_file_name, \"r\", encoding=\"utf8\") as f:",
"a set object, or any other conversion, because we want",
"\"frozen_app_ids.txt\" return frozen_app_ids_filename def freeze_app_ids(app_ids, output_file_name=None): if output_file_name is None:",
"app_ids def get_frozen_app_ids_filename(): frozen_app_ids_filename = get_data_path() + \"frozen_app_ids.txt\" return frozen_app_ids_filename",
"to keep the list order as it is. # Just",
"sorted(app_ids, key=int) return app_ids def get_frozen_app_ids_filename(): frozen_app_ids_filename = get_data_path() +",
"do. Otherwise, appIDs will be scrambled! frozen_app_ids = [app_id.strip() for",
"keep the list order as it is. # Just read",
"key=int) return app_ids def get_frozen_app_ids_filename(): frozen_app_ids_filename = get_data_path() + \"frozen_app_ids.txt\"",
"for app_id in app_ids: f.write(\"{}\\n\".format(app_id)) return def load_frozen_app_ids(input_file_name=None): if input_file_name",
"= Path(image_data_path).glob(\"*\" + get_image_extension()) app_ids = [image_filename_to_app_id(filename) for filename in",
"image_data_path = get_image_data_path(is_horizontal_banner) image_filename = image_data_path + str(app_id) + get_image_extension()",
"load_frozen_app_ids() except FileNotFoundError: print(\"Creating {}\".format(get_frozen_app_ids_filename())) frozen_app_ids = list_app_ids(is_horizontal_banner=is_horizontal_banner) freeze_app_ids(frozen_app_ids) return",
"as it is. # Just read the list from the",
"list_app_ids(is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filenames = Path(image_data_path).glob(\"*\" + get_image_extension()) app_ids",
"get_data_path() + \"frozen_app_ids.txt\" return frozen_app_ids_filename def freeze_app_ids(app_ids, output_file_name=None): if output_file_name",
"def app_id_to_image_filename(app_id, is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filename = image_data_path +",
"to a set object, or any other conversion, because we",
"frozen_app_ids = [app_id.strip() for app_id in f.readlines()] return frozen_app_ids def",
"= get_frozen_app_ids_filename() with open(output_file_name, \"w\", encoding=\"utf8\") as f: for app_id",
"app_id = base_name.strip(get_image_extension()) return app_id def list_app_ids(is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner)",
"is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filename = image_data_path + str(app_id) +",
"from data_utils import get_data_path, get_image_data_path, get_image_extension def app_id_to_image_filename(app_id, is_horizontal_banner=False): image_data_path",
"get_frozen_app_ids_filename(): frozen_app_ids_filename = get_data_path() + \"frozen_app_ids.txt\" return frozen_app_ids_filename def freeze_app_ids(app_ids,",
"get_frozen_app_ids_filename() with open(input_file_name, \"r\", encoding=\"utf8\") as f: # Do not",
"list from the file. That is all there is to",
"+ str(app_id) + get_image_extension() return image_filename def image_filename_to_app_id(image_filename): base_name =",
"app_id def list_app_ids(is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filenames = Path(image_data_path).glob(\"*\" +",
"def list_app_ids(is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filenames = Path(image_data_path).glob(\"*\" + get_image_extension())",
"with open(input_file_name, \"r\", encoding=\"utf8\") as f: # Do not convert",
"scrambled! frozen_app_ids = [app_id.strip() for app_id in f.readlines()] return frozen_app_ids",
"\"w\", encoding=\"utf8\") as f: for app_id in app_ids: f.write(\"{}\\n\".format(app_id)) return",
"= [image_filename_to_app_id(filename) for filename in image_filenames] app_ids = sorted(app_ids, key=int)",
"= base_name.strip(get_image_extension()) return app_id def list_app_ids(is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filenames",
"data_utils import get_data_path, get_image_data_path, get_image_extension def app_id_to_image_filename(app_id, is_horizontal_banner=False): image_data_path =",
"in f.readlines()] return frozen_app_ids def get_frozen_app_ids(is_horizontal_banner=False): try: frozen_app_ids = load_frozen_app_ids()",
"= image_data_path + str(app_id) + get_image_extension() return image_filename def image_filename_to_app_id(image_filename):",
"order as it is. # Just read the list from",
"import os from pathlib import Path from data_utils import get_data_path,",
"freeze_app_ids(app_ids, output_file_name=None): if output_file_name is None: output_file_name = get_frozen_app_ids_filename() with",
"output_file_name=None): if output_file_name is None: output_file_name = get_frozen_app_ids_filename() with open(output_file_name,",
"image_data_path + str(app_id) + get_image_extension() return image_filename def image_filename_to_app_id(image_filename): base_name",
"set object, or any other conversion, because we want to",
"+ \"frozen_app_ids.txt\" return frozen_app_ids_filename def freeze_app_ids(app_ids, output_file_name=None): if output_file_name is",
"= get_image_data_path(is_horizontal_banner) image_filename = image_data_path + str(app_id) + get_image_extension() return",
"convert to a set object, or any other conversion, because",
"[image_filename_to_app_id(filename) for filename in image_filenames] app_ids = sorted(app_ids, key=int) return",
"get_image_data_path(is_horizontal_banner) image_filenames = Path(image_data_path).glob(\"*\" + get_image_extension()) app_ids = [image_filename_to_app_id(filename) for",
"def image_filename_to_app_id(image_filename): base_name = os.path.basename(image_filename) app_id = base_name.strip(get_image_extension()) return app_id",
"image_filename = image_data_path + str(app_id) + get_image_extension() return image_filename def",
"or any other conversion, because we want to keep the",
"get_frozen_app_ids_filename() with open(output_file_name, \"w\", encoding=\"utf8\") as f: for app_id in",
"# Do not convert to a set object, or any",
"to do. Otherwise, appIDs will be scrambled! frozen_app_ids = [app_id.strip()",
"os from pathlib import Path from data_utils import get_data_path, get_image_data_path,",
"there is to do. Otherwise, appIDs will be scrambled! frozen_app_ids",
"None: output_file_name = get_frozen_app_ids_filename() with open(output_file_name, \"w\", encoding=\"utf8\") as f:",
"frozen_app_ids_filename def freeze_app_ids(app_ids, output_file_name=None): if output_file_name is None: output_file_name =",
"str(app_id) + get_image_extension() return image_filename def image_filename_to_app_id(image_filename): base_name = os.path.basename(image_filename)",
"base_name = os.path.basename(image_filename) app_id = base_name.strip(get_image_extension()) return app_id def list_app_ids(is_horizontal_banner=False):",
"[app_id.strip() for app_id in f.readlines()] return frozen_app_ids def get_frozen_app_ids(is_horizontal_banner=False): try:",
"os.path.basename(image_filename) app_id = base_name.strip(get_image_extension()) return app_id def list_app_ids(is_horizontal_banner=False): image_data_path =",
"pathlib import Path from data_utils import get_data_path, get_image_data_path, get_image_extension def",
"because we want to keep the list order as it",
"app_ids = sorted(app_ids, key=int) return app_ids def get_frozen_app_ids_filename(): frozen_app_ids_filename =",
"in image_filenames] app_ids = sorted(app_ids, key=int) return app_ids def get_frozen_app_ids_filename():",
"= get_frozen_app_ids_filename() with open(input_file_name, \"r\", encoding=\"utf8\") as f: # Do",
"file. That is all there is to do. Otherwise, appIDs",
"= load_frozen_app_ids() except FileNotFoundError: print(\"Creating {}\".format(get_frozen_app_ids_filename())) frozen_app_ids = list_app_ids(is_horizontal_banner=is_horizontal_banner) freeze_app_ids(frozen_app_ids)",
"from pathlib import Path from data_utils import get_data_path, get_image_data_path, get_image_extension",
"load_frozen_app_ids(input_file_name=None): if input_file_name is None: input_file_name = get_frozen_app_ids_filename() with open(input_file_name,",
"object, or any other conversion, because we want to keep",
"will be scrambled! frozen_app_ids = [app_id.strip() for app_id in f.readlines()]",
"be scrambled! frozen_app_ids = [app_id.strip() for app_id in f.readlines()] return",
"return frozen_app_ids_filename def freeze_app_ids(app_ids, output_file_name=None): if output_file_name is None: output_file_name",
"f.readlines()] return frozen_app_ids def get_frozen_app_ids(is_horizontal_banner=False): try: frozen_app_ids = load_frozen_app_ids() except",
"f.write(\"{}\\n\".format(app_id)) return def load_frozen_app_ids(input_file_name=None): if input_file_name is None: input_file_name =",
"+ get_image_extension()) app_ids = [image_filename_to_app_id(filename) for filename in image_filenames] app_ids",
"image_filename def image_filename_to_app_id(image_filename): base_name = os.path.basename(image_filename) app_id = base_name.strip(get_image_extension()) return",
"image_filenames = Path(image_data_path).glob(\"*\" + get_image_extension()) app_ids = [image_filename_to_app_id(filename) for filename",
"the list order as it is. # Just read the",
"frozen_app_ids def get_frozen_app_ids(is_horizontal_banner=False): try: frozen_app_ids = load_frozen_app_ids() except FileNotFoundError: print(\"Creating",
"image_filenames] app_ids = sorted(app_ids, key=int) return app_ids def get_frozen_app_ids_filename(): frozen_app_ids_filename",
"Just read the list from the file. That is all",
"return def load_frozen_app_ids(input_file_name=None): if input_file_name is None: input_file_name = get_frozen_app_ids_filename()",
"app_id in app_ids: f.write(\"{}\\n\".format(app_id)) return def load_frozen_app_ids(input_file_name=None): if input_file_name is",
"get_image_extension() return image_filename def image_filename_to_app_id(image_filename): base_name = os.path.basename(image_filename) app_id =",
"+ get_image_extension() return image_filename def image_filename_to_app_id(image_filename): base_name = os.path.basename(image_filename) app_id",
"as f: for app_id in app_ids: f.write(\"{}\\n\".format(app_id)) return def load_frozen_app_ids(input_file_name=None):",
"we want to keep the list order as it is.",
"read the list from the file. That is all there",
"input_file_name is None: input_file_name = get_frozen_app_ids_filename() with open(input_file_name, \"r\", encoding=\"utf8\")",
"return app_id def list_app_ids(is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filenames = Path(image_data_path).glob(\"*\"",
"= os.path.basename(image_filename) app_id = base_name.strip(get_image_extension()) return app_id def list_app_ids(is_horizontal_banner=False): image_data_path",
"appIDs will be scrambled! frozen_app_ids = [app_id.strip() for app_id in",
"app_ids: f.write(\"{}\\n\".format(app_id)) return def load_frozen_app_ids(input_file_name=None): if input_file_name is None: input_file_name",
"is all there is to do. Otherwise, appIDs will be",
"def get_frozen_app_ids_filename(): frozen_app_ids_filename = get_data_path() + \"frozen_app_ids.txt\" return frozen_app_ids_filename def",
"f: # Do not convert to a set object, or",
"def get_frozen_app_ids(is_horizontal_banner=False): try: frozen_app_ids = load_frozen_app_ids() except FileNotFoundError: print(\"Creating {}\".format(get_frozen_app_ids_filename()))",
"list order as it is. # Just read the list",
"= get_image_data_path(is_horizontal_banner) image_filenames = Path(image_data_path).glob(\"*\" + get_image_extension()) app_ids = [image_filename_to_app_id(filename)",
"base_name.strip(get_image_extension()) return app_id def list_app_ids(is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filenames =",
"any other conversion, because we want to keep the list",
"all there is to do. Otherwise, appIDs will be scrambled!",
"other conversion, because we want to keep the list order",
"frozen_app_ids_filename = get_data_path() + \"frozen_app_ids.txt\" return frozen_app_ids_filename def freeze_app_ids(app_ids, output_file_name=None):",
"Otherwise, appIDs will be scrambled! frozen_app_ids = [app_id.strip() for app_id",
"That is all there is to do. Otherwise, appIDs will",
"is None: input_file_name = get_frozen_app_ids_filename() with open(input_file_name, \"r\", encoding=\"utf8\") as",
"not convert to a set object, or any other conversion,",
"if input_file_name is None: input_file_name = get_frozen_app_ids_filename() with open(input_file_name, \"r\",",
"image_data_path = get_image_data_path(is_horizontal_banner) image_filenames = Path(image_data_path).glob(\"*\" + get_image_extension()) app_ids =",
"return app_ids def get_frozen_app_ids_filename(): frozen_app_ids_filename = get_data_path() + \"frozen_app_ids.txt\" return",
"from the file. That is all there is to do.",
"for app_id in f.readlines()] return frozen_app_ids def get_frozen_app_ids(is_horizontal_banner=False): try: frozen_app_ids",
"the file. That is all there is to do. Otherwise,",
"get_image_extension def app_id_to_image_filename(app_id, is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filename = image_data_path",
"for filename in image_filenames] app_ids = sorted(app_ids, key=int) return app_ids",
"is None: output_file_name = get_frozen_app_ids_filename() with open(output_file_name, \"w\", encoding=\"utf8\") as",
"with open(output_file_name, \"w\", encoding=\"utf8\") as f: for app_id in app_ids:",
"return frozen_app_ids def get_frozen_app_ids(is_horizontal_banner=False): try: frozen_app_ids = load_frozen_app_ids() except FileNotFoundError:",
"the list from the file. That is all there is",
"get_data_path, get_image_data_path, get_image_extension def app_id_to_image_filename(app_id, is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filename",
"it is. # Just read the list from the file.",
"is to do. Otherwise, appIDs will be scrambled! frozen_app_ids =",
"import Path from data_utils import get_data_path, get_image_data_path, get_image_extension def app_id_to_image_filename(app_id,",
"f: for app_id in app_ids: f.write(\"{}\\n\".format(app_id)) return def load_frozen_app_ids(input_file_name=None): if",
"get_image_data_path(is_horizontal_banner) image_filename = image_data_path + str(app_id) + get_image_extension() return image_filename",
"output_file_name is None: output_file_name = get_frozen_app_ids_filename() with open(output_file_name, \"w\", encoding=\"utf8\")",
"Path(image_data_path).glob(\"*\" + get_image_extension()) app_ids = [image_filename_to_app_id(filename) for filename in image_filenames]",
"= get_data_path() + \"frozen_app_ids.txt\" return frozen_app_ids_filename def freeze_app_ids(app_ids, output_file_name=None): if",
"conversion, because we want to keep the list order as",
"Do not convert to a set object, or any other",
"app_id_to_image_filename(app_id, is_horizontal_banner=False): image_data_path = get_image_data_path(is_horizontal_banner) image_filename = image_data_path + str(app_id)",
"app_ids = [image_filename_to_app_id(filename) for filename in image_filenames] app_ids = sorted(app_ids,"
] |
[
"import boto3 import random import os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if (BUCKET !=",
"\"rb\") as f: s3.upload_fileobj(f, BUCKET, \"maze\"+str(random.randrange(100000))+\".txt\") else: print(\"EXPORT_S3_BUCKET_URL was not",
"BUCKET, \"maze\"+str(random.randrange(100000))+\".txt\") else: print(\"EXPORT_S3_BUCKET_URL was not set so not uploading",
"random import os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if (BUCKET != None): s3 =",
"boto3 import random import os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if (BUCKET != None):",
"None): s3 = boto3.client('s3') with open(\"maze.txt\", \"rb\") as f: s3.upload_fileobj(f,",
"<reponame>sjm446/aMAZEd #!/usr/bin/env python import boto3 import random import os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL')",
"BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if (BUCKET != None): s3 = boto3.client('s3') with open(\"maze.txt\",",
"\"maze\"+str(random.randrange(100000))+\".txt\") else: print(\"EXPORT_S3_BUCKET_URL was not set so not uploading file\")",
"python import boto3 import random import os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if (BUCKET",
"f: s3.upload_fileobj(f, BUCKET, \"maze\"+str(random.randrange(100000))+\".txt\") else: print(\"EXPORT_S3_BUCKET_URL was not set so",
"s3.upload_fileobj(f, BUCKET, \"maze\"+str(random.randrange(100000))+\".txt\") else: print(\"EXPORT_S3_BUCKET_URL was not set so not",
"import os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if (BUCKET != None): s3 = boto3.client('s3')",
"open(\"maze.txt\", \"rb\") as f: s3.upload_fileobj(f, BUCKET, \"maze\"+str(random.randrange(100000))+\".txt\") else: print(\"EXPORT_S3_BUCKET_URL was",
"with open(\"maze.txt\", \"rb\") as f: s3.upload_fileobj(f, BUCKET, \"maze\"+str(random.randrange(100000))+\".txt\") else: print(\"EXPORT_S3_BUCKET_URL",
"if (BUCKET != None): s3 = boto3.client('s3') with open(\"maze.txt\", \"rb\")",
"import random import os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if (BUCKET != None): s3",
"= boto3.client('s3') with open(\"maze.txt\", \"rb\") as f: s3.upload_fileobj(f, BUCKET, \"maze\"+str(random.randrange(100000))+\".txt\")",
"(BUCKET != None): s3 = boto3.client('s3') with open(\"maze.txt\", \"rb\") as",
"as f: s3.upload_fileobj(f, BUCKET, \"maze\"+str(random.randrange(100000))+\".txt\") else: print(\"EXPORT_S3_BUCKET_URL was not set",
"os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if (BUCKET != None): s3 = boto3.client('s3') with",
"!= None): s3 = boto3.client('s3') with open(\"maze.txt\", \"rb\") as f:",
"boto3.client('s3') with open(\"maze.txt\", \"rb\") as f: s3.upload_fileobj(f, BUCKET, \"maze\"+str(random.randrange(100000))+\".txt\") else:",
"#!/usr/bin/env python import boto3 import random import os BUCKET=os.environ.get('EXPORT_S3_BUCKET_URL') if",
"s3 = boto3.client('s3') with open(\"maze.txt\", \"rb\") as f: s3.upload_fileobj(f, BUCKET,"
] |
[
"if realm.deactivated: print(self.style.ERROR(outer_format % (realm.id, realm.string_id, realm.name))) deactivated = True",
"from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help = \"\"\"List realms",
"Fix the one bitfield to display useful data realm_dict['authentication_methods'] =",
"object, which is # hacky but doesn't require any work",
"is confusingly useless del realm_dict['_state'] # Fix the one bitfield",
"% (key, realm_dict[key])) for key, value in sorted(realm_dict.iteritems()): if key",
"the server and it's configuration settings(optional). Usage examples: ./manage.py list_realms",
"remaining code path is the --all case. identifier_attributes = [\"id\",",
"from typing import Any from argparse import ArgumentParser from zerver.models",
"def handle(self, *args: Any, **options: Any) -> None: realms =",
"if not options[\"all\"]: print(outer_format % (\"id\", \"string_id\", \"name\")) print(outer_format %",
"% (realm.id, realm.string_id, realm.name)) if deactivated: print(self.style.WARNING(\"\\nRed rows represent deactivated",
"sys.exit(0) # The remaining code path is the --all case.",
"confusingly useless del realm_dict['_state'] # Fix the one bitfield to",
"the configuration settings of the realms.\") def handle(self, *args: Any,",
"fields on the object, which is # hacky but doesn't",
"= realm.__dict__ # Remove a field that is confusingly useless",
"import ArgumentParser from zerver.models import Realm from zerver.lib.management import ZulipBaseCommand",
"realms in the server and it's configuration settings(optional). Usage examples:",
"**options: Any) -> None: realms = Realm.objects.all() outer_format = \"%-5s",
"\"name\")) print(outer_format % (\"--\", \"---------\", \"----\")) for realm in realms:",
"useless del realm_dict['_state'] # Fix the one bitfield to display",
"add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument(\"--all\", dest=\"all\", action=\"store_true\", default=False, help=\"Print",
"data realm_dict['authentication_methods'] = str(realm.authentication_methods_dict()) for key in identifier_attributes: if realm.deactivated:",
"(key, realm_dict[key]))) deactivated = True else: print(inner_format % (key, realm_dict[key]))",
"identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key, realm_dict[key]))) deactivated = True",
"it's configuration settings(optional). Usage examples: ./manage.py list_realms ./manage.py list_realms --all\"\"\"",
"realm in realms: # Start with just all the fields",
"configuration settings of the realms.\") def handle(self, *args: Any, **options:",
"Any, **options: Any) -> None: realms = Realm.objects.all() outer_format =",
"%-40s\" inner_format = \"%-40s %s\" deactivated = False if not",
"value))) else: print(inner_format % (key, value)) print(\"-\" * 80) if",
"from zerver.models import Realm from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand):",
"print(outer_format % (realm.id, realm.string_id, realm.name)) if deactivated: print(self.style.WARNING(\"\\nRed rows represent",
"(realm.id, realm.string_id, realm.name))) deactivated = True else: print(outer_format % (realm.id,",
"maintain. realm_dict = realm.__dict__ # Remove a field that is",
"None: realms = Realm.objects.all() outer_format = \"%-5s %-40s %-40s\" inner_format",
"realms.\")) sys.exit(0) # The remaining code path is the --all",
"code path is the --all case. identifier_attributes = [\"id\", \"name\",",
"if deactivated: print(self.style.WARNING(\"\\nRed rows represent deactivated realms.\")) sys.exit(0) # The",
"key not in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key, value)))",
"with just all the fields on the object, which is",
"of the realms.\") def handle(self, *args: Any, **options: Any) ->",
"Usage examples: ./manage.py list_realms ./manage.py list_realms --all\"\"\" def add_arguments(self, parser:",
"None: parser.add_argument(\"--all\", dest=\"all\", action=\"store_true\", default=False, help=\"Print all the configuration settings",
"realm.string_id, realm.name)) if deactivated: print(self.style.WARNING(\"\\nRed rows represent deactivated realms.\")) sys.exit(0)",
"import sys from typing import Any from argparse import ArgumentParser",
"one bitfield to display useful data realm_dict['authentication_methods'] = str(realm.authentication_methods_dict()) for",
"in the server and it's configuration settings(optional). Usage examples: ./manage.py",
"= \"%-40s %s\" deactivated = False if not options[\"all\"]: print(outer_format",
"= True else: print(inner_format % (key, realm_dict[key])) for key, value",
"realm_dict[key]))) deactivated = True else: print(inner_format % (key, realm_dict[key])) for",
"realm.name))) deactivated = True else: print(outer_format % (realm.id, realm.string_id, realm.name))",
"deactivated = False if not options[\"all\"]: print(outer_format % (\"id\", \"string_id\",",
"options[\"all\"]: print(outer_format % (\"id\", \"string_id\", \"name\")) print(outer_format % (\"--\", \"---------\",",
"% (key, value)) print(\"-\" * 80) if deactivated: print(self.style.WARNING(\"\\nRed is",
"Start with just all the fields on the object, which",
"represent deactivated realms.\")) sys.exit(0) # The remaining code path is",
"in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key, realm_dict[key]))) deactivated =",
"a field that is confusingly useless del realm_dict['_state'] # Fix",
"argparse import ArgumentParser from zerver.models import Realm from zerver.lib.management import",
"def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument(\"--all\", dest=\"all\", action=\"store_true\", default=False,",
"True else: print(outer_format % (realm.id, realm.string_id, realm.name)) if deactivated: print(self.style.WARNING(\"\\nRed",
"print(self.style.ERROR(outer_format % (realm.id, realm.string_id, realm.name))) deactivated = True else: print(outer_format",
"realm_dict[key])) for key, value in sorted(realm_dict.iteritems()): if key not in",
"bitfield to display useful data realm_dict['authentication_methods'] = str(realm.authentication_methods_dict()) for key",
"if realm.deactivated: print(self.style.ERROR(inner_format % (key, value))) else: print(inner_format % (key,",
"settings(optional). Usage examples: ./manage.py list_realms ./manage.py list_realms --all\"\"\" def add_arguments(self,",
"print(self.style.ERROR(inner_format % (key, value))) else: print(inner_format % (key, value)) print(\"-\"",
"path is the --all case. identifier_attributes = [\"id\", \"name\", \"string_id\"]",
"action=\"store_true\", default=False, help=\"Print all the configuration settings of the realms.\")",
"print(inner_format % (key, value)) print(\"-\" * 80) if deactivated: print(self.style.WARNING(\"\\nRed",
"% (key, value))) else: print(inner_format % (key, value)) print(\"-\" *",
"* 80) if deactivated: print(self.style.WARNING(\"\\nRed is used to highlight deactivated",
"the object, which is # hacky but doesn't require any",
"(key, value))) else: print(inner_format % (key, value)) print(\"-\" * 80)",
"the --all case. identifier_attributes = [\"id\", \"name\", \"string_id\"] for realm",
"key, value in sorted(realm_dict.iteritems()): if key not in identifier_attributes: if",
"dest=\"all\", action=\"store_true\", default=False, help=\"Print all the configuration settings of the",
"in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key, value))) else: print(inner_format",
"in realms: if realm.deactivated: print(self.style.ERROR(outer_format % (realm.id, realm.string_id, realm.name))) deactivated",
"realm_dict['authentication_methods'] = str(realm.authentication_methods_dict()) for key in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format",
"--all case. identifier_attributes = [\"id\", \"name\", \"string_id\"] for realm in",
"rows represent deactivated realms.\")) sys.exit(0) # The remaining code path",
"% (key, realm_dict[key]))) deactivated = True else: print(inner_format % (key,",
"zerver.models import Realm from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help",
"in sorted(realm_dict.iteritems()): if key not in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format",
"handle(self, *args: Any, **options: Any) -> None: realms = Realm.objects.all()",
"# Remove a field that is confusingly useless del realm_dict['_state']",
"not options[\"all\"]: print(outer_format % (\"id\", \"string_id\", \"name\")) print(outer_format % (\"--\",",
"for key, value in sorted(realm_dict.iteritems()): if key not in identifier_attributes:",
"that is confusingly useless del realm_dict['_state'] # Fix the one",
"from argparse import ArgumentParser from zerver.models import Realm from zerver.lib.management",
"all the configuration settings of the realms.\") def handle(self, *args:",
"Command(ZulipBaseCommand): help = \"\"\"List realms in the server and it's",
"./manage.py list_realms --all\"\"\" def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument(\"--all\",",
"just all the fields on the object, which is #",
"to display useful data realm_dict['authentication_methods'] = str(realm.authentication_methods_dict()) for key in",
"import Realm from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help =",
"settings of the realms.\") def handle(self, *args: Any, **options: Any)",
"for realm in realms: if realm.deactivated: print(self.style.ERROR(outer_format % (realm.id, realm.string_id,",
"realms.\") def handle(self, *args: Any, **options: Any) -> None: realms",
"<filename>zerver/management/commands/list_realms.py<gh_stars>0 import sys from typing import Any from argparse import",
"= [\"id\", \"name\", \"string_id\"] for realm in realms: # Start",
"but doesn't require any work to maintain. realm_dict = realm.__dict__",
"identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key, value))) else: print(inner_format %",
"--all\"\"\" def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument(\"--all\", dest=\"all\", action=\"store_true\",",
"= str(realm.authentication_methods_dict()) for key in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format %",
"to maintain. realm_dict = realm.__dict__ # Remove a field that",
"-> None: realms = Realm.objects.all() outer_format = \"%-5s %-40s %-40s\"",
"realm.deactivated: print(self.style.ERROR(inner_format % (key, realm_dict[key]))) deactivated = True else: print(inner_format",
"Any from argparse import ArgumentParser from zerver.models import Realm from",
"list_realms --all\"\"\" def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument(\"--all\", dest=\"all\",",
"the one bitfield to display useful data realm_dict['authentication_methods'] = str(realm.authentication_methods_dict())",
"if key not in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key,",
"print(\"-\" * 80) if deactivated: print(self.style.WARNING(\"\\nRed is used to highlight",
"the realms.\") def handle(self, *args: Any, **options: Any) -> None:",
"% (realm.id, realm.string_id, realm.name))) deactivated = True else: print(outer_format %",
"sorted(realm_dict.iteritems()): if key not in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format %",
"ArgumentParser) -> None: parser.add_argument(\"--all\", dest=\"all\", action=\"store_true\", default=False, help=\"Print all the",
"is # hacky but doesn't require any work to maintain.",
"%s\" deactivated = False if not options[\"all\"]: print(outer_format % (\"id\",",
"% (\"--\", \"---------\", \"----\")) for realm in realms: if realm.deactivated:",
"str(realm.authentication_methods_dict()) for key in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key,",
"parser.add_argument(\"--all\", dest=\"all\", action=\"store_true\", default=False, help=\"Print all the configuration settings of",
"realms: if realm.deactivated: print(self.style.ERROR(outer_format % (realm.id, realm.string_id, realm.name))) deactivated =",
"\"---------\", \"----\")) for realm in realms: if realm.deactivated: print(self.style.ERROR(outer_format %",
"Any) -> None: realms = Realm.objects.all() outer_format = \"%-5s %-40s",
"\"\"\"List realms in the server and it's configuration settings(optional). Usage",
"for realm in realms: # Start with just all the",
"case. identifier_attributes = [\"id\", \"name\", \"string_id\"] for realm in realms:",
"field that is confusingly useless del realm_dict['_state'] # Fix the",
"\"name\", \"string_id\"] for realm in realms: # Start with just",
"# Fix the one bitfield to display useful data realm_dict['authentication_methods']",
"hacky but doesn't require any work to maintain. realm_dict =",
"typing import Any from argparse import ArgumentParser from zerver.models import",
"(\"--\", \"---------\", \"----\")) for realm in realms: if realm.deactivated: print(self.style.ERROR(outer_format",
"False if not options[\"all\"]: print(outer_format % (\"id\", \"string_id\", \"name\")) print(outer_format",
"\"%-40s %s\" deactivated = False if not options[\"all\"]: print(outer_format %",
"print(outer_format % (\"id\", \"string_id\", \"name\")) print(outer_format % (\"--\", \"---------\", \"----\"))",
"\"string_id\"] for realm in realms: # Start with just all",
"in realms: # Start with just all the fields on",
"= \"\"\"List realms in the server and it's configuration settings(optional).",
"Realm from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help = \"\"\"List",
"(realm.id, realm.string_id, realm.name)) if deactivated: print(self.style.WARNING(\"\\nRed rows represent deactivated realms.\"))",
"ArgumentParser from zerver.models import Realm from zerver.lib.management import ZulipBaseCommand class",
"print(self.style.ERROR(inner_format % (key, realm_dict[key]))) deactivated = True else: print(inner_format %",
"realms = Realm.objects.all() outer_format = \"%-5s %-40s %-40s\" inner_format =",
"server and it's configuration settings(optional). Usage examples: ./manage.py list_realms ./manage.py",
"examples: ./manage.py list_realms ./manage.py list_realms --all\"\"\" def add_arguments(self, parser: ArgumentParser)",
"print(outer_format % (\"--\", \"---------\", \"----\")) for realm in realms: if",
"# hacky but doesn't require any work to maintain. realm_dict",
"True else: print(inner_format % (key, realm_dict[key])) for key, value in",
"doesn't require any work to maintain. realm_dict = realm.__dict__ #",
"value in sorted(realm_dict.iteritems()): if key not in identifier_attributes: if realm.deactivated:",
"[\"id\", \"name\", \"string_id\"] for realm in realms: # Start with",
"display useful data realm_dict['authentication_methods'] = str(realm.authentication_methods_dict()) for key in identifier_attributes:",
"import Any from argparse import ArgumentParser from zerver.models import Realm",
"\"%-5s %-40s %-40s\" inner_format = \"%-40s %s\" deactivated = False",
"realm.deactivated: print(self.style.ERROR(inner_format % (key, value))) else: print(inner_format % (key, value))",
"./manage.py list_realms ./manage.py list_realms --all\"\"\" def add_arguments(self, parser: ArgumentParser) ->",
"= True else: print(outer_format % (realm.id, realm.string_id, realm.name)) if deactivated:",
"any work to maintain. realm_dict = realm.__dict__ # Remove a",
"on the object, which is # hacky but doesn't require",
"work to maintain. realm_dict = realm.__dict__ # Remove a field",
"Realm.objects.all() outer_format = \"%-5s %-40s %-40s\" inner_format = \"%-40s %s\"",
"deactivated = True else: print(inner_format % (key, realm_dict[key])) for key,",
"all the fields on the object, which is # hacky",
"require any work to maintain. realm_dict = realm.__dict__ # Remove",
"realm in realms: if realm.deactivated: print(self.style.ERROR(outer_format % (realm.id, realm.string_id, realm.name)))",
"(\"id\", \"string_id\", \"name\")) print(outer_format % (\"--\", \"---------\", \"----\")) for realm",
"else: print(outer_format % (realm.id, realm.string_id, realm.name)) if deactivated: print(self.style.WARNING(\"\\nRed rows",
"realm.name)) if deactivated: print(self.style.WARNING(\"\\nRed rows represent deactivated realms.\")) sys.exit(0) #",
"\"----\")) for realm in realms: if realm.deactivated: print(self.style.ERROR(outer_format % (realm.id,",
"sys from typing import Any from argparse import ArgumentParser from",
"class Command(ZulipBaseCommand): help = \"\"\"List realms in the server and",
"outer_format = \"%-5s %-40s %-40s\" inner_format = \"%-40s %s\" deactivated",
"deactivated: print(self.style.WARNING(\"\\nRed rows represent deactivated realms.\")) sys.exit(0) # The remaining",
"zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help = \"\"\"List realms in",
"= \"%-5s %-40s %-40s\" inner_format = \"%-40s %s\" deactivated =",
"list_realms ./manage.py list_realms --all\"\"\" def add_arguments(self, parser: ArgumentParser) -> None:",
"% (\"id\", \"string_id\", \"name\")) print(outer_format % (\"--\", \"---------\", \"----\")) for",
"= False if not options[\"all\"]: print(outer_format % (\"id\", \"string_id\", \"name\"))",
"deactivated realms.\")) sys.exit(0) # The remaining code path is the",
"key in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key, realm_dict[key]))) deactivated",
"inner_format = \"%-40s %s\" deactivated = False if not options[\"all\"]:",
"realm_dict = realm.__dict__ # Remove a field that is confusingly",
"(key, realm_dict[key])) for key, value in sorted(realm_dict.iteritems()): if key not",
"deactivated = True else: print(outer_format % (realm.id, realm.string_id, realm.name)) if",
"useful data realm_dict['authentication_methods'] = str(realm.authentication_methods_dict()) for key in identifier_attributes: if",
"realm.string_id, realm.name))) deactivated = True else: print(outer_format % (realm.id, realm.string_id,",
"print(inner_format % (key, realm_dict[key])) for key, value in sorted(realm_dict.iteritems()): if",
"\"string_id\", \"name\")) print(outer_format % (\"--\", \"---------\", \"----\")) for realm in",
"realm_dict['_state'] # Fix the one bitfield to display useful data",
"value)) print(\"-\" * 80) if deactivated: print(self.style.WARNING(\"\\nRed is used to",
"realms: # Start with just all the fields on the",
"del realm_dict['_state'] # Fix the one bitfield to display useful",
"help = \"\"\"List realms in the server and it's configuration",
"# Start with just all the fields on the object,",
"else: print(inner_format % (key, realm_dict[key])) for key, value in sorted(realm_dict.iteritems()):",
"help=\"Print all the configuration settings of the realms.\") def handle(self,",
"= Realm.objects.all() outer_format = \"%-5s %-40s %-40s\" inner_format = \"%-40s",
"else: print(inner_format % (key, value)) print(\"-\" * 80) if deactivated:",
"print(self.style.WARNING(\"\\nRed rows represent deactivated realms.\")) sys.exit(0) # The remaining code",
"# The remaining code path is the --all case. identifier_attributes",
"Remove a field that is confusingly useless del realm_dict['_state'] #",
"realm.deactivated: print(self.style.ERROR(outer_format % (realm.id, realm.string_id, realm.name))) deactivated = True else:",
"configuration settings(optional). Usage examples: ./manage.py list_realms ./manage.py list_realms --all\"\"\" def",
"ZulipBaseCommand class Command(ZulipBaseCommand): help = \"\"\"List realms in the server",
"parser: ArgumentParser) -> None: parser.add_argument(\"--all\", dest=\"all\", action=\"store_true\", default=False, help=\"Print all",
"if realm.deactivated: print(self.style.ERROR(inner_format % (key, realm_dict[key]))) deactivated = True else:",
"*args: Any, **options: Any) -> None: realms = Realm.objects.all() outer_format",
"80) if deactivated: print(self.style.WARNING(\"\\nRed is used to highlight deactivated realms.\"))",
"The remaining code path is the --all case. identifier_attributes =",
"import ZulipBaseCommand class Command(ZulipBaseCommand): help = \"\"\"List realms in the",
"%-40s %-40s\" inner_format = \"%-40s %s\" deactivated = False if",
"is the --all case. identifier_attributes = [\"id\", \"name\", \"string_id\"] for",
"realm.__dict__ # Remove a field that is confusingly useless del",
"the fields on the object, which is # hacky but",
"-> None: parser.add_argument(\"--all\", dest=\"all\", action=\"store_true\", default=False, help=\"Print all the configuration",
"(key, value)) print(\"-\" * 80) if deactivated: print(self.style.WARNING(\"\\nRed is used",
"for key in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key, realm_dict[key])))",
"and it's configuration settings(optional). Usage examples: ./manage.py list_realms ./manage.py list_realms",
"which is # hacky but doesn't require any work to",
"not in identifier_attributes: if realm.deactivated: print(self.style.ERROR(inner_format % (key, value))) else:",
"default=False, help=\"Print all the configuration settings of the realms.\") def",
"identifier_attributes = [\"id\", \"name\", \"string_id\"] for realm in realms: #"
] |
[
"is furnished to do so, subject to the fol- #",
"of private AMI's rs = c.get_all_images(owners=[user_id]) assert len(rs) > 0",
"permission status = image.remove_launch_permissions(group_names=['all']) assert status time.sleep(10) d = image.get_launch_permissions()",
"= c.authorize_security_group(group1.name, group2.name, group2.owner_id) assert status status = c.revoke_security_group(group1.name, group2.name,",
"= c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small', dry_run=True ) self.fail(\"Should have gotten an",
"print '--- running EC2Connection tests ---' c = EC2Connection() #",
"included # in all copies or substantial portions of the",
"created during unit testing' group1 = c.create_security_group(group1_name, group_desc) time.sleep(2) group2_name",
"WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT",
"rs: if k.name == key_name: found = True assert found",
"create a new key pair key_name = 'test-%d' % int(time.time())",
"EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"# instance in now running, try to telnet to port",
"= 'test-%d' % int(time.time()) group_desc = 'This is a security",
"d = image.get_launch_permissions() assert 'groups' not in d def test_1_basic(self):",
"> 0 # now pick the first one image =",
"group2 = c.create_security_group(group2_name, group_desc) # now get a listing of",
"a specific port status = c.authorize_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22,",
"= image.get_launch_permissions() assert 'groups' in d assert len(d['groups']) > 0",
"assert len(rs) > 0 # now pick the first one",
"= reservation.instances[0] while instance.state != 'running': print '\\tinstance is %s'",
"OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE.",
"EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) # Need an actual instance",
"g.name == group2_name: found = True assert not found group",
"time.sleep(10) d = image.get_launch_permissions() assert 'groups' not in d def",
"groups and look for our new one rs = c.get_all_security_groups()",
"to filter results to only our new group rs =",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS #",
"the EC2Connection \"\"\" import unittest import time import telnetlib import",
"len(rs) > 0 # now pick the first one image",
"free of charge, to any person obtaining a # copy",
"the instance and delete the security group instance.terminate() # check",
"# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"that state and previous_state have updated assert instance.state == 'shutting-down'",
"to the fol- # lowing conditions: # # The above",
"the fol- # lowing conditions: # # The above copyright",
"a listing of all key pairs and look for our",
"# now revoke authorization and try again group.revoke('tcp', 80, 80,",
"group.revoke('tcp', 80, 80, '0.0.0.0/0') try: t.open(instance.dns_name, 80) except socket.error: pass",
"NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY",
"status time.sleep(10) d = image.get_launch_permissions() assert 'groups' not in d",
"ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"portions of the Software. # # THE SOFTWARE IS PROVIDED",
"assert instance.previous_state_code == 16 # unfortunately, I can't delete the",
"use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or",
"tests completed ---' def test_dry_run(self): c = EC2Connection() dry_run_msg =",
"make sure it's really gone rs = c.get_all_security_groups() found =",
"status d = image.get_launch_permissions() assert 'groups' in d assert len(d['groups'])",
"any person obtaining a # copy of this software and",
"# # The above copyright notice and this permission notice",
"self.assertTrue(dry_run_msg in str(e)) # Need an actual instance for the",
"80, 80, '0.0.0.0/0') try: t.open(instance.dns_name, 80) except socket.error: pass #",
"authorizations/revocations # first try the old style status = c.authorize_security_group(group1.name,",
"key_name: found = True assert found # now pass arg",
"Paid AMI capability demo_paid_ami_id = 'ami-bd9d78d4' demo_paid_ami_product_code = 'A79EC0DB' l",
"unit tests for the EC2Connection \"\"\" import unittest import time",
"flag is set.' try: rs = c.get_all_images(dry_run=True) self.fail(\"Should have gotten",
"user_id, if you want to run these tests you should",
"status = c.authorize_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22) assert status",
"1 key_pair = rs[0] # now delete the key pair",
"22) assert status # now delete the second security group",
"open up port 80 and try again, it should work",
"Need an actual instance for the rest of this... rs",
"USE OR OTHER DEALINGS # IN THE SOFTWARE. \"\"\" Some",
"hereby granted, free of charge, to any person obtaining a",
"k.name == key_name: found = True assert found # now",
"g in rs: if g.name == group1_name: found = True",
"in str(e)) # Need an actual instance for the rest",
"test around Paid AMI capability demo_paid_ami_id = 'ami-bd9d78d4' demo_paid_ami_product_code =",
"get a listing of all key pairs and look for",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"key pair rs = c.get_all_key_pairs([key_name]) assert len(rs) == 1 key_pair",
"demo_paid_ami_id = 'ami-bd9d78d4' demo_paid_ami_product_code = 'A79EC0DB' l = c.get_all_images([demo_paid_ami_id]) assert",
"# now try specifying a specific port status = c.authorize_security_group(group1.name,",
"to run these tests you should # replace this with",
"AMI's rs = c.get_all_images(owners=[user_id]) assert len(rs) > 0 # now",
"rs = c.get_all_key_pairs([key_name]) assert len(rs) == 1 key_pair = rs[0]",
"== 'running' assert instance.previous_state_code == 16 # unfortunately, I can't",
"'tcp', 22, 22) assert status # now delete the second",
"our new one rs = c.get_all_security_groups() found = False for",
"again, it should work group.authorize('tcp', 80, 80, '0.0.0.0/0') t.open(instance.dns_name, 80)",
"now try to launch apache image with our new security",
"without restriction, including # without limitation the rights to use,",
"have gotten an exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e))",
"telnetlib.Telnet() try: t.open(instance.dns_name, 80) except socket.error: pass # now open",
"c.delete_key_pair(key_name) # now make sure it's really gone rs =",
"c.delete_security_group(group2_name) # now make sure it's really gone rs =",
"# first try the old style status = c.authorize_security_group(group1.name, group2.name,",
"# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS",
"rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small', dry_run=True ) self.fail(\"Should have gotten",
"shall be included # in all copies or substantial portions",
"c.create_key_pair(key_name) assert status # now get a listing of all",
"= False for k in rs: if k.name == key_name:",
"image.get_launch_permissions() assert 'groups' not in d def test_1_basic(self): # create",
"= c.create_security_group(group1_name, group_desc) time.sleep(2) group2_name = 'test-%d' % int(time.time()) group_desc",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"# now get a listing of all security groups and",
"= False for g in rs: if g.name == group1_name:",
"= 'ec2-public-images/fedora-core4-apache.manifest.xml' for image in rs: if image.location == img_loc:",
"= c.terminate_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have gotten an exception\")",
"these tests you should # replace this with yours or",
"== 'shutting-down' assert instance.state_code == 32 assert instance.previous_state == 'running'",
"persons to whom the Software is furnished to do so,",
"group2.owner_id, 'tcp', 22, 22) assert status # now delete the",
"# All rights reserved. # # Permission is hereby granted,",
"for g in rs: if g.name == group1_name: found =",
"testing' group2 = c.create_security_group(group2_name, group_desc) # now get a listing",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"= 'ami-bd9d78d4' demo_paid_ami_product_code = 'A79EC0DB' l = c.get_all_images([demo_paid_ami_id]) assert len(l)",
"'test-%d' % int(time.time()) group_desc = 'This is a security group",
"dry_run=True ) self.fail(\"Should have gotten an exception\") except EC2ResponseError, e:",
"# lowing conditions: # # The above copyright notice and",
"runnable by everyone status = image.set_launch_permissions(group_names=['all']) assert status d =",
"copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell",
"OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT",
"group_desc) time.sleep(2) group2_name = 'test-%d' % int(time.time()) group_desc = 'This",
"all copies or substantial portions of the Software. # #",
"testing' group1 = c.create_security_group(group1_name, group_desc) time.sleep(2) group2_name = 'test-%d' %",
"to telnet to port 80 t = telnetlib.Telnet() try: t.open(instance.dns_name,",
"assert len(d['groups']) > 0 # now remove that permission status",
"= c.get_all_security_groups() found = False for g in rs: if",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL",
"time.sleep(2) group2_name = 'test-%d' % int(time.time()) group_desc = 'This is",
") self.fail(\"Should have gotten an exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg",
"# now delete the second security group status = c.delete_security_group(group2_name)",
"(c) 2006-2010 <NAME> http://garnaat.org/ # Copyright (c) 2009, Eucalyptus Systems,",
"rs = c.get_all_images() img_loc = 'ec2-public-images/fedora-core4-apache.manifest.xml' for image in rs:",
"including # without limitation the rights to use, copy, modify,",
"c.create_security_group(group1_name, group_desc) time.sleep(2) group2_name = 'test-%d' % int(time.time()) group_desc =",
"!= 'running': print '\\tinstance is %s' % instance.state time.sleep(30) instance.update()",
"# without limitation the rights to use, copy, modify, merge,",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"assert instance.previous_state == 'running' assert instance.previous_state_code == 16 # unfortunately,",
"in rs: if k.name == key_name: found = True assert",
"> 0 # now remove that permission status = image.remove_launch_permissions(group_names=['all'])",
"try: rs = c.stop_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have gotten",
"assert status d = image.get_launch_permissions() assert 'groups' in d assert",
"'A79EC0DB' l = c.get_all_images([demo_paid_ami_id]) assert len(l) == 1 assert len(l[0].product_codes)",
"# unfortunately, I can't delete the sg within this script",
"EC2Connection \"\"\" import unittest import time import telnetlib import socket",
"EC2Connection tests ---' c = EC2Connection() # get list of",
"actual instance for the rest of this... rs = c.run_instances(",
"t.open(instance.dns_name, 80) t.close() # now revoke authorization and try again",
"status = image.set_launch_permissions(group_names=['all']) assert status d = image.get_launch_permissions() assert 'groups'",
"really gone rs = c.get_all_security_groups() found = False for g",
"try: rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small', dry_run=True ) self.fail(\"Should have",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT #",
"= c.get_all_images() img_loc = 'ec2-public-images/fedora-core4-apache.manifest.xml' for image in rs: if",
"c.get_all_images() img_loc = 'ec2-public-images/fedora-core4-apache.manifest.xml' for image in rs: if image.location",
"= 'A79EC0DB' l = c.get_all_images([demo_paid_ami_id]) assert len(l) == 1 assert",
"rs = c.terminate_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have gotten an",
"found = False for g in rs: if g.name ==",
"an exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) try: rs",
"telnetlib import socket from nose.plugins.attrib import attr from boto.ec2.connection import",
"EC2Connection from boto.exception import EC2ResponseError class EC2ConnectionTest(unittest.TestCase): ec2 = True",
"EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM,",
"exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) try: rs =",
"try: rs = c.get_all_images(dry_run=True) self.fail(\"Should have gotten an exception\") except",
"image.location == img_loc: break reservation = image.run(security_groups=[group.name]) instance = reservation.instances[0]",
"create 2 new security groups c = EC2Connection() group1_name =",
"a security group created during unit testing' group1 = c.create_security_group(group1_name,",
"Software, and to permit # persons to whom the Software",
"now delete the key pair status = c.delete_key_pair(key_name) # now",
"in now running, try to telnet to port 80 t",
"Software without restriction, including # without limitation the rights to",
"exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) # Need an",
"found # now pass arg to filter results to only",
"except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) # And kill it.",
"e: self.assertTrue(dry_run_msg in str(e)) try: rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small',",
"instance.state time.sleep(30) instance.update() # instance in now running, try to",
"(the # \"Software\"), to deal in the Software without restriction,",
"# The above copyright notice and this permission notice shall",
"int(time.time()) status = c.create_key_pair(key_name) assert status # now get a",
"= image.set_launch_permissions(group_names=['all']) assert status d = image.get_launch_permissions() assert 'groups' in",
"OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT,",
"= EC2Connection() group1_name = 'test-%d' % int(time.time()) group_desc = 'This",
"assert not found group = group1 # now try to",
"instance = reservation.instances[0] while instance.state != 'running': print '\\tinstance is",
"80) except socket.error: pass # now kill the instance and",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"delete the sg within this script #sg.delete() # create a",
"would have succeeded, but DryRun flag is set.' try: rs",
"# create a new key pair key_name = 'test-%d' %",
"1 # try some group to group authorizations/revocations # first",
"instance and delete the security group instance.terminate() # check that",
"import time import telnetlib import socket from nose.plugins.attrib import attr",
"c.get_all_security_groups() found = False for g in rs: if g.name",
"EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) try: rs = c.run_instances( image_id='ami-a0cd60c9',",
"c.terminate_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have gotten an exception\") except",
"in the Software without restriction, including # without limitation the",
"AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER",
"want to run these tests you should # replace this",
"= 'This is a security group created during unit testing'",
"an exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) # And",
"merge, publish, dis- # tribute, sublicense, and/or sell copies of",
"of this software and associated documentation files (the # \"Software\"),",
"publish, dis- # tribute, sublicense, and/or sell copies of the",
"e: self.assertTrue(dry_run_msg in str(e)) # Need an actual instance for",
"EC2Connection() # get list of private AMI's rs = c.get_all_images(owners=[user_id])",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"now pick the first one image = rs[0] # temporarily",
"2 new security groups c = EC2Connection() group1_name = 'test-%d'",
"notice and this permission notice shall be included # in",
"of charge, to any person obtaining a # copy of",
"to only our new group rs = c.get_all_security_groups([group1_name]) assert len(rs)",
"first try the old style status = c.authorize_security_group(group1.name, group2.name, group2.owner_id)",
"in str(e)) try: rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small', dry_run=True )",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS #",
"EC2Connection() group1_name = 'test-%d' % int(time.time()) group_desc = 'This is",
"furnished to do so, subject to the fol- # lowing",
"= rs[0] # temporarily make this image runnable by everyone",
"Some unit tests for the EC2Connection \"\"\" import unittest import",
"rs: if g.name == group2_name: found = True assert not",
"True assert found # now pass arg to filter results",
"new key pair key_name = 'test-%d' % int(time.time()) status =",
"conditions: # # The above copyright notice and this permission",
"'Request would have succeeded, but DryRun flag is set.' try:",
"rights to use, copy, modify, merge, publish, dis- # tribute,",
"2009, Eucalyptus Systems, Inc. # All rights reserved. # #",
"rs = c.get_all_key_pairs() found = False for k in rs:",
"EC2ResponseError class EC2ConnectionTest(unittest.TestCase): ec2 = True @attr('notdefault') def test_launch_permissions(self): #",
"in d assert len(d['groups']) > 0 # now remove that",
"image.get_launch_permissions() assert 'groups' in d assert len(d['groups']) > 0 #",
"time.sleep(30) instance.update() # instance in now running, try to telnet",
"our new one rs = c.get_all_key_pairs() found = False for",
"this with yours or they won't work user_id = '963068290131'",
"some group to group authorizations/revocations # first try the old",
"should work group.authorize('tcp', 80, 80, '0.0.0.0/0') t.open(instance.dns_name, 80) t.close() #",
"EC2Connection() dry_run_msg = 'Request would have succeeded, but DryRun flag",
"32 assert instance.previous_state == 'running' assert instance.previous_state_code == 16 #",
"ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED",
"copies of the Software, and to permit # persons to",
"unittest import time import telnetlib import socket from nose.plugins.attrib import",
"# in all copies or substantial portions of the Software.",
"sure it's really gone rs = c.get_all_key_pairs() found = False",
"c.revoke_security_group(group1.name, group2.name, group2.owner_id) assert status # now try specifying a",
"80) except socket.error: pass # now open up port 80",
"instance.previous_state_code == 16 # unfortunately, I can't delete the sg",
"of this... rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small' ) time.sleep(120) try:",
"our new group rs = c.get_all_security_groups([group1_name]) assert len(rs) == 1",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED,",
"rs = c.get_all_images(dry_run=True) self.fail(\"Should have gotten an exception\") except EC2ResponseError,",
"check that state and previous_state have updated assert instance.state ==",
"KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"test_launch_permissions(self): # this is my user_id, if you want to",
"should # replace this with yours or they won't work",
"c.get_all_security_groups([group1_name]) assert len(rs) == 1 # try some group to",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING",
"# IN THE SOFTWARE. \"\"\" Some unit tests for the",
"and look for our new one rs = c.get_all_security_groups() found",
"= True assert found # now pass arg to filter",
"really gone rs = c.get_all_key_pairs() found = False for k",
"charge, to any person obtaining a # copy of this",
"assert found # now pass arg to filter results to",
"copy of this software and associated documentation files (the #",
"now running, try to telnet to port 80 t =",
"image_id='ami-a0cd60c9', instance_type='m1.small', dry_run=True ) self.fail(\"Should have gotten an exception\") except",
"(c) 2009, Eucalyptus Systems, Inc. # All rights reserved. #",
"but DryRun flag is set.' try: rs = c.get_all_images(dry_run=True) self.fail(\"Should",
"to filter results to only our new key pair rs",
"and try again group.revoke('tcp', 80, 80, '0.0.0.0/0') try: t.open(instance.dns_name, 80)",
"security group created during unit testing' group2 = c.create_security_group(group2_name, group_desc)",
"rs: if g.name == group1_name: found = True assert found",
"work group.authorize('tcp', 80, 80, '0.0.0.0/0') t.open(instance.dns_name, 80) t.close() # now",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR",
"this image runnable by everyone status = image.set_launch_permissions(group_names=['all']) assert status",
"80, 80, '0.0.0.0/0') t.open(instance.dns_name, 80) t.close() # now revoke authorization",
"'running' assert instance.previous_state_code == 16 # unfortunately, I can't delete",
"if k.name == key_name: found = True assert found #",
"status = c.delete_security_group(group2_name) # now make sure it's really gone",
"a # copy of this software and associated documentation files",
"pair status = c.delete_key_pair(key_name) # now make sure it's really",
"person obtaining a # copy of this software and associated",
"is hereby granted, free of charge, to any person obtaining",
"int(time.time()) group_desc = 'This is a security group created during",
"and this permission notice shall be included # in all",
"c.stop_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have gotten an exception\") except",
"'tcp', 22, 22) assert status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id,",
"not in d def test_1_basic(self): # create 2 new security",
"group2.name, group2.owner_id, 'tcp', 22, 22) assert status # now delete",
"from boto.exception import EC2ResponseError class EC2ConnectionTest(unittest.TestCase): ec2 = True @attr('notdefault')",
"instance_type='m1.small' ) time.sleep(120) try: rs = c.stop_instances( instance_ids=[rs.instances[0].id], dry_run=True )",
"group2.owner_id) assert status # now try specifying a specific port",
"# try some group to group authorizations/revocations # first try",
"% int(time.time()) status = c.create_key_pair(key_name) assert status # now get",
"security groups and look for our new one rs =",
"# now pass arg to filter results to only our",
"up port 80 and try again, it should work group.authorize('tcp',",
"is set.' try: rs = c.get_all_images(dry_run=True) self.fail(\"Should have gotten an",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"running, try to telnet to port 80 t = telnetlib.Telnet()",
"assert status # now try specifying a specific port status",
"specifying a specific port status = c.authorize_security_group(group1.name, group2.name, group2.owner_id, 'tcp',",
"img_loc = 'ec2-public-images/fedora-core4-apache.manifest.xml' for image in rs: if image.location ==",
"Inc. # All rights reserved. # # Permission is hereby",
"# # Permission is hereby granted, free of charge, to",
"c = EC2Connection() group1_name = 'test-%d' % int(time.time()) group_desc =",
"assert l[0].product_codes[0] == demo_paid_ami_product_code print '--- tests completed ---' def",
"rest of this... rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small' ) time.sleep(120)",
"status # now delete the second security group status =",
"self.assertTrue(dry_run_msg in str(e)) try: rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small', dry_run=True",
"look for our new one rs = c.get_all_security_groups() found =",
"now remove that permission status = image.remove_launch_permissions(group_names=['all']) assert status time.sleep(10)",
"'0.0.0.0/0') t.open(instance.dns_name, 80) t.close() # now revoke authorization and try",
"by everyone status = image.set_launch_permissions(group_names=['all']) assert status d = image.get_launch_permissions()",
"80 and try again, it should work group.authorize('tcp', 80, 80,",
"assert not found # short test around Paid AMI capability",
"with yours or they won't work user_id = '963068290131' print",
"AMI capability demo_paid_ami_id = 'ami-bd9d78d4' demo_paid_ami_product_code = 'A79EC0DB' l =",
"image with our new security group rs = c.get_all_images() img_loc",
"DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF",
"not found # short test around Paid AMI capability demo_paid_ami_id",
"is %s' % instance.state time.sleep(30) instance.update() # instance in now",
"c.get_all_images(owners=[user_id]) assert len(rs) > 0 # now pick the first",
"group1 = c.create_security_group(group1_name, group_desc) time.sleep(2) group2_name = 'test-%d' % int(time.time())",
"apache image with our new security group rs = c.get_all_images()",
"demo_paid_ami_product_code = 'A79EC0DB' l = c.get_all_images([demo_paid_ami_id]) assert len(l) == 1",
"this... rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small' ) time.sleep(120) try: rs",
"print '\\tinstance is %s' % instance.state time.sleep(30) instance.update() # instance",
"the key pair status = c.delete_key_pair(key_name) # now make sure",
"status = c.revoke_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22) assert status",
"image.run(security_groups=[group.name]) instance = reservation.instances[0] while instance.state != 'running': print '\\tinstance",
"and associated documentation files (the # \"Software\"), to deal in",
"or substantial portions of the Software. # # THE SOFTWARE",
"g.name == group1_name: found = True assert found # now",
"time import telnetlib import socket from nose.plugins.attrib import attr from",
"security group rs = c.get_all_images() img_loc = 'ec2-public-images/fedora-core4-apache.manifest.xml' for image",
"key pair status = c.delete_key_pair(key_name) # now make sure it's",
"import unittest import time import telnetlib import socket from nose.plugins.attrib",
"# now get a listing of all key pairs and",
"assert status # now delete the second security group status",
"except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) try: rs = c.terminate_instances(",
"granted, free of charge, to any person obtaining a #",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"image = rs[0] # temporarily make this image runnable by",
"0 # now remove that permission status = image.remove_launch_permissions(group_names=['all']) assert",
"one image = rs[0] # temporarily make this image runnable",
"group2.name, group2.owner_id) assert status # now try specifying a specific",
"break reservation = image.run(security_groups=[group.name]) instance = reservation.instances[0] while instance.state !=",
"rights reserved. # # Permission is hereby granted, free of",
"# Copyright (c) 2009, Eucalyptus Systems, Inc. # All rights",
"from nose.plugins.attrib import attr from boto.ec2.connection import EC2Connection from boto.exception",
"rs[0] # temporarily make this image runnable by everyone status",
"listing of all key pairs and look for our new",
"found group = group1 # now try to launch apache",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"reserved. # # Permission is hereby granted, free of charge,",
"= c.get_all_key_pairs([key_name]) assert len(rs) == 1 key_pair = rs[0] #",
"status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id) assert status # now",
"str(e)) # Need an actual instance for the rest of",
"found = True assert not found # short test around",
"c.authorize_security_group(group1.name, group2.name, group2.owner_id) assert status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id)",
"% instance.state time.sleep(30) instance.update() # instance in now running, try",
"# Permission is hereby granted, free of charge, to any",
"WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE",
"assert status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id) assert status #",
"fol- # lowing conditions: # # The above copyright notice",
"pick the first one image = rs[0] # temporarily make",
"image.set_launch_permissions(group_names=['all']) assert status d = image.get_launch_permissions() assert 'groups' in d",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"instance in now running, try to telnet to port 80",
"'\\tinstance is %s' % instance.state time.sleep(30) instance.update() # instance in",
"pass arg to filter results to only our new group",
"IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR",
"pair key_name = 'test-%d' % int(time.time()) status = c.create_key_pair(key_name) assert",
"assert instance.state == 'shutting-down' assert instance.state_code == 32 assert instance.previous_state",
"# now kill the instance and delete the security group",
"without limitation the rights to use, copy, modify, merge, publish,",
"'test-%d' % int(time.time()) status = c.create_key_pair(key_name) assert status # now",
"Copyright (c) 2009, Eucalyptus Systems, Inc. # All rights reserved.",
"l = c.get_all_images([demo_paid_ami_id]) assert len(l) == 1 assert len(l[0].product_codes) ==",
"time.sleep(120) try: rs = c.stop_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have",
"now try specifying a specific port status = c.authorize_security_group(group1.name, group2.name,",
"= EC2Connection() dry_run_msg = 'Request would have succeeded, but DryRun",
"the old style status = c.authorize_security_group(group1.name, group2.name, group2.owner_id) assert status",
"c.get_all_key_pairs([key_name]) assert len(rs) == 1 key_pair = rs[0] # now",
"for the rest of this... rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small'",
"# now make sure it's really gone rs = c.get_all_key_pairs()",
"rs[0] # now delete the key pair status = c.delete_key_pair(key_name)",
"set.' try: rs = c.get_all_images(dry_run=True) self.fail(\"Should have gotten an exception\")",
"obtaining a # copy of this software and associated documentation",
"telnet to port 80 t = telnetlib.Telnet() try: t.open(instance.dns_name, 80)",
"new one rs = c.get_all_security_groups() found = False for g",
"won't work user_id = '963068290131' print '--- running EC2Connection tests",
"c.get_all_key_pairs() found = False for k in rs: if k.name",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small', dry_run=True ) self.fail(\"Should have gotten an exception\")",
"the first one image = rs[0] # temporarily make this",
"it should work group.authorize('tcp', 80, 80, '0.0.0.0/0') t.open(instance.dns_name, 80) t.close()",
"found = True assert found # now pass arg to",
"= telnetlib.Telnet() try: t.open(instance.dns_name, 80) except socket.error: pass # now",
"import telnetlib import socket from nose.plugins.attrib import attr from boto.ec2.connection",
"SOFTWARE. \"\"\" Some unit tests for the EC2Connection \"\"\" import",
"our new security group rs = c.get_all_images() img_loc = 'ec2-public-images/fedora-core4-apache.manifest.xml'",
"str(e)) try: rs = c.terminate_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have",
"get a listing of all security groups and look for",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"= c.revoke_security_group(group1.name, group2.name, group2.owner_id) assert status # now try specifying",
"image runnable by everyone status = image.set_launch_permissions(group_names=['all']) assert status d",
"group status = c.delete_security_group(group2_name) # now make sure it's really",
"len(rs) == 1 key_pair = rs[0] # now delete the",
"succeeded, but DryRun flag is set.' try: rs = c.get_all_images(dry_run=True)",
"only our new key pair rs = c.get_all_key_pairs([key_name]) assert len(rs)",
"run these tests you should # replace this with yours",
"except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) try: rs = c.run_instances(",
"status = c.revoke_security_group(group1.name, group2.name, group2.owner_id) assert status # now try",
"rs: if image.location == img_loc: break reservation = image.run(security_groups=[group.name]) instance",
"True @attr('notdefault') def test_launch_permissions(self): # this is my user_id, if",
"to group authorizations/revocations # first try the old style status",
"assert instance.state_code == 32 assert instance.previous_state == 'running' assert instance.previous_state_code",
"make this image runnable by everyone status = image.set_launch_permissions(group_names=['all']) assert",
"rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small' ) time.sleep(120) try: rs =",
"== key_name: found = True assert not found # short",
"now pass arg to filter results to only our new",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"= image.run(security_groups=[group.name]) instance = reservation.instances[0] while instance.state != 'running': print",
"d = image.get_launch_permissions() assert 'groups' in d assert len(d['groups']) >",
"for our new one rs = c.get_all_key_pairs() found = False",
"== demo_paid_ami_product_code print '--- tests completed ---' def test_dry_run(self): c",
"DryRun flag is set.' try: rs = c.get_all_images(dry_run=True) self.fail(\"Should have",
"to any person obtaining a # copy of this software",
"it's really gone rs = c.get_all_security_groups() found = False for",
"# \"Software\"), to deal in the Software without restriction, including",
"socket from nose.plugins.attrib import attr from boto.ec2.connection import EC2Connection from",
"launch apache image with our new security group rs =",
"for k in rs: if k.name == key_name: found =",
"delete the key pair status = c.delete_key_pair(key_name) # now make",
"False for g in rs: if g.name == group2_name: found",
"THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR",
"# copy of this software and associated documentation files (the",
"# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"now make sure it's really gone rs = c.get_all_key_pairs() found",
"group rs = c.get_all_images() img_loc = 'ec2-public-images/fedora-core4-apache.manifest.xml' for image in",
"True assert not found group = group1 # now try",
"import socket from nose.plugins.attrib import attr from boto.ec2.connection import EC2Connection",
"have succeeded, but DryRun flag is set.' try: rs =",
"# temporarily make this image runnable by everyone status =",
"THE USE OR OTHER DEALINGS # IN THE SOFTWARE. \"\"\"",
"= image.get_launch_permissions() assert 'groups' not in d def test_1_basic(self): #",
"# create 2 new security groups c = EC2Connection() group1_name",
"copyright notice and this permission notice shall be included #",
"'groups' not in d def test_1_basic(self): # create 2 new",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN",
"g in rs: if g.name == group2_name: found = True",
"assert len(l) == 1 assert len(l[0].product_codes) == 1 assert l[0].product_codes[0]",
"instance.state != 'running': print '\\tinstance is %s' % instance.state time.sleep(30)",
"k in rs: if k.name == key_name: found = True",
"key_name = 'test-%d' % int(time.time()) status = c.create_key_pair(key_name) assert status",
"an actual instance for the rest of this... rs =",
"Systems, Inc. # All rights reserved. # # Permission is",
"status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22) assert",
"previous_state have updated assert instance.state == 'shutting-down' assert instance.state_code ==",
"and try again, it should work group.authorize('tcp', 80, 80, '0.0.0.0/0')",
"test_1_basic(self): # create 2 new security groups c = EC2Connection()",
"a new key pair key_name = 'test-%d' % int(time.time()) status",
"test_dry_run(self): c = EC2Connection() dry_run_msg = 'Request would have succeeded,",
"to whom the Software is furnished to do so, subject",
"gone rs = c.get_all_security_groups() found = False for g in",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"status = image.remove_launch_permissions(group_names=['all']) assert status time.sleep(10) d = image.get_launch_permissions() assert",
"do so, subject to the fol- # lowing conditions: #",
"sell copies of the Software, and to permit # persons",
"state and previous_state have updated assert instance.state == 'shutting-down' assert",
"work user_id = '963068290131' print '--- running EC2Connection tests ---'",
"= c.get_all_images(dry_run=True) self.fail(\"Should have gotten an exception\") except EC2ResponseError, e:",
"reservation.instances[0] while instance.state != 'running': print '\\tinstance is %s' %",
"notice shall be included # in all copies or substantial",
"image_id='ami-a0cd60c9', instance_type='m1.small' ) time.sleep(120) try: rs = c.stop_instances( instance_ids=[rs.instances[0].id], dry_run=True",
"'running': print '\\tinstance is %s' % instance.state time.sleep(30) instance.update() #",
"SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE",
"pass # now kill the instance and delete the security",
"# now delete the key pair status = c.delete_key_pair(key_name) #",
"authorization and try again group.revoke('tcp', 80, 80, '0.0.0.0/0') try: t.open(instance.dns_name,",
"user_id = '963068290131' print '--- running EC2Connection tests ---' c",
"image.remove_launch_permissions(group_names=['all']) assert status time.sleep(10) d = image.get_launch_permissions() assert 'groups' not",
"now get a listing of all security groups and look",
"l[0].product_codes[0] == demo_paid_ami_product_code print '--- tests completed ---' def test_dry_run(self):",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"t.open(instance.dns_name, 80) except socket.error: pass # now open up port",
"group2.owner_id) assert status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id) assert status",
"80) t.close() # now revoke authorization and try again group.revoke('tcp',",
"group2.name, group2.owner_id) assert status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id) assert",
"you want to run these tests you should # replace",
"you should # replace this with yours or they won't",
"== key_name: found = True assert found # now pass",
"results to only our new key pair rs = c.get_all_key_pairs([key_name])",
"tests ---' c = EC2Connection() # get list of private",
"assert len(rs) == 1 key_pair = rs[0] # now delete",
"get list of private AMI's rs = c.get_all_images(owners=[user_id]) assert len(rs)",
"during unit testing' group1 = c.create_security_group(group1_name, group_desc) time.sleep(2) group2_name =",
"that permission status = image.remove_launch_permissions(group_names=['all']) assert status time.sleep(10) d =",
"status # now try specifying a specific port status =",
"have updated assert instance.state == 'shutting-down' assert instance.state_code == 32",
"around Paid AMI capability demo_paid_ami_id = 'ami-bd9d78d4' demo_paid_ami_product_code = 'A79EC0DB'",
"# now open up port 80 and try again, it",
"look for our new one rs = c.get_all_key_pairs() found =",
"= image.remove_launch_permissions(group_names=['all']) assert status time.sleep(10) d = image.get_launch_permissions() assert 'groups'",
"img_loc: break reservation = image.run(security_groups=[group.name]) instance = reservation.instances[0] while instance.state",
"this is my user_id, if you want to run these",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE",
"# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES",
"image in rs: if image.location == img_loc: break reservation =",
"security group instance.terminate() # check that state and previous_state have",
"= c.get_all_images(owners=[user_id]) assert len(rs) > 0 # now pick the",
"if g.name == group1_name: found = True assert found #",
"80 t = telnetlib.Telnet() try: t.open(instance.dns_name, 80) except socket.error: pass",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"filter results to only our new group rs = c.get_all_security_groups([group1_name])",
"substantial portions of the Software. # # THE SOFTWARE IS",
"= c.get_all_security_groups([group1_name]) assert len(rs) == 1 # try some group",
"try: rs = c.terminate_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have gotten",
"= c.create_security_group(group2_name, group_desc) # now get a listing of all",
"security group status = c.delete_security_group(group2_name) # now make sure it's",
"kill the instance and delete the security group instance.terminate() #",
"and/or sell copies of the Software, and to permit #",
"'--- tests completed ---' def test_dry_run(self): c = EC2Connection() dry_run_msg",
"tribute, sublicense, and/or sell copies of the Software, and to",
"assert status # now get a listing of all key",
"our new key pair rs = c.get_all_key_pairs([key_name]) assert len(rs) ==",
"found = False for k in rs: if k.name ==",
"the sg within this script #sg.delete() # create a new",
"# tribute, sublicense, and/or sell copies of the Software, and",
"key_pair = rs[0] # now delete the key pair status",
"pairs and look for our new one rs = c.get_all_key_pairs()",
"== 16 # unfortunately, I can't delete the sg within",
"make sure it's really gone rs = c.get_all_key_pairs() found =",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"tests for the EC2Connection \"\"\" import unittest import time import",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"try: t.open(instance.dns_name, 80) except socket.error: pass # now open up",
"t.open(instance.dns_name, 80) except socket.error: pass # now kill the instance",
"e: self.assertTrue(dry_run_msg in str(e)) try: rs = c.terminate_instances( instance_ids=[rs.instances[0].id], dry_run=True",
"with our new security group rs = c.get_all_images() img_loc =",
"THE SOFTWARE. \"\"\" Some unit tests for the EC2Connection \"\"\"",
"t = telnetlib.Telnet() try: t.open(instance.dns_name, 80) except socket.error: pass #",
"it's really gone rs = c.get_all_key_pairs() found = False for",
"rs = c.stop_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have gotten an",
"#sg.delete() # create a new key pair key_name = 'test-%d'",
"instance.terminate() # check that state and previous_state have updated assert",
"exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) # And kill",
"= c.get_all_key_pairs() found = False for k in rs: if",
"True assert not found # short test around Paid AMI",
"try the old style status = c.authorize_security_group(group1.name, group2.name, group2.owner_id) assert",
"import attr from boto.ec2.connection import EC2Connection from boto.exception import EC2ResponseError",
"try some group to group authorizations/revocations # first try the",
"c.authorize_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22) assert status status =",
"gone rs = c.get_all_key_pairs() found = False for k in",
"for image in rs: if image.location == img_loc: break reservation",
"EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) # And kill it. rs.instances[0].terminate()",
"updated assert instance.state == 'shutting-down' assert instance.state_code == 32 assert",
"== 1 # try some group to group authorizations/revocations #",
"---' c = EC2Connection() # get list of private AMI's",
"import EC2ResponseError class EC2ConnectionTest(unittest.TestCase): ec2 = True @attr('notdefault') def test_launch_permissions(self):",
"= True assert not found group = group1 # now",
"to port 80 t = telnetlib.Telnet() try: t.open(instance.dns_name, 80) except",
"Eucalyptus Systems, Inc. # All rights reserved. # # Permission",
"0 # now pick the first one image = rs[0]",
"arg to filter results to only our new group rs",
"group instance.terminate() # check that state and previous_state have updated",
"try again group.revoke('tcp', 80, 80, '0.0.0.0/0') try: t.open(instance.dns_name, 80) except",
"new key pair rs = c.get_all_key_pairs([key_name]) assert len(rs) == 1",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN",
"private AMI's rs = c.get_all_images(owners=[user_id]) assert len(rs) > 0 #",
"instance for the rest of this... rs = c.run_instances( image_id='ami-a0cd60c9',",
"capability demo_paid_ami_id = 'ami-bd9d78d4' demo_paid_ami_product_code = 'A79EC0DB' l = c.get_all_images([demo_paid_ami_id])",
"pass # now open up port 80 and try again,",
"assert 'groups' in d assert len(d['groups']) > 0 # now",
"try specifying a specific port status = c.authorize_security_group(group1.name, group2.name, group2.owner_id,",
"if you want to run these tests you should #",
"can't delete the sg within this script #sg.delete() # create",
"this software and associated documentation files (the # \"Software\"), to",
"and look for our new one rs = c.get_all_key_pairs() found",
"dry_run_msg = 'Request would have succeeded, but DryRun flag is",
"instance.state == 'shutting-down' assert instance.state_code == 32 assert instance.previous_state ==",
"unit testing' group1 = c.create_security_group(group1_name, group_desc) time.sleep(2) group2_name = 'test-%d'",
"# this is my user_id, if you want to run",
"assert len(rs) == 1 # try some group to group",
"port status = c.authorize_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22) assert",
"Copyright (c) 2006-2010 <NAME> http://garnaat.org/ # Copyright (c) 2009, Eucalyptus",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"c.create_security_group(group2_name, group_desc) # now get a listing of all security",
"not found group = group1 # now try to launch",
"status = c.create_key_pair(key_name) assert status # now get a listing",
"str(e)) try: rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small', dry_run=True ) self.fail(\"Should",
"delete the second security group status = c.delete_security_group(group2_name) # now",
"EC2ConnectionTest(unittest.TestCase): ec2 = True @attr('notdefault') def test_launch_permissions(self): # this is",
"group2.name, group2.owner_id, 'tcp', 22, 22) assert status status = c.revoke_security_group(group1.name,",
"c.get_all_images([demo_paid_ami_id]) assert len(l) == 1 assert len(l[0].product_codes) == 1 assert",
"limitation the rights to use, copy, modify, merge, publish, dis-",
"status = c.authorize_security_group(group1.name, group2.name, group2.owner_id) assert status status = c.revoke_security_group(group1.name,",
"self.fail(\"Should have gotten an exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in",
"OTHER DEALINGS # IN THE SOFTWARE. \"\"\" Some unit tests",
"whom the Software is furnished to do so, subject to",
"'ami-bd9d78d4' demo_paid_ami_product_code = 'A79EC0DB' l = c.get_all_images([demo_paid_ami_id]) assert len(l) ==",
"except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) # Need an actual",
"key pair key_name = 'test-%d' % int(time.time()) status = c.create_key_pair(key_name)",
"<NAME> http://garnaat.org/ # Copyright (c) 2009, Eucalyptus Systems, Inc. #",
"c = EC2Connection() # get list of private AMI's rs",
"'This is a security group created during unit testing' group1",
"= False for g in rs: if g.name == group2_name:",
"\"\"\" Some unit tests for the EC2Connection \"\"\" import unittest",
"within this script #sg.delete() # create a new key pair",
"nose.plugins.attrib import attr from boto.ec2.connection import EC2Connection from boto.exception import",
"I can't delete the sg within this script #sg.delete() #",
"== 1 assert len(l[0].product_codes) == 1 assert l[0].product_codes[0] == demo_paid_ami_product_code",
"boto.ec2.connection import EC2Connection from boto.exception import EC2ResponseError class EC2ConnectionTest(unittest.TestCase): ec2",
"a listing of all security groups and look for our",
"= c.get_all_images([demo_paid_ami_id]) assert len(l) == 1 assert len(l[0].product_codes) == 1",
"# persons to whom the Software is furnished to do",
"# now make sure it's really gone rs = c.get_all_security_groups()",
"len(l) == 1 assert len(l[0].product_codes) == 1 assert l[0].product_codes[0] ==",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR",
"'This is a security group created during unit testing' group2",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"d assert len(d['groups']) > 0 # now remove that permission",
"files (the # \"Software\"), to deal in the Software without",
"the second security group status = c.delete_security_group(group2_name) # now make",
"documentation files (the # \"Software\"), to deal in the Software",
"group2_name: found = True assert not found group = group1",
"self.assertTrue(dry_run_msg in str(e)) try: rs = c.terminate_instances( instance_ids=[rs.instances[0].id], dry_run=True )",
"def test_launch_permissions(self): # this is my user_id, if you want",
"sublicense, and/or sell copies of the Software, and to permit",
"len(l[0].product_codes) == 1 assert l[0].product_codes[0] == demo_paid_ami_product_code print '--- tests",
"the Software, and to permit # persons to whom the",
"# now remove that permission status = image.remove_launch_permissions(group_names=['all']) assert status",
"22) assert status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22,",
"ec2 = True @attr('notdefault') def test_launch_permissions(self): # this is my",
"remove that permission status = image.remove_launch_permissions(group_names=['all']) assert status time.sleep(10) d",
"unfortunately, I can't delete the sg within this script #sg.delete()",
"EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) try: rs = c.terminate_instances( instance_ids=[rs.instances[0].id],",
"delete the security group instance.terminate() # check that state and",
"now kill the instance and delete the security group instance.terminate()",
"False for k in rs: if k.name == key_name: found",
"http://garnaat.org/ # Copyright (c) 2009, Eucalyptus Systems, Inc. # All",
"for the EC2Connection \"\"\" import unittest import time import telnetlib",
"== group1_name: found = True assert found # now pass",
"group to group authorizations/revocations # first try the old style",
"so, subject to the fol- # lowing conditions: # #",
"pair rs = c.get_all_key_pairs([key_name]) assert len(rs) == 1 key_pair =",
"= c.delete_security_group(group2_name) # now make sure it's really gone rs",
"'0.0.0.0/0') try: t.open(instance.dns_name, 80) except socket.error: pass # now kill",
"temporarily make this image runnable by everyone status = image.set_launch_permissions(group_names=['all'])",
"def test_dry_run(self): c = EC2Connection() dry_run_msg = 'Request would have",
"of all key pairs and look for our new one",
"of all security groups and look for our new one",
"reservation = image.run(security_groups=[group.name]) instance = reservation.instances[0] while instance.state != 'running':",
"be included # in all copies or substantial portions of",
"except socket.error: pass # now open up port 80 and",
"port 80 and try again, it should work group.authorize('tcp', 80,",
"demo_paid_ami_product_code print '--- tests completed ---' def test_dry_run(self): c =",
"boto.exception import EC2ResponseError class EC2ConnectionTest(unittest.TestCase): ec2 = True @attr('notdefault') def",
"= 'Request would have succeeded, but DryRun flag is set.'",
"the rights to use, copy, modify, merge, publish, dis- #",
"False for g in rs: if g.name == group1_name: found",
"of the Software, and to permit # persons to whom",
"\"\"\" import unittest import time import telnetlib import socket from",
"specific port status = c.authorize_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22)",
"to launch apache image with our new security group rs",
"new security group rs = c.get_all_images() img_loc = 'ec2-public-images/fedora-core4-apache.manifest.xml' for",
"in rs: if image.location == img_loc: break reservation = image.run(security_groups=[group.name])",
"one rs = c.get_all_key_pairs() found = False for k in",
"and to permit # persons to whom the Software is",
"subject to the fol- # lowing conditions: # # The",
"above copyright notice and this permission notice shall be included",
"# Copyright (c) 2006-2010 <NAME> http://garnaat.org/ # Copyright (c) 2009,",
"= group1 # now try to launch apache image with",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- #",
"all security groups and look for our new one rs",
"security groups c = EC2Connection() group1_name = 'test-%d' % int(time.time())",
"new one rs = c.get_all_key_pairs() found = False for k",
"replace this with yours or they won't work user_id =",
"'ec2-public-images/fedora-core4-apache.manifest.xml' for image in rs: if image.location == img_loc: break",
"now open up port 80 and try again, it should",
"LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"everyone status = image.set_launch_permissions(group_names=['all']) assert status d = image.get_launch_permissions() assert",
"except socket.error: pass # now kill the instance and delete",
"status # now get a listing of all key pairs",
"gotten an exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) #",
"and delete the security group instance.terminate() # check that state",
"group created during unit testing' group2 = c.create_security_group(group2_name, group_desc) #",
"one rs = c.get_all_security_groups() found = False for g in",
"k.name == key_name: found = True assert not found #",
"80, '0.0.0.0/0') t.open(instance.dns_name, 80) t.close() # now revoke authorization and",
"22, 22) assert status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id, 'tcp',",
"associated documentation files (the # \"Software\"), to deal in the",
"instance_type='m1.small', dry_run=True ) self.fail(\"Should have gotten an exception\") except EC2ResponseError,",
"in all copies or substantial portions of the Software. #",
"NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE",
"@attr('notdefault') def test_launch_permissions(self): # this is my user_id, if you",
"socket.error: pass # now kill the instance and delete the",
"# short test around Paid AMI capability demo_paid_ami_id = 'ami-bd9d78d4'",
"new group rs = c.get_all_security_groups([group1_name]) assert len(rs) == 1 #",
"t.close() # now revoke authorization and try again group.revoke('tcp', 80,",
"copies or substantial portions of the Software. # # THE",
"from boto.ec2.connection import EC2Connection from boto.exception import EC2ResponseError class EC2ConnectionTest(unittest.TestCase):",
"an exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) # Need",
"= c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small' ) time.sleep(120) try: rs = c.stop_instances(",
"LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR",
"to deal in the Software without restriction, including # without",
"'963068290131' print '--- running EC2Connection tests ---' c = EC2Connection()",
"the rest of this... rs = c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small' )",
"group_desc = 'This is a security group created during unit",
"for our new one rs = c.get_all_security_groups() found = False",
"lowing conditions: # # The above copyright notice and this",
"rs = c.get_all_images(owners=[user_id]) assert len(rs) > 0 # now pick",
"the security group instance.terminate() # check that state and previous_state",
"print '--- tests completed ---' def test_dry_run(self): c = EC2Connection()",
"if k.name == key_name: found = True assert not found",
"again group.revoke('tcp', 80, 80, '0.0.0.0/0') try: t.open(instance.dns_name, 80) except socket.error:",
"in rs: if g.name == group2_name: found = True assert",
"---' def test_dry_run(self): c = EC2Connection() dry_run_msg = 'Request would",
"= True @attr('notdefault') def test_launch_permissions(self): # this is my user_id,",
"% int(time.time()) group_desc = 'This is a security group created",
"TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A",
"tests you should # replace this with yours or they",
"== 1 key_pair = rs[0] # now delete the key",
"== group2_name: found = True assert not found group =",
"group = group1 # now try to launch apache image",
"socket.error: pass # now open up port 80 and try",
"my user_id, if you want to run these tests you",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"'groups' in d assert len(d['groups']) > 0 # now remove",
"= '963068290131' print '--- running EC2Connection tests ---' c =",
"in str(e)) try: rs = c.terminate_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should",
"instance.update() # instance in now running, try to telnet to",
"group1_name = 'test-%d' % int(time.time()) group_desc = 'This is a",
"found = True assert not found group = group1 #",
"THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"style status = c.authorize_security_group(group1.name, group2.name, group2.owner_id) assert status status =",
"DEALINGS # IN THE SOFTWARE. \"\"\" Some unit tests for",
"running EC2Connection tests ---' c = EC2Connection() # get list",
"to permit # persons to whom the Software is furnished",
"== img_loc: break reservation = image.run(security_groups=[group.name]) instance = reservation.instances[0] while",
"completed ---' def test_dry_run(self): c = EC2Connection() dry_run_msg = 'Request",
"a security group created during unit testing' group2 = c.create_security_group(group2_name,",
"= rs[0] # now delete the key pair status =",
"22, 22) assert status # now delete the second security",
"len(rs) == 1 # try some group to group authorizations/revocations",
"is a security group created during unit testing' group2 =",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, #",
"group authorizations/revocations # first try the old style status =",
"for g in rs: if g.name == group2_name: found =",
"if g.name == group2_name: found = True assert not found",
"# Need an actual instance for the rest of this...",
"found # short test around Paid AMI capability demo_paid_ami_id =",
"group2_name = 'test-%d' % int(time.time()) group_desc = 'This is a",
"group1 # now try to launch apache image with our",
"restriction, including # without limitation the rights to use, copy,",
"or they won't work user_id = '963068290131' print '--- running",
"filter results to only our new key pair rs =",
"assert 'groups' not in d def test_1_basic(self): # create 2",
"now make sure it's really gone rs = c.get_all_security_groups() found",
"the Software without restriction, including # without limitation the rights",
"port 80 t = telnetlib.Telnet() try: t.open(instance.dns_name, 80) except socket.error:",
"now revoke authorization and try again group.revoke('tcp', 80, 80, '0.0.0.0/0')",
"groups c = EC2Connection() group1_name = 'test-%d' % int(time.time()) group_desc",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"= EC2Connection() # get list of private AMI's rs =",
"assert len(l[0].product_codes) == 1 assert l[0].product_codes[0] == demo_paid_ami_product_code print '---",
"list of private AMI's rs = c.get_all_images(owners=[user_id]) assert len(rs) >",
"= c.stop_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have gotten an exception\")",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"d def test_1_basic(self): # create 2 new security groups c",
"the Software is furnished to do so, subject to the",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN",
"= c.revoke_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22) assert status #",
"gotten an exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg in str(e)) try:",
"is my user_id, if you want to run these tests",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY,",
"new security groups c = EC2Connection() group1_name = 'test-%d' %",
"rs = c.get_all_security_groups([group1_name]) assert len(rs) == 1 # try some",
"script #sg.delete() # create a new key pair key_name =",
"pass arg to filter results to only our new key",
"MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"assert status time.sleep(10) d = image.get_launch_permissions() assert 'groups' not in",
"'--- running EC2Connection tests ---' c = EC2Connection() # get",
"= True assert not found # short test around Paid",
"try to launch apache image with our new security group",
"# check that state and previous_state have updated assert instance.state",
"== 1 assert l[0].product_codes[0] == demo_paid_ami_product_code print '--- tests completed",
"rs: if k.name == key_name: found = True assert not",
"second security group status = c.delete_security_group(group2_name) # now make sure",
"rs = c.get_all_security_groups() found = False for g in rs:",
"import EC2Connection from boto.exception import EC2ResponseError class EC2ConnectionTest(unittest.TestCase): ec2 =",
"key_name: found = True assert not found # short test",
"all key pairs and look for our new one rs",
") time.sleep(120) try: rs = c.stop_instances( instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should",
"# get list of private AMI's rs = c.get_all_images(owners=[user_id]) assert",
"= c.create_key_pair(key_name) assert status # now get a listing of",
"arg to filter results to only our new key pair",
"= c.delete_key_pair(key_name) # now make sure it's really gone rs",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"class EC2ConnectionTest(unittest.TestCase): ec2 = True @attr('notdefault') def test_launch_permissions(self): # this",
"\"Software\"), to deal in the Software without restriction, including #",
"key pairs and look for our new one rs =",
"software and associated documentation files (the # \"Software\"), to deal",
"to use, copy, modify, merge, publish, dis- # tribute, sublicense,",
"group_desc) # now get a listing of all security groups",
"instance.previous_state == 'running' assert instance.previous_state_code == 16 # unfortunately, I",
"assert status status = c.revoke_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22)",
"sg within this script #sg.delete() # create a new key",
"attr from boto.ec2.connection import EC2Connection from boto.exception import EC2ResponseError class",
"'shutting-down' assert instance.state_code == 32 assert instance.previous_state == 'running' assert",
"permission notice shall be included # in all copies or",
"revoke authorization and try again group.revoke('tcp', 80, 80, '0.0.0.0/0') try:",
"short test around Paid AMI capability demo_paid_ami_id = 'ami-bd9d78d4' demo_paid_ami_product_code",
"try to telnet to port 80 t = telnetlib.Telnet() try:",
"All rights reserved. # # Permission is hereby granted, free",
"CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION",
"unit testing' group2 = c.create_security_group(group2_name, group_desc) # now get a",
"old style status = c.authorize_security_group(group1.name, group2.name, group2.owner_id) assert status status",
"try again, it should work group.authorize('tcp', 80, 80, '0.0.0.0/0') t.open(instance.dns_name,",
"c = EC2Connection() dry_run_msg = 'Request would have succeeded, but",
"1 assert len(l[0].product_codes) == 1 assert l[0].product_codes[0] == demo_paid_ami_product_code print",
"# now try to launch apache image with our new",
"c.get_all_images(dry_run=True) self.fail(\"Should have gotten an exception\") except EC2ResponseError, e: self.assertTrue(dry_run_msg",
"status = c.delete_key_pair(key_name) # now make sure it's really gone",
"c.run_instances( image_id='ami-a0cd60c9', instance_type='m1.small' ) time.sleep(120) try: rs = c.stop_instances( instance_ids=[rs.instances[0].id],",
"group2.owner_id, 'tcp', 22, 22) assert status status = c.revoke_security_group(group1.name, group2.name,",
"this permission notice shall be included # in all copies",
"deal in the Software without restriction, including # without limitation",
"# replace this with yours or they won't work user_id",
"try: t.open(instance.dns_name, 80) except socket.error: pass # now kill the",
"in rs: if g.name == group1_name: found = True assert",
"instance_ids=[rs.instances[0].id], dry_run=True ) self.fail(\"Should have gotten an exception\") except EC2ResponseError,",
"to only our new key pair rs = c.get_all_key_pairs([key_name]) assert",
"= 'test-%d' % int(time.time()) status = c.create_key_pair(key_name) assert status #",
"first one image = rs[0] # temporarily make this image",
"created during unit testing' group2 = c.create_security_group(group2_name, group_desc) # now",
"if image.location == img_loc: break reservation = image.run(security_groups=[group.name]) instance =",
"to do so, subject to the fol- # lowing conditions:",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"in d def test_1_basic(self): # create 2 new security groups",
"AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"1 assert l[0].product_codes[0] == demo_paid_ami_product_code print '--- tests completed ---'",
"dis- # tribute, sublicense, and/or sell copies of the Software,",
"sure it's really gone rs = c.get_all_security_groups() found = False",
"Permission is hereby granted, free of charge, to any person",
"OR OTHER DEALINGS # IN THE SOFTWARE. \"\"\" Some unit",
"c.revoke_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22) assert status # now",
"yours or they won't work user_id = '963068290131' print '---",
"OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT",
"2006-2010 <NAME> http://garnaat.org/ # Copyright (c) 2009, Eucalyptus Systems, Inc.",
"len(d['groups']) > 0 # now remove that permission status =",
"security group created during unit testing' group1 = c.create_security_group(group1_name, group_desc)",
"= c.authorize_security_group(group1.name, group2.name, group2.owner_id, 'tcp', 22, 22) assert status status",
"16 # unfortunately, I can't delete the sg within this",
"The above copyright notice and this permission notice shall be",
"only our new group rs = c.get_all_security_groups([group1_name]) assert len(rs) ==",
"group1_name: found = True assert found # now pass arg",
"and previous_state have updated assert instance.state == 'shutting-down' assert instance.state_code",
"listing of all security groups and look for our new",
"now delete the second security group status = c.delete_security_group(group2_name) #",
"instance.state_code == 32 assert instance.previous_state == 'running' assert instance.previous_state_code ==",
"def test_1_basic(self): # create 2 new security groups c =",
"SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"== 32 assert instance.previous_state == 'running' assert instance.previous_state_code == 16",
"during unit testing' group2 = c.create_security_group(group2_name, group_desc) # now get",
"permit # persons to whom the Software is furnished to",
"Software is furnished to do so, subject to the fol-",
"they won't work user_id = '963068290131' print '--- running EC2Connection",
"# now pick the first one image = rs[0] #",
"80, '0.0.0.0/0') try: t.open(instance.dns_name, 80) except socket.error: pass # now",
"modify, merge, publish, dis- # tribute, sublicense, and/or sell copies",
"OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"now get a listing of all key pairs and look",
"group rs = c.get_all_security_groups([group1_name]) assert len(rs) == 1 # try",
"group created during unit testing' group1 = c.create_security_group(group1_name, group_desc) time.sleep(2)",
"%s' % instance.state time.sleep(30) instance.update() # instance in now running,",
"results to only our new group rs = c.get_all_security_groups([group1_name]) assert",
"while instance.state != 'running': print '\\tinstance is %s' % instance.state",
"is a security group created during unit testing' group1 =",
"IN THE SOFTWARE. \"\"\" Some unit tests for the EC2Connection",
"group.authorize('tcp', 80, 80, '0.0.0.0/0') t.open(instance.dns_name, 80) t.close() # now revoke",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"this script #sg.delete() # create a new key pair key_name"
] |
[
"# noqa: E501 :rtype: str \"\"\" return self._tab_id @tab_id.setter def",
"\"\"\" DocuSign REST API The DocuSign REST API provides you",
"None)) setattr(self, \"_{}\".format('tab_type'), kwargs.get('tab_type', None)) setattr(self, \"_{}\".format('value'), kwargs.get('value', None)) @property",
"'tabLabel', 'tab_type': 'tabType', 'value': 'value' } def __init__(self, _configuration=None, **kwargs):",
"noqa: E501 :param tab_type: The tab_type of this ConditionalRecipientRuleFilter. #",
"lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x, value ))",
"# noqa: E501 :type: str \"\"\" self._recipient_id = recipient_id @property",
"API provides you with a powerful, convenient, and simple Web",
"is to sign the Document. # noqa: E501 :param recipient_id:",
"model defined in Swagger\"\"\" # noqa: E501 if _configuration is",
"ConditionalRecipientRuleFilter. The label string associated with the tab. # noqa:",
"this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._value =",
"None)) setattr(self, \"_{}\".format('recipient_id'), kwargs.get('recipient_id', None)) setattr(self, \"_{}\".format('scope'), kwargs.get('scope', None)) setattr(self,",
"@property def tab_label(self): \"\"\"Gets the tab_label of this ConditionalRecipientRuleFilter. #",
"\"\"\"Sets the recipient_id of this ConditionalRecipientRuleFilter. Unique for the recipient.",
"key, value in self.items(): result[key] = value return result def",
"= tab_id @property def tab_label(self): \"\"\"Gets the tab_label of this",
":param recipient_id: The recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501",
"noqa: E501 :type: str \"\"\" self._recipient_id = recipient_id @property def",
"def tab_id(self, tab_id): \"\"\"Sets the tab_id of this ConditionalRecipientRuleFilter. The",
"other): \"\"\"Returns true if both objects are equal\"\"\" if not",
"E501 :return: The recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501",
"recipient is to sign the Document. # noqa: E501 :param",
"value )) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value,",
"= None self._tab_type = None self._value = None self.discriminator =",
"is json key in definition. \"\"\" swagger_types = { 'operator':",
"# noqa: E501 :param tab_type: The tab_type of this ConditionalRecipientRuleFilter.",
"this ConditionalRecipientRuleFilter. # noqa: E501 Specifies the value of the",
"= { 'operator': 'operator', 'recipient_id': 'recipientId', 'scope': 'scope', 'tab_id': 'tabId',",
"'tabType', 'value': 'value' } def __init__(self, _configuration=None, **kwargs): # noqa:",
"scope(self): \"\"\"Gets the scope of this ConditionalRecipientRuleFilter. # noqa: E501",
"the tab_id of this ConditionalRecipientRuleFilter. # noqa: E501 The unique",
"noqa: E501 :return: The tab_id of this ConditionalRecipientRuleFilter. # noqa:",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :param tab_type: The tab_type",
"value of the tab. # noqa: E501 :param value: The",
"} attribute_map = { 'operator': 'operator', 'recipient_id': 'recipientId', 'scope': 'scope',",
"E501 :return: The value of this ConditionalRecipientRuleFilter. # noqa: E501",
"__repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str() def __eq__(self, other):",
"noqa: E501 :param value: The value of this ConditionalRecipientRuleFilter. #",
"\"\"\" self._scope = scope @property def tab_id(self): \"\"\"Gets the tab_id",
"string associated with the tab. # noqa: E501 :return: The",
"str \"\"\" return self._tab_type @tab_type.setter def tab_type(self, tab_type): \"\"\"Sets the",
"convenient, and simple Web services API for interacting with DocuSign.",
"_configuration is None: _configuration = Configuration() self._configuration = _configuration self._operator",
"str \"\"\" return self._operator @operator.setter def operator(self, operator): \"\"\"Sets the",
"the tab_label of this ConditionalRecipientRuleFilter. # noqa: E501 The label",
"tab element to indicate which recipient is to sign the",
"the value is attribute type. attribute_map (dict): The key is",
"`pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns true if both",
"utf-8 \"\"\" DocuSign REST API The DocuSign REST API provides",
"Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re # noqa:",
"return False return self.to_dict() == other.to_dict() def __ne__(self, other): \"\"\"Returns",
"code generator program. Do not edit the class manually. \"\"\"",
"the tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 # noqa:",
"model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return",
"ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._recipient_id = recipient_id",
"value in self.items(): result[key] = value return result def to_str(self):",
"@scope.setter def scope(self, scope): \"\"\"Sets the scope of this ConditionalRecipientRuleFilter.",
"ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._operator @operator.setter",
"this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._tab_label",
"string representation of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For",
"return result def to_str(self): \"\"\"Returns the string representation of the",
"v2.1 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import",
"noqa: E501 \"\"\"ConditionalRecipientRuleFilter - a model defined in Swagger\"\"\" #",
":rtype: str \"\"\" return self._recipient_id @recipient_id.setter def recipient_id(self, recipient_id): \"\"\"Sets",
"self.discriminator = None setattr(self, \"_{}\".format('operator'), kwargs.get('operator', None)) setattr(self, \"_{}\".format('recipient_id'), kwargs.get('recipient_id',",
"be retrieved with the [ML:GET call]. # noqa: E501 :return:",
"ConditionalRecipientRuleFilter. # noqa: E501 :param operator: The operator of this",
"# noqa: E501 :return: The value of this ConditionalRecipientRuleFilter. #",
"\"\"\"For `print` and `pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns",
"name and the value is json key in definition. \"\"\"",
"# noqa: E501 # noqa: E501 :return: The scope of",
"The key is attribute name and the value is attribute",
"identifier for the tab. The tabid can be retrieved with",
"self.to_str() def __eq__(self, other): \"\"\"Returns true if both objects are",
"def __init__(self, _configuration=None, **kwargs): # noqa: E501 \"\"\"ConditionalRecipientRuleFilter - a",
"ConditionalRecipientRuleFilter. Unique for the recipient. It is used by the",
"defined in Swagger\"\"\" # noqa: E501 if _configuration is None:",
"the tab element to indicate which recipient is to sign",
"recipient is to sign the Document. # noqa: E501 :return:",
"\"\"\"Sets the value of this ConditionalRecipientRuleFilter. Specifies the value of",
"E501 :param value: The value of this ConditionalRecipientRuleFilter. # noqa:",
":return: The scope of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype:",
"ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._scope @scope.setter",
"retrieved with the [ML:GET call]. # noqa: E501 :return: The",
"tab_id of this ConditionalRecipientRuleFilter. # noqa: E501 The unique identifier",
"The unique identifier for the tab. The tabid can be",
"\"_{}\".format('scope'), kwargs.get('scope', None)) setattr(self, \"_{}\".format('tab_id'), kwargs.get('tab_id', None)) setattr(self, \"_{}\".format('tab_label'), kwargs.get('tab_label',",
"true if both objects are equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter):",
"ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._tab_id = tab_id",
"kwargs.get('value', None)) @property def operator(self): \"\"\"Gets the operator of this",
"swagger_types = { 'operator': 'str', 'recipient_id': 'str', 'scope': 'str', 'tab_id':",
"tab_id(self, tab_id): \"\"\"Sets the tab_id of this ConditionalRecipientRuleFilter. The unique",
"self._tab_id = tab_id @property def tab_label(self): \"\"\"Gets the tab_label of",
"this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._value",
"_configuration self._operator = None self._recipient_id = None self._scope = None",
"return self._recipient_id @recipient_id.setter def recipient_id(self, recipient_id): \"\"\"Sets the recipient_id of",
"return self._tab_type @tab_type.setter def tab_type(self, tab_type): \"\"\"Sets the tab_type of",
"str \"\"\" self._tab_type = tab_type @property def value(self): \"\"\"Gets the",
"version: v2.1 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint",
"\"to_dict\") else item, value.items() )) else: result[attr] = value if",
"tab_type(self, tab_type): \"\"\"Sets the tab_type of this ConditionalRecipientRuleFilter. # noqa:",
"# noqa: E501 :return: The tab_type of this ConditionalRecipientRuleFilter. #",
"noqa: E501 :rtype: str \"\"\" return self._scope @scope.setter def scope(self,",
"The tab_label of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str",
":rtype: str \"\"\" return self._tab_label @tab_label.setter def tab_label(self, tab_label): \"\"\"Sets",
"\"\"\"Sets the operator of this ConditionalRecipientRuleFilter. # noqa: E501 :param",
"a model defined in Swagger\"\"\" # noqa: E501 if _configuration",
"to sign the Document. # noqa: E501 :return: The recipient_id",
"return self._scope @scope.setter def scope(self, scope): \"\"\"Sets the scope of",
"of this ConditionalRecipientRuleFilter. # noqa: E501 The unique identifier for",
"isinstance(other, ConditionalRecipientRuleFilter): return False return self.to_dict() == other.to_dict() def __ne__(self,",
"E501 :param tab_label: The tab_label of this ConditionalRecipientRuleFilter. # noqa:",
"tabid can be retrieved with the [ML:GET call]. # noqa:",
"dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1],",
"ConditionalRecipientRuleFilter. # noqa: E501 Specifies the value of the tab.",
"@tab_type.setter def tab_type(self, tab_type): \"\"\"Sets the tab_type of this ConditionalRecipientRuleFilter.",
"E501 if _configuration is None: _configuration = Configuration() self._configuration =",
"docusign_esign.client.configuration import Configuration class ConditionalRecipientRuleFilter(object): \"\"\"NOTE: This class is auto",
"the operator of this ConditionalRecipientRuleFilter. # noqa: E501 :param operator:",
"hasattr(item[1], \"to_dict\") else item, value.items() )) else: result[attr] = value",
"for key, value in self.items(): result[key] = value return result",
"# noqa: E501 :return: The recipient_id of this ConditionalRecipientRuleFilter. #",
"the value of this ConditionalRecipientRuleFilter. # noqa: E501 Specifies the",
"'recipientId', 'scope': 'scope', 'tab_id': 'tabId', 'tab_label': 'tabLabel', 'tab_type': 'tabType', 'value':",
"E501 :type: str \"\"\" self._scope = scope @property def tab_id(self):",
"of the tab. # noqa: E501 :param value: The value",
"str \"\"\" self._tab_label = tab_label @property def tab_type(self): \"\"\"Gets the",
"# noqa: E501 :param recipient_id: The recipient_id of this ConditionalRecipientRuleFilter.",
"Configuration class ConditionalRecipientRuleFilter(object): \"\"\"NOTE: This class is auto generated by",
"the tab. # noqa: E501 :param value: The value of",
"the operator of this ConditionalRecipientRuleFilter. # noqa: E501 # noqa:",
"is attribute name and the value is json key in",
"def scope(self, scope): \"\"\"Sets the scope of this ConditionalRecipientRuleFilter. #",
"def tab_type(self): \"\"\"Gets the tab_type of this ConditionalRecipientRuleFilter. # noqa:",
"self._recipient_id = recipient_id @property def scope(self): \"\"\"Gets the scope of",
"= {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self,",
"recipient_id @property def scope(self): \"\"\"Gets the scope of this ConditionalRecipientRuleFilter.",
"= tab_type @property def value(self): \"\"\"Gets the value of this",
"element to indicate which recipient is to sign the Document.",
"E501 :param scope: The scope of this ConditionalRecipientRuleFilter. # noqa:",
"operator of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\"",
"this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._recipient_id",
"\"\"\"Gets the operator of this ConditionalRecipientRuleFilter. # noqa: E501 #",
"is used by the tab element to indicate which recipient",
"tab_id: The tab_id of this ConditionalRecipientRuleFilter. # noqa: E501 :type:",
"value(self): \"\"\"Gets the value of this ConditionalRecipientRuleFilter. # noqa: E501",
"representation of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print`",
"this ConditionalRecipientRuleFilter. # noqa: E501 :param operator: The operator of",
"type. attribute_map (dict): The key is attribute name and the",
"associated with the tab. # noqa: E501 :return: The tab_label",
"if hasattr(x, \"to_dict\") else x, value )) elif hasattr(value, \"to_dict\"):",
"= recipient_id @property def scope(self): \"\"\"Gets the scope of this",
"# noqa: E501 :rtype: str \"\"\" return self._value @value.setter def",
"- a model defined in Swagger\"\"\" # noqa: E501 if",
"item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items() )) else: result[attr]",
"return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str()",
"the recipient_id of this ConditionalRecipientRuleFilter. Unique for the recipient. It",
"[ML:GET call]. # noqa: E501 :param tab_id: The tab_id of",
"The tab_id of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str",
"E501 :type: str \"\"\" self._recipient_id = recipient_id @property def scope(self):",
"to_str(self): \"\"\"Returns the string representation of the model\"\"\" return pprint.pformat(self.to_dict())",
"kwargs.get('tab_label', None)) setattr(self, \"_{}\".format('tab_type'), kwargs.get('tab_type', None)) setattr(self, \"_{}\".format('value'), kwargs.get('value', None))",
"tab_label): \"\"\"Sets the tab_label of this ConditionalRecipientRuleFilter. The label string",
"'tab_id': 'tabId', 'tab_label': 'tabLabel', 'tab_type': 'tabType', 'value': 'value' } def",
"ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._value @value.setter",
":type: str \"\"\" self._operator = operator @property def recipient_id(self): \"\"\"Gets",
"retrieved with the [ML:GET call]. # noqa: E501 :param tab_id:",
"of this ConditionalRecipientRuleFilter. # noqa: E501 Specifies the value of",
"'recipient_id': 'recipientId', 'scope': 'scope', 'tab_id': 'tabId', 'tab_label': 'tabLabel', 'tab_type': 'tabType',",
"result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda",
"# noqa: E501 :param operator: The operator of this ConditionalRecipientRuleFilter.",
"the [ML:GET call]. # noqa: E501 :param tab_id: The tab_id",
"unique identifier for the tab. The tabid can be retrieved",
"# noqa: E501 :type: str \"\"\" self._operator = operator @property",
"operator of this ConditionalRecipientRuleFilter. # noqa: E501 :param operator: The",
"self._operator = operator @property def recipient_id(self): \"\"\"Gets the recipient_id of",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return",
"E501 :return: The tab_type of this ConditionalRecipientRuleFilter. # noqa: E501",
"used by the tab element to indicate which recipient is",
"with the tab. # noqa: E501 :param tab_label: The tab_label",
"value if issubclass(ConditionalRecipientRuleFilter, dict): for key, value in self.items(): result[key]",
"E501 :type: str \"\"\" self._value = value def to_dict(self): \"\"\"Returns",
"@operator.setter def operator(self, operator): \"\"\"Sets the operator of this ConditionalRecipientRuleFilter.",
"self._recipient_id = None self._scope = None self._tab_id = None self._tab_label",
"equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return True return self.to_dict() !=",
"scope of this ConditionalRecipientRuleFilter. # noqa: E501 :param scope: The",
"a powerful, convenient, and simple Web services API for interacting",
"'tab_type': 'str', 'value': 'str' } attribute_map = { 'operator': 'operator',",
"@property def tab_id(self): \"\"\"Gets the tab_id of this ConditionalRecipientRuleFilter. #",
"The DocuSign REST API provides you with a powerful, convenient,",
"self._operator = None self._recipient_id = None self._scope = None self._tab_id",
"self._scope = None self._tab_id = None self._tab_label = None self._tab_type",
"E501 :return: The scope of this ConditionalRecipientRuleFilter. # noqa: E501",
"value): \"\"\"Sets the value of this ConditionalRecipientRuleFilter. Specifies the value",
"'operator': 'str', 'recipient_id': 'str', 'scope': 'str', 'tab_id': 'str', 'tab_label': 'str',",
"'str', 'recipient_id': 'str', 'scope': 'str', 'tab_id': 'str', 'tab_label': 'str', 'tab_type':",
":return: The tab_id of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype:",
"item, value.items() )) else: result[attr] = value if issubclass(ConditionalRecipientRuleFilter, dict):",
"can be retrieved with the [ML:GET call]. # noqa: E501",
"== other.to_dict() def __ne__(self, other): \"\"\"Returns true if both objects",
"ConditionalRecipientRuleFilter. # noqa: E501 The label string associated with the",
"simple Web services API for interacting with DocuSign. # noqa:",
":type: str \"\"\" self._tab_type = tab_type @property def value(self): \"\"\"Gets",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._tab_label",
"self._tab_id @tab_id.setter def tab_id(self, tab_id): \"\"\"Sets the tab_id of this",
"noqa: E501 :return: The value of this ConditionalRecipientRuleFilter. # noqa:",
"tab_type: The tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 :type:",
"# noqa: E501 :rtype: str \"\"\" return self._operator @operator.setter def",
"\"\"\" return self._recipient_id @recipient_id.setter def recipient_id(self, recipient_id): \"\"\"Sets the recipient_id",
"noqa: E501 :type: str \"\"\" self._tab_label = tab_label @property def",
"tab_type): \"\"\"Sets the tab_type of this ConditionalRecipientRuleFilter. # noqa: E501",
"operator of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\"",
"None)) setattr(self, \"_{}\".format('tab_id'), kwargs.get('tab_id', None)) setattr(self, \"_{}\".format('tab_label'), kwargs.get('tab_label', None)) setattr(self,",
"of this ConditionalRecipientRuleFilter. The unique identifier for the tab. The",
"setattr(self, \"_{}\".format('operator'), kwargs.get('operator', None)) setattr(self, \"_{}\".format('recipient_id'), kwargs.get('recipient_id', None)) setattr(self, \"_{}\".format('scope'),",
"self._tab_id = None self._tab_label = None self._tab_type = None self._value",
"E501 :rtype: str \"\"\" return self._tab_type @tab_type.setter def tab_type(self, tab_type):",
"program. Do not edit the class manually. \"\"\" \"\"\" Attributes:",
"'tab_id': 'str', 'tab_label': 'str', 'tab_type': 'str', 'value': 'str' } attribute_map",
"coding: utf-8 \"\"\" DocuSign REST API The DocuSign REST API",
"ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._tab_id @tab_id.setter",
"the value of the tab. # noqa: E501 :param value:",
"class is auto generated by the swagger code generator program.",
"not edit the class manually. \"\"\" \"\"\" Attributes: swagger_types (dict):",
"tab_id of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\"",
"list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\")",
"def recipient_id(self, recipient_id): \"\"\"Sets the recipient_id of this ConditionalRecipientRuleFilter. Unique",
"import six from docusign_esign.client.configuration import Configuration class ConditionalRecipientRuleFilter(object): \"\"\"NOTE: This",
"tab_id of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\"",
"'tab_type': 'tabType', 'value': 'value' } def __init__(self, _configuration=None, **kwargs): #",
"\"\"\" self._recipient_id = recipient_id @property def scope(self): \"\"\"Gets the scope",
"'str', 'tab_type': 'str', 'value': 'str' } attribute_map = { 'operator':",
"tab. The tabid can be retrieved with the [ML:GET call].",
"Configuration() self._configuration = _configuration self._operator = None self._recipient_id = None",
"recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\"",
"E501 :rtype: str \"\"\" return self._tab_id @tab_id.setter def tab_id(self, tab_id):",
"else: result[attr] = value if issubclass(ConditionalRecipientRuleFilter, dict): for key, value",
"this ConditionalRecipientRuleFilter. # noqa: E501 :param tab_type: The tab_type of",
"\"\"\" return self._tab_id @tab_id.setter def tab_id(self, tab_id): \"\"\"Sets the tab_id",
"'operator': 'operator', 'recipient_id': 'recipientId', 'scope': 'scope', 'tab_id': 'tabId', 'tab_label': 'tabLabel',",
"# noqa: E501 \"\"\"ConditionalRecipientRuleFilter - a model defined in Swagger\"\"\"",
"a dict\"\"\" result = {} for attr, _ in six.iteritems(self.swagger_types):",
"self._tab_label = tab_label @property def tab_type(self): \"\"\"Gets the tab_type of",
":param value: The value of this ConditionalRecipientRuleFilter. # noqa: E501",
"swagger code generator program. Do not edit the class manually.",
"key is attribute name and the value is attribute type.",
"OpenAPI spec version: v2.1 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\"",
"# noqa: E501 :rtype: str \"\"\" return self._tab_type @tab_type.setter def",
"The value of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str",
"tab_label: The tab_label of this ConditionalRecipientRuleFilter. # noqa: E501 :type:",
"noqa: E501 :rtype: str \"\"\" return self._operator @operator.setter def operator(self,",
"if not isinstance(other, ConditionalRecipientRuleFilter): return True return self.to_dict() != other.to_dict()",
"https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re # noqa: F401 import",
"'recipient_id': 'str', 'scope': 'str', 'tab_id': 'str', 'tab_label': 'str', 'tab_type': 'str',",
"# noqa: E501 The unique identifier for the tab. The",
"value of the tab. # noqa: E501 :return: The value",
"def recipient_id(self): \"\"\"Gets the recipient_id of this ConditionalRecipientRuleFilter. # noqa:",
"DocuSign. # noqa: E501 OpenAPI spec version: v2.1 Contact: <EMAIL>",
"kwargs.get('scope', None)) setattr(self, \"_{}\".format('tab_id'), kwargs.get('tab_id', None)) setattr(self, \"_{}\".format('tab_label'), kwargs.get('tab_label', None))",
"str \"\"\" self._recipient_id = recipient_id @property def scope(self): \"\"\"Gets the",
"E501 :return: The tab_id of this ConditionalRecipientRuleFilter. # noqa: E501",
"tab_label(self): \"\"\"Gets the tab_label of this ConditionalRecipientRuleFilter. # noqa: E501",
"this ConditionalRecipientRuleFilter. The label string associated with the tab. #",
"\"\"\"Returns the model properties as a dict\"\"\" result = {}",
"item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items() ))",
"def to_str(self): \"\"\"Returns the string representation of the model\"\"\" return",
"ConditionalRecipientRuleFilter): return False return self.to_dict() == other.to_dict() def __ne__(self, other):",
":rtype: str \"\"\" return self._operator @operator.setter def operator(self, operator): \"\"\"Sets",
":rtype: str \"\"\" return self._value @value.setter def value(self, value): \"\"\"Sets",
"noqa: E501 if _configuration is None: _configuration = Configuration() self._configuration",
"operator of this ConditionalRecipientRuleFilter. # noqa: E501 # noqa: E501",
"self._tab_label @tab_label.setter def tab_label(self, tab_label): \"\"\"Sets the tab_label of this",
"result[attr] = value if issubclass(ConditionalRecipientRuleFilter, dict): for key, value in",
"setattr(self, \"_{}\".format('tab_id'), kwargs.get('tab_id', None)) setattr(self, \"_{}\".format('tab_label'), kwargs.get('tab_label', None)) setattr(self, \"_{}\".format('tab_type'),",
"sign the Document. # noqa: E501 :return: The recipient_id of",
"label string associated with the tab. # noqa: E501 :param",
":return: The value of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype:",
"`print` and `pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns true",
"name and the value is attribute type. attribute_map (dict): The",
"noqa: E501 :type: str \"\"\" self._scope = scope @property def",
"tab. # noqa: E501 :return: The tab_label of this ConditionalRecipientRuleFilter.",
"tab. # noqa: E501 :param tab_label: The tab_label of this",
"the Document. # noqa: E501 :param recipient_id: The recipient_id of",
"\"\"\"Returns the string representation of the model\"\"\" return pprint.pformat(self.to_dict()) def",
"for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if",
"The scope of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str",
"DocuSign REST API The DocuSign REST API provides you with",
"you with a powerful, convenient, and simple Web services API",
"E501 :return: The operator of this ConditionalRecipientRuleFilter. # noqa: E501",
"scope): \"\"\"Sets the scope of this ConditionalRecipientRuleFilter. # noqa: E501",
"= list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,",
"interacting with DocuSign. # noqa: E501 OpenAPI spec version: v2.1",
"'value': 'value' } def __init__(self, _configuration=None, **kwargs): # noqa: E501",
"equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return False return self.to_dict() ==",
"are equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return False return self.to_dict()",
"of this ConditionalRecipientRuleFilter. # noqa: E501 # noqa: E501 :return:",
"of this ConditionalRecipientRuleFilter. Unique for the recipient. It is used",
"REST API The DocuSign REST API provides you with a",
"The key is attribute name and the value is json",
"E501 # noqa: E501 :return: The scope of this ConditionalRecipientRuleFilter.",
"E501 :rtype: str \"\"\" return self._scope @scope.setter def scope(self, scope):",
"self._scope = scope @property def tab_id(self): \"\"\"Gets the tab_id of",
"noqa: E501 :return: The recipient_id of this ConditionalRecipientRuleFilter. # noqa:",
"manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The key is attribute",
"setattr(self, \"_{}\".format('tab_label'), kwargs.get('tab_label', None)) setattr(self, \"_{}\".format('tab_type'), kwargs.get('tab_type', None)) setattr(self, \"_{}\".format('value'),",
"None self._scope = None self._tab_id = None self._tab_label = None",
"None self._tab_label = None self._tab_type = None self._value = None",
"E501 \"\"\"ConditionalRecipientRuleFilter - a model defined in Swagger\"\"\" # noqa:",
"self._value @value.setter def value(self, value): \"\"\"Sets the value of this",
"this ConditionalRecipientRuleFilter. # noqa: E501 # noqa: E501 :return: The",
"ConditionalRecipientRuleFilter. # noqa: E501 The unique identifier for the tab.",
"noqa: E501 :rtype: str \"\"\" return self._tab_id @tab_id.setter def tab_id(self,",
"noqa: E501 :rtype: str \"\"\" return self._value @value.setter def value(self,",
"are not equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return True return",
"# noqa: E501 :return: The tab_label of this ConditionalRecipientRuleFilter. #",
"getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x:",
"The operator of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str",
"the value of the tab. # noqa: E501 :return: The",
"the tab. The tabid can be retrieved with the [ML:GET",
"hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] =",
"setattr(self, \"_{}\".format('value'), kwargs.get('value', None)) @property def operator(self): \"\"\"Gets the operator",
"from docusign_esign.client.configuration import Configuration class ConditionalRecipientRuleFilter(object): \"\"\"NOTE: This class is",
"if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if",
"for the recipient. It is used by the tab element",
"the tab_id of this ConditionalRecipientRuleFilter. The unique identifier for the",
"auto generated by the swagger code generator program. Do not",
"Document. # noqa: E501 :return: The recipient_id of this ConditionalRecipientRuleFilter.",
"noqa: E501 :type: str \"\"\" self._tab_type = tab_type @property def",
"str \"\"\" return self._scope @scope.setter def scope(self, scope): \"\"\"Sets the",
"kwargs.get('operator', None)) setattr(self, \"_{}\".format('recipient_id'), kwargs.get('recipient_id', None)) setattr(self, \"_{}\".format('scope'), kwargs.get('scope', None))",
"The recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str",
"\"\"\" swagger_types = { 'operator': 'str', 'recipient_id': 'str', 'scope': 'str',",
"__init__(self, _configuration=None, **kwargs): # noqa: E501 \"\"\"ConditionalRecipientRuleFilter - a model",
"str \"\"\" self._operator = operator @property def recipient_id(self): \"\"\"Gets the",
"recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501 Unique for the",
"else item, value.items() )) else: result[attr] = value if issubclass(ConditionalRecipientRuleFilter,",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._value",
"def __eq__(self, other): \"\"\"Returns true if both objects are equal\"\"\"",
"of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and",
"\"_{}\".format('recipient_id'), kwargs.get('recipient_id', None)) setattr(self, \"_{}\".format('scope'), kwargs.get('scope', None)) setattr(self, \"_{}\".format('tab_id'), kwargs.get('tab_id',",
"attribute name and the value is json key in definition.",
"the [ML:GET call]. # noqa: E501 :return: The tab_id of",
"ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._tab_type @tab_type.setter",
"(dict): The key is attribute name and the value is",
")) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict):",
"the value is json key in definition. \"\"\" swagger_types =",
"ConditionalRecipientRuleFilter. # noqa: E501 # noqa: E501 :return: The tab_type",
"'tab_label': 'str', 'tab_type': 'str', 'value': 'str' } attribute_map = {",
"which recipient is to sign the Document. # noqa: E501",
"E501 OpenAPI spec version: v2.1 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git",
"def tab_type(self, tab_type): \"\"\"Sets the tab_type of this ConditionalRecipientRuleFilter. #",
"this ConditionalRecipientRuleFilter. Specifies the value of the tab. # noqa:",
"and simple Web services API for interacting with DocuSign. #",
"\"\"\" \"\"\" Attributes: swagger_types (dict): The key is attribute name",
"# noqa: E501 :type: str \"\"\" self._scope = scope @property",
"noqa: E501 :param scope: The scope of this ConditionalRecipientRuleFilter. #",
"\"\"\" return self._scope @scope.setter def scope(self, scope): \"\"\"Sets the scope",
"(item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items() )) else:",
"ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._value = value",
"@property def scope(self): \"\"\"Gets the scope of this ConditionalRecipientRuleFilter. #",
"kwargs.get('tab_id', None)) setattr(self, \"_{}\".format('tab_label'), kwargs.get('tab_label', None)) setattr(self, \"_{}\".format('tab_type'), kwargs.get('tab_type', None))",
"value(self, value): \"\"\"Sets the value of this ConditionalRecipientRuleFilter. Specifies the",
"None setattr(self, \"_{}\".format('operator'), kwargs.get('operator', None)) setattr(self, \"_{}\".format('recipient_id'), kwargs.get('recipient_id', None)) setattr(self,",
"setattr(self, \"_{}\".format('tab_type'), kwargs.get('tab_type', None)) setattr(self, \"_{}\".format('value'), kwargs.get('value', None)) @property def",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._tab_type",
"= None self.discriminator = None setattr(self, \"_{}\".format('operator'), kwargs.get('operator', None)) setattr(self,",
"noqa: E501 :param operator: The operator of this ConditionalRecipientRuleFilter. #",
"result = {} for attr, _ in six.iteritems(self.swagger_types): value =",
"def value(self, value): \"\"\"Sets the value of this ConditionalRecipientRuleFilter. Specifies",
"noqa: E501 # noqa: E501 :return: The scope of this",
"'scope': 'str', 'tab_id': 'str', 'tab_label': 'str', 'tab_type': 'str', 'value': 'str'",
"# noqa: E501 :type: str \"\"\" self._tab_label = tab_label @property",
"_configuration = Configuration() self._configuration = _configuration self._operator = None self._recipient_id",
"self._tab_type = None self._value = None self.discriminator = None setattr(self,",
"of this ConditionalRecipientRuleFilter. # noqa: E501 The label string associated",
"__ne__(self, other): \"\"\"Returns true if both objects are not equal\"\"\"",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :param scope: The scope",
"and the value is json key in definition. \"\"\" swagger_types",
"{ 'operator': 'str', 'recipient_id': 'str', 'scope': 'str', 'tab_id': 'str', 'tab_label':",
"noqa: E501 :return: The scope of this ConditionalRecipientRuleFilter. # noqa:",
"noqa: E501 :return: The tab_type of this ConditionalRecipientRuleFilter. # noqa:",
"\"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map(",
"recipient_id(self, recipient_id): \"\"\"Sets the recipient_id of this ConditionalRecipientRuleFilter. Unique for",
"with DocuSign. # noqa: E501 OpenAPI spec version: v2.1 Contact:",
"= _configuration self._operator = None self._recipient_id = None self._scope =",
"'tab_label': 'tabLabel', 'tab_type': 'tabType', 'value': 'value' } def __init__(self, _configuration=None,",
"\"_{}\".format('operator'), kwargs.get('operator', None)) setattr(self, \"_{}\".format('recipient_id'), kwargs.get('recipient_id', None)) setattr(self, \"_{}\".format('scope'), kwargs.get('scope',",
"model properties as a dict\"\"\" result = {} for attr,",
"the tab. # noqa: E501 :return: The value of this",
"tab_id @property def tab_label(self): \"\"\"Gets the tab_label of this ConditionalRecipientRuleFilter.",
"# noqa: E501 :param scope: The scope of this ConditionalRecipientRuleFilter.",
"tab. # noqa: E501 :return: The value of this ConditionalRecipientRuleFilter.",
"def __ne__(self, other): \"\"\"Returns true if both objects are not",
"'scope': 'scope', 'tab_id': 'tabId', 'tab_label': 'tabLabel', 'tab_type': 'tabType', 'value': 'value'",
"noqa: E501 :rtype: str \"\"\" return self._tab_type @tab_type.setter def tab_type(self,",
"self.to_dict() == other.to_dict() def __ne__(self, other): \"\"\"Returns true if both",
"kwargs.get('recipient_id', None)) setattr(self, \"_{}\".format('scope'), kwargs.get('scope', None)) setattr(self, \"_{}\".format('tab_id'), kwargs.get('tab_id', None))",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._operator",
"ConditionalRecipientRuleFilter. The unique identifier for the tab. The tabid can",
"= dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else",
"attribute_map = { 'operator': 'operator', 'recipient_id': 'recipientId', 'scope': 'scope', 'tab_id':",
"tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\"",
"# noqa: E501 Unique for the recipient. It is used",
":return: The recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype:",
"None)) setattr(self, \"_{}\".format('tab_label'), kwargs.get('tab_label', None)) setattr(self, \"_{}\".format('tab_type'), kwargs.get('tab_type', None)) setattr(self,",
"def operator(self): \"\"\"Gets the operator of this ConditionalRecipientRuleFilter. # noqa:",
"E501 :param operator: The operator of this ConditionalRecipientRuleFilter. # noqa:",
"this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._operator =",
"class ConditionalRecipientRuleFilter(object): \"\"\"NOTE: This class is auto generated by the",
"scope @property def tab_id(self): \"\"\"Gets the tab_id of this ConditionalRecipientRuleFilter.",
"scope of this ConditionalRecipientRuleFilter. # noqa: E501 # noqa: E501",
"this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._tab_id =",
"# noqa: E501 :type: str \"\"\" self._tab_type = tab_type @property",
"the value of this ConditionalRecipientRuleFilter. Specifies the value of the",
"# noqa: E501 :param tab_id: The tab_id of this ConditionalRecipientRuleFilter.",
"services API for interacting with DocuSign. # noqa: E501 OpenAPI",
"spec version: v2.1 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import",
"this ConditionalRecipientRuleFilter. # noqa: E501 The label string associated with",
"'str', 'tab_label': 'str', 'tab_type': 'str', 'value': 'str' } attribute_map =",
"E501 # noqa: E501 :return: The operator of this ConditionalRecipientRuleFilter.",
"key is attribute name and the value is json key",
"The label string associated with the tab. # noqa: E501",
"noqa: E501 :param tab_id: The tab_id of this ConditionalRecipientRuleFilter. #",
"noqa: E501 :param recipient_id: The recipient_id of this ConditionalRecipientRuleFilter. #",
"generator program. Do not edit the class manually. \"\"\" \"\"\"",
"# noqa: E501 # noqa: E501 :return: The tab_type of",
"return self._operator @operator.setter def operator(self, operator): \"\"\"Sets the operator of",
"E501 :rtype: str \"\"\" return self._tab_label @tab_label.setter def tab_label(self, tab_label):",
"= None setattr(self, \"_{}\".format('operator'), kwargs.get('operator', None)) setattr(self, \"_{}\".format('recipient_id'), kwargs.get('recipient_id', None))",
"The tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str",
":type: str \"\"\" self._value = value def to_dict(self): \"\"\"Returns the",
"def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str() def __eq__(self,",
":return: The operator of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype:",
"E501 :return: The tab_label of this ConditionalRecipientRuleFilter. # noqa: E501",
"and `pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns true if",
"None self._tab_id = None self._tab_label = None self._tab_type = None",
"noqa: E501 :type: str \"\"\" self._tab_id = tab_id @property def",
"ConditionalRecipientRuleFilter. # noqa: E501 # noqa: E501 :return: The scope",
"\"\"\"Gets the scope of this ConditionalRecipientRuleFilter. # noqa: E501 #",
"E501 :param tab_id: The tab_id of this ConditionalRecipientRuleFilter. # noqa:",
"# noqa: E501 :param tab_label: The tab_label of this ConditionalRecipientRuleFilter.",
"list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x, value",
"both objects are equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return False",
"# noqa: E501 :type: str \"\"\" self._value = value def",
"str \"\"\" return self._recipient_id @recipient_id.setter def recipient_id(self, recipient_id): \"\"\"Sets the",
"None: _configuration = Configuration() self._configuration = _configuration self._operator = None",
"**kwargs): # noqa: E501 \"\"\"ConditionalRecipientRuleFilter - a model defined in",
"E501 :type: str \"\"\" self._tab_type = tab_type @property def value(self):",
"self.items(): result[key] = value return result def to_str(self): \"\"\"Returns the",
"= None self._tab_id = None self._tab_label = None self._tab_type =",
"DocuSign REST API provides you with a powerful, convenient, and",
"\"\"\"Returns true if both objects are equal\"\"\" if not isinstance(other,",
"scope of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\"",
"the scope of this ConditionalRecipientRuleFilter. # noqa: E501 :param scope:",
"str \"\"\" self._scope = scope @property def tab_id(self): \"\"\"Gets the",
"# noqa: E501 :return: The tab_id of this ConditionalRecipientRuleFilter. #",
"\"\"\" Attributes: swagger_types (dict): The key is attribute name and",
"\"\"\"Gets the tab_label of this ConditionalRecipientRuleFilter. # noqa: E501 The",
"value def to_dict(self): \"\"\"Returns the model properties as a dict\"\"\"",
"{} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr)",
"setattr(self, \"_{}\".format('scope'), kwargs.get('scope', None)) setattr(self, \"_{}\".format('tab_id'), kwargs.get('tab_id', None)) setattr(self, \"_{}\".format('tab_label'),",
"[ML:GET call]. # noqa: E501 :return: The tab_id of this",
"# noqa: E501 The label string associated with the tab.",
"\"\"\" return self._value @value.setter def value(self, value): \"\"\"Sets the value",
"in Swagger\"\"\" # noqa: E501 if _configuration is None: _configuration",
"noqa: E501 :rtype: str \"\"\" return self._recipient_id @recipient_id.setter def recipient_id(self,",
"ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._scope = scope",
"noqa: E501 :return: The operator of this ConditionalRecipientRuleFilter. # noqa:",
"isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x,",
"\"\"\"Gets the recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501 Unique",
"result[key] = value return result def to_str(self): \"\"\"Returns the string",
"def to_dict(self): \"\"\"Returns the model properties as a dict\"\"\" result",
"key in definition. \"\"\" swagger_types = { 'operator': 'str', 'recipient_id':",
"= value def to_dict(self): \"\"\"Returns the model properties as a",
"The operator of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str",
"\"\"\"Gets the tab_id of this ConditionalRecipientRuleFilter. # noqa: E501 The",
"Specifies the value of the tab. # noqa: E501 :param",
"the tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 :param tab_type:",
"noqa: E501 # noqa: E501 :return: The tab_type of this",
"\"\"\" self._value = value def to_dict(self): \"\"\"Returns the model properties",
"in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr]",
"__eq__(self, other): \"\"\"Returns true if both objects are equal\"\"\" if",
"re # noqa: F401 import six from docusign_esign.client.configuration import Configuration",
"It is used by the tab element to indicate which",
"'value': 'str' } attribute_map = { 'operator': 'operator', 'recipient_id': 'recipientId',",
"= getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda",
"tab_id(self): \"\"\"Gets the tab_id of this ConditionalRecipientRuleFilter. # noqa: E501",
"tab_id): \"\"\"Sets the tab_id of this ConditionalRecipientRuleFilter. The unique identifier",
"to indicate which recipient is to sign the Document. #",
"value return result def to_str(self): \"\"\"Returns the string representation of",
"in self.items(): result[key] = value return result def to_str(self): \"\"\"Returns",
"import pprint import re # noqa: F401 import six from",
"\"_{}\".format('tab_label'), kwargs.get('tab_label', None)) setattr(self, \"_{}\".format('tab_type'), kwargs.get('tab_type', None)) setattr(self, \"_{}\".format('value'), kwargs.get('value',",
"ConditionalRecipientRuleFilter. # noqa: E501 :param scope: The scope of this",
"tab_label of this ConditionalRecipientRuleFilter. The label string associated with the",
"\"\"\" self._operator = operator @property def recipient_id(self): \"\"\"Gets the recipient_id",
"None self.discriminator = None setattr(self, \"_{}\".format('operator'), kwargs.get('operator', None)) setattr(self, \"_{}\".format('recipient_id'),",
"# noqa: E501 :return: The operator of this ConditionalRecipientRuleFilter. #",
"None)) @property def operator(self): \"\"\"Gets the operator of this ConditionalRecipientRuleFilter.",
":type: str \"\"\" self._tab_id = tab_id @property def tab_label(self): \"\"\"Gets",
"\"\"\"Returns true if both objects are not equal\"\"\" if not",
"import Configuration class ConditionalRecipientRuleFilter(object): \"\"\"NOTE: This class is auto generated",
"this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._scope =",
"not equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return True return self.to_dict()",
"\"_{}\".format('tab_type'), kwargs.get('tab_type', None)) setattr(self, \"_{}\".format('value'), kwargs.get('value', None)) @property def operator(self):",
"\"\"\"Sets the tab_id of this ConditionalRecipientRuleFilter. The unique identifier for",
"_configuration=None, **kwargs): # noqa: E501 \"\"\"ConditionalRecipientRuleFilter - a model defined",
"E501 :rtype: str \"\"\" return self._value @value.setter def value(self, value):",
"indicate which recipient is to sign the Document. # noqa:",
"by the tab element to indicate which recipient is to",
"# noqa: E501 :type: str \"\"\" self._tab_id = tab_id @property",
"\"\"\" return self._tab_type @tab_type.setter def tab_type(self, tab_type): \"\"\"Sets the tab_type",
"ConditionalRecipientRuleFilter. # noqa: E501 :param tab_type: The tab_type of this",
"else x, value )) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict()",
"# noqa: E501 Specifies the value of the tab. #",
"# noqa: F401 import six from docusign_esign.client.configuration import Configuration class",
"@recipient_id.setter def recipient_id(self, recipient_id): \"\"\"Sets the recipient_id of this ConditionalRecipientRuleFilter.",
"the scope of this ConditionalRecipientRuleFilter. # noqa: E501 # noqa:",
"value of this ConditionalRecipientRuleFilter. # noqa: E501 Specifies the value",
"\"\"\" self._tab_id = tab_id @property def tab_label(self): \"\"\"Gets the tab_label",
"The tabid can be retrieved with the [ML:GET call]. #",
"swagger_types (dict): The key is attribute name and the value",
"is None: _configuration = Configuration() self._configuration = _configuration self._operator =",
"= value return result def to_str(self): \"\"\"Returns the string representation",
"recipient. It is used by the tab element to indicate",
"F401 import six from docusign_esign.client.configuration import Configuration class ConditionalRecipientRuleFilter(object): \"\"\"NOTE:",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :param operator: The operator",
"= tab_label @property def tab_type(self): \"\"\"Gets the tab_type of this",
"both objects are not equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return",
"Unique for the recipient. It is used by the tab",
"Web services API for interacting with DocuSign. # noqa: E501",
"kwargs.get('tab_type', None)) setattr(self, \"_{}\".format('value'), kwargs.get('value', None)) @property def operator(self): \"\"\"Gets",
"tab_label of this ConditionalRecipientRuleFilter. # noqa: E501 The label string",
"tab_label of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\"",
":return: The tab_label of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype:",
"= None self._tab_label = None self._tab_type = None self._value =",
"@property def recipient_id(self): \"\"\"Gets the recipient_id of this ConditionalRecipientRuleFilter. #",
"REST API provides you with a powerful, convenient, and simple",
"this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._recipient_id =",
"@property def tab_type(self): \"\"\"Gets the tab_type of this ConditionalRecipientRuleFilter. #",
"API for interacting with DocuSign. # noqa: E501 OpenAPI spec",
"None)) setattr(self, \"_{}\".format('value'), kwargs.get('value', None)) @property def operator(self): \"\"\"Gets the",
"# noqa: E501 # noqa: E501 :return: The operator of",
"noqa: E501 Specifies the value of the tab. # noqa:",
"x, value )) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif",
"of this ConditionalRecipientRuleFilter. Specifies the value of the tab. #",
"\"\"\"NOTE: This class is auto generated by the swagger code",
"return self._tab_label @tab_label.setter def tab_label(self, tab_label): \"\"\"Sets the tab_label of",
"this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._operator",
"E501 Specifies the value of the tab. # noqa: E501",
"API The DocuSign REST API provides you with a powerful,",
"the Document. # noqa: E501 :return: The recipient_id of this",
"def operator(self, operator): \"\"\"Sets the operator of this ConditionalRecipientRuleFilter. #",
"'scope', 'tab_id': 'tabId', 'tab_label': 'tabLabel', 'tab_type': 'tabType', 'value': 'value' }",
"this ConditionalRecipientRuleFilter. # noqa: E501 Unique for the recipient. It",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._recipient_id",
"the tab. # noqa: E501 :param tab_label: The tab_label of",
"self._value = value def to_dict(self): \"\"\"Returns the model properties as",
"result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\")",
"# noqa: E501 :rtype: str \"\"\" return self._scope @scope.setter def",
"noqa: F401 import six from docusign_esign.client.configuration import Configuration class ConditionalRecipientRuleFilter(object):",
":param tab_label: The tab_label of this ConditionalRecipientRuleFilter. # noqa: E501",
"noqa: E501 # noqa: E501 :return: The operator of this",
"@tab_label.setter def tab_label(self, tab_label): \"\"\"Sets the tab_label of this ConditionalRecipientRuleFilter.",
"None self._tab_type = None self._value = None self.discriminator = None",
"properties as a dict\"\"\" result = {} for attr, _",
"edit the class manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The",
"provides you with a powerful, convenient, and simple Web services",
"ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._recipient_id @recipient_id.setter",
"str \"\"\" return self._tab_id @tab_id.setter def tab_id(self, tab_id): \"\"\"Sets the",
"self._tab_type @tab_type.setter def tab_type(self, tab_type): \"\"\"Sets the tab_type of this",
"E501 :param tab_type: The tab_type of this ConditionalRecipientRuleFilter. # noqa:",
"noqa: E501 :type: str \"\"\" self._operator = operator @property def",
"sign the Document. # noqa: E501 :param recipient_id: The recipient_id",
"\"\"\"ConditionalRecipientRuleFilter - a model defined in Swagger\"\"\" # noqa: E501",
"\"_{}\".format('value'), kwargs.get('value', None)) @property def operator(self): \"\"\"Gets the operator of",
"\"to_dict\") else x, value )) elif hasattr(value, \"to_dict\"): result[attr] =",
"False return self.to_dict() == other.to_dict() def __ne__(self, other): \"\"\"Returns true",
"of this ConditionalRecipientRuleFilter. # noqa: E501 Unique for the recipient.",
"ConditionalRecipientRuleFilter. # noqa: E501 # noqa: E501 :return: The operator",
"recipient_id: The recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501 :type:",
"\"\"\"Gets the tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 #",
"@property def operator(self): \"\"\"Gets the operator of this ConditionalRecipientRuleFilter. #",
"attribute name and the value is attribute type. attribute_map (dict):",
"Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re",
":type: str \"\"\" self._tab_label = tab_label @property def tab_type(self): \"\"\"Gets",
"Specifies the value of the tab. # noqa: E501 :return:",
"value of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\"",
"tab. # noqa: E501 :param value: The value of this",
"E501 # noqa: E501 :return: The tab_type of this ConditionalRecipientRuleFilter.",
"E501 The label string associated with the tab. # noqa:",
"if not isinstance(other, ConditionalRecipientRuleFilter): return False return self.to_dict() == other.to_dict()",
"elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict())",
"E501 :type: str \"\"\" self._tab_id = tab_id @property def tab_label(self):",
"tab_label(self, tab_label): \"\"\"Sets the tab_label of this ConditionalRecipientRuleFilter. The label",
"recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\"",
"with the tab. # noqa: E501 :return: The tab_label of",
"tab_type(self): \"\"\"Gets the tab_type of this ConditionalRecipientRuleFilter. # noqa: E501",
"'value' } def __init__(self, _configuration=None, **kwargs): # noqa: E501 \"\"\"ConditionalRecipientRuleFilter",
"the model properties as a dict\"\"\" result = {} for",
"The tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str",
"ConditionalRecipientRuleFilter. Specifies the value of the tab. # noqa: E501",
"noqa: E501 Unique for the recipient. It is used by",
"the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\"",
"@value.setter def value(self, value): \"\"\"Sets the value of this ConditionalRecipientRuleFilter.",
"in definition. \"\"\" swagger_types = { 'operator': 'str', 'recipient_id': 'str',",
"this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._tab_id",
"E501 The unique identifier for the tab. The tabid can",
"The recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str",
"= operator @property def recipient_id(self): \"\"\"Gets the recipient_id of this",
"x.to_dict() if hasattr(x, \"to_dict\") else x, value )) elif hasattr(value,",
"\"\"\"Sets the tab_label of this ConditionalRecipientRuleFilter. The label string associated",
"Attributes: swagger_types (dict): The key is attribute name and the",
"json key in definition. \"\"\" swagger_types = { 'operator': 'str',",
"E501 :param recipient_id: The recipient_id of this ConditionalRecipientRuleFilter. # noqa:",
"self._configuration = _configuration self._operator = None self._recipient_id = None self._scope",
"self._tab_type = tab_type @property def value(self): \"\"\"Gets the value of",
"be retrieved with the [ML:GET call]. # noqa: E501 :param",
"str \"\"\" self._tab_id = tab_id @property def tab_label(self): \"\"\"Gets the",
"by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re # noqa: F401",
"None self._recipient_id = None self._scope = None self._tab_id = None",
"= None self._scope = None self._tab_id = None self._tab_label =",
"is auto generated by the swagger code generator program. Do",
"} def __init__(self, _configuration=None, **kwargs): # noqa: E501 \"\"\"ConditionalRecipientRuleFilter -",
")) else: result[attr] = value if issubclass(ConditionalRecipientRuleFilter, dict): for key,",
"call]. # noqa: E501 :return: The tab_id of this ConditionalRecipientRuleFilter.",
"E501 :rtype: str \"\"\" return self._recipient_id @recipient_id.setter def recipient_id(self, recipient_id):",
"value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0],",
"str \"\"\" return self._value @value.setter def value(self, value): \"\"\"Sets the",
"'operator', 'recipient_id': 'recipientId', 'scope': 'scope', 'tab_id': 'tabId', 'tab_label': 'tabLabel', 'tab_type':",
"if hasattr(item[1], \"to_dict\") else item, value.items() )) else: result[attr] =",
"def tab_id(self): \"\"\"Gets the tab_id of this ConditionalRecipientRuleFilter. # noqa:",
"= None self._recipient_id = None self._scope = None self._tab_id =",
"this ConditionalRecipientRuleFilter. Unique for the recipient. It is used by",
"\"\"\" import pprint import re # noqa: F401 import six",
"dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item,",
"'str', 'tab_id': 'str', 'tab_label': 'str', 'tab_type': 'str', 'value': 'str' }",
"noqa: E501 OpenAPI spec version: v2.1 Contact: <EMAIL> Generated by:",
"E501 :type: str \"\"\" self._tab_label = tab_label @property def tab_type(self):",
"'str', 'scope': 'str', 'tab_id': 'str', 'tab_label': 'str', 'tab_type': 'str', 'value':",
"if both objects are not equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter):",
":return: The tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype:",
"value of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\"",
":rtype: str \"\"\" return self._tab_type @tab_type.setter def tab_type(self, tab_type): \"\"\"Sets",
"scope(self, scope): \"\"\"Sets the scope of this ConditionalRecipientRuleFilter. # noqa:",
"\"\"\"Gets the value of this ConditionalRecipientRuleFilter. # noqa: E501 Specifies",
"if both objects are equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return",
"# coding: utf-8 \"\"\" DocuSign REST API The DocuSign REST",
"issubclass(ConditionalRecipientRuleFilter, dict): for key, value in self.items(): result[key] = value",
"the tab_label of this ConditionalRecipientRuleFilter. The label string associated with",
"return self.to_dict() == other.to_dict() def __ne__(self, other): \"\"\"Returns true if",
"operator(self, operator): \"\"\"Sets the operator of this ConditionalRecipientRuleFilter. # noqa:",
"def value(self): \"\"\"Gets the value of this ConditionalRecipientRuleFilter. # noqa:",
"<filename>docusign_esign/models/conditional_recipient_rule_filter.py # coding: utf-8 \"\"\" DocuSign REST API The DocuSign",
"tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 # noqa: E501",
"noqa: E501 :type: str \"\"\" self._value = value def to_dict(self):",
"ConditionalRecipientRuleFilter(object): \"\"\"NOTE: This class is auto generated by the swagger",
"the recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501 Unique for",
"of this ConditionalRecipientRuleFilter. The label string associated with the tab.",
"recipient_id(self): \"\"\"Gets the recipient_id of this ConditionalRecipientRuleFilter. # noqa: E501",
"'tabId', 'tab_label': 'tabLabel', 'tab_type': 'tabType', 'value': 'value' } def __init__(self,",
"\"\"\" return self._tab_label @tab_label.setter def tab_label(self, tab_label): \"\"\"Sets the tab_label",
"'str', 'value': 'str' } attribute_map = { 'operator': 'operator', 'recipient_id':",
"this ConditionalRecipientRuleFilter. # noqa: E501 :param scope: The scope of",
"tab_id of this ConditionalRecipientRuleFilter. The unique identifier for the tab.",
"return self._tab_id @tab_id.setter def tab_id(self, tab_id): \"\"\"Sets the tab_id of",
"value is attribute type. attribute_map (dict): The key is attribute",
"string associated with the tab. # noqa: E501 :param tab_label:",
"return self.to_str() def __eq__(self, other): \"\"\"Returns true if both objects",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._scope",
"x: x.to_dict() if hasattr(x, \"to_dict\") else x, value )) elif",
"not isinstance(other, ConditionalRecipientRuleFilter): return False return self.to_dict() == other.to_dict() def",
"value.items() )) else: result[attr] = value if issubclass(ConditionalRecipientRuleFilter, dict): for",
"self._value = None self.discriminator = None setattr(self, \"_{}\".format('operator'), kwargs.get('operator', None))",
"this ConditionalRecipientRuleFilter. # noqa: E501 The unique identifier for the",
"if _configuration is None: _configuration = Configuration() self._configuration = _configuration",
"E501 Unique for the recipient. It is used by the",
"of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._tab_id",
"of the tab. # noqa: E501 :return: The value of",
"and the value is attribute type. attribute_map (dict): The key",
"if issubclass(ConditionalRecipientRuleFilter, dict): for key, value in self.items(): result[key] =",
"value is json key in definition. \"\"\" swagger_types = {",
"lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items()",
"noqa: E501 The label string associated with the tab. #",
"str \"\"\" self._value = value def to_dict(self): \"\"\"Returns the model",
"six from docusign_esign.client.configuration import Configuration class ConditionalRecipientRuleFilter(object): \"\"\"NOTE: This class",
":param tab_type: The tab_type of this ConditionalRecipientRuleFilter. # noqa: E501",
"self._operator @operator.setter def operator(self, operator): \"\"\"Sets the operator of this",
"# noqa: E501 :rtype: str \"\"\" return self._recipient_id @recipient_id.setter def",
"self._recipient_id @recipient_id.setter def recipient_id(self, recipient_id): \"\"\"Sets the recipient_id of this",
"tab_label of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\"",
"= value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item:",
"# noqa: E501 :return: The scope of this ConditionalRecipientRuleFilter. #",
"operator(self): \"\"\"Gets the operator of this ConditionalRecipientRuleFilter. # noqa: E501",
"The scope of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str",
"noqa: E501 The unique identifier for the tab. The tabid",
"definition. \"\"\" swagger_types = { 'operator': 'str', 'recipient_id': 'str', 'scope':",
"this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._tab_type",
"<EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re #",
"is to sign the Document. # noqa: E501 :return: The",
"None self._value = None self.discriminator = None setattr(self, \"_{}\".format('operator'), kwargs.get('operator',",
"operator @property def recipient_id(self): \"\"\"Gets the recipient_id of this ConditionalRecipientRuleFilter.",
"= None self._value = None self.discriminator = None setattr(self, \"_{}\".format('operator'),",
"with a powerful, convenient, and simple Web services API for",
"dict): for key, value in self.items(): result[key] = value return",
"tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\"",
"tab_type @property def value(self): \"\"\"Gets the value of this ConditionalRecipientRuleFilter.",
"associated with the tab. # noqa: E501 :param tab_label: The",
"with the [ML:GET call]. # noqa: E501 :return: The tab_id",
":rtype: str \"\"\" return self._scope @scope.setter def scope(self, scope): \"\"\"Sets",
"noqa: E501 :rtype: str \"\"\" return self._tab_label @tab_label.setter def tab_label(self,",
"= Configuration() self._configuration = _configuration self._operator = None self._recipient_id =",
"{ 'operator': 'operator', 'recipient_id': 'recipientId', 'scope': 'scope', 'tab_id': 'tabId', 'tab_label':",
"the recipient. It is used by the tab element to",
":type: str \"\"\" self._scope = scope @property def tab_id(self): \"\"\"Gets",
"# noqa: E501 :param value: The value of this ConditionalRecipientRuleFilter.",
"ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._operator = operator",
"this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._tab_type =",
"the class manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The key",
"the swagger code generator program. Do not edit the class",
"recipient_id): \"\"\"Sets the recipient_id of this ConditionalRecipientRuleFilter. Unique for the",
"label string associated with the tab. # noqa: E501 :return:",
"@tab_id.setter def tab_id(self, tab_id): \"\"\"Sets the tab_id of this ConditionalRecipientRuleFilter.",
"pprint import re # noqa: F401 import six from docusign_esign.client.configuration",
"powerful, convenient, and simple Web services API for interacting with",
"Document. # noqa: E501 :param recipient_id: The recipient_id of this",
":rtype: str \"\"\" return self._tab_id @tab_id.setter def tab_id(self, tab_id): \"\"\"Sets",
"with the [ML:GET call]. # noqa: E501 :param tab_id: The",
"as a dict\"\"\" result = {} for attr, _ in",
"other): \"\"\"Returns true if both objects are not equal\"\"\" if",
"= value if issubclass(ConditionalRecipientRuleFilter, dict): for key, value in self.items():",
":param scope: The scope of this ConditionalRecipientRuleFilter. # noqa: E501",
"true if both objects are not equal\"\"\" if not isinstance(other,",
"None)) setattr(self, \"_{}\".format('scope'), kwargs.get('scope', None)) setattr(self, \"_{}\".format('tab_id'), kwargs.get('tab_id', None)) setattr(self,",
"scope of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\"",
"= { 'operator': 'str', 'recipient_id': 'str', 'scope': 'str', 'tab_id': 'str',",
":param operator: The operator of this ConditionalRecipientRuleFilter. # noqa: E501",
"this ConditionalRecipientRuleFilter. The unique identifier for the tab. The tabid",
"This class is auto generated by the swagger code generator",
"generated by the swagger code generator program. Do not edit",
"scope: The scope of this ConditionalRecipientRuleFilter. # noqa: E501 :type:",
"ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._tab_type = tab_type",
"isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if",
"ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._tab_label = tab_label",
"this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._scope",
"by the swagger code generator program. Do not edit the",
"result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\") else",
"to sign the Document. # noqa: E501 :param recipient_id: The",
"\"_{}\".format('tab_id'), kwargs.get('tab_id', None)) setattr(self, \"_{}\".format('tab_label'), kwargs.get('tab_label', None)) setattr(self, \"_{}\".format('tab_type'), kwargs.get('tab_type',",
"tab_label @property def tab_type(self): \"\"\"Gets the tab_type of this ConditionalRecipientRuleFilter.",
"attribute_map (dict): The key is attribute name and the value",
"elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr]",
"str \"\"\" return self._tab_label @tab_label.setter def tab_label(self, tab_label): \"\"\"Sets the",
"hasattr(x, \"to_dict\") else x, value )) elif hasattr(value, \"to_dict\"): result[attr]",
"call]. # noqa: E501 :param tab_id: The tab_id of this",
"attribute type. attribute_map (dict): The key is attribute name and",
"\"\"\" return self._operator @operator.setter def operator(self, operator): \"\"\"Sets the operator",
"recipient_id of this ConditionalRecipientRuleFilter. Unique for the recipient. It is",
"= scope @property def tab_id(self): \"\"\"Gets the tab_id of this",
"the string representation of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self):",
"return self._value @value.setter def value(self, value): \"\"\"Sets the value of",
":type: str \"\"\" self._recipient_id = recipient_id @property def scope(self): \"\"\"Gets",
"self._scope @scope.setter def scope(self, scope): \"\"\"Sets the scope of this",
"noqa: E501 :return: The tab_label of this ConditionalRecipientRuleFilter. # noqa:",
"\"\"\"Sets the tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 :param",
"for the tab. The tabid can be retrieved with the",
"_ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list):",
"ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str \"\"\" return self._tab_label @tab_label.setter",
"value: The value of this ConditionalRecipientRuleFilter. # noqa: E501 :type:",
"def tab_label(self): \"\"\"Gets the tab_label of this ConditionalRecipientRuleFilter. # noqa:",
"self._tab_label = None self._tab_type = None self._value = None self.discriminator",
"@property def value(self): \"\"\"Gets the value of this ConditionalRecipientRuleFilter. #",
"tab_type of this ConditionalRecipientRuleFilter. # noqa: E501 :param tab_type: The",
"dict\"\"\" result = {} for attr, _ in six.iteritems(self.swagger_types): value",
"the tab. # noqa: E501 :return: The tab_label of this",
"'str' } attribute_map = { 'operator': 'operator', 'recipient_id': 'recipientId', 'scope':",
"import re # noqa: F401 import six from docusign_esign.client.configuration import",
"\"\"\"Sets the scope of this ConditionalRecipientRuleFilter. # noqa: E501 :param",
"value of this ConditionalRecipientRuleFilter. Specifies the value of the tab.",
"attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict()",
"six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] =",
"objects are equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return False return",
"The tab_id of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str",
"The value of this ConditionalRecipientRuleFilter. # noqa: E501 :rtype: str",
"# noqa: E501 OpenAPI spec version: v2.1 Contact: <EMAIL> Generated",
"ConditionalRecipientRuleFilter. # noqa: E501 Unique for the recipient. It is",
"is attribute name and the value is attribute type. attribute_map",
"def scope(self): \"\"\"Gets the scope of this ConditionalRecipientRuleFilter. # noqa:",
"Do not edit the class manually. \"\"\" \"\"\" Attributes: swagger_types",
"def tab_label(self, tab_label): \"\"\"Sets the tab_label of this ConditionalRecipientRuleFilter. The",
"this ConditionalRecipientRuleFilter. # noqa: E501 :type: str \"\"\" self._tab_label =",
"The tab_label of this ConditionalRecipientRuleFilter. # noqa: E501 :type: str",
"objects are not equal\"\"\" if not isinstance(other, ConditionalRecipientRuleFilter): return True",
"class manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The key is",
":param tab_id: The tab_id of this ConditionalRecipientRuleFilter. # noqa: E501",
"result def to_str(self): \"\"\"Returns the string representation of the model\"\"\"",
"pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str() def",
"noqa: E501 :param tab_label: The tab_label of this ConditionalRecipientRuleFilter. #",
"for interacting with DocuSign. # noqa: E501 OpenAPI spec version:",
"value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map(",
"to_dict(self): \"\"\"Returns the model properties as a dict\"\"\" result =",
"# noqa: E501 :rtype: str \"\"\" return self._tab_label @tab_label.setter def",
"E501 :rtype: str \"\"\" return self._operator @operator.setter def operator(self, operator):",
"E501 :type: str \"\"\" self._operator = operator @property def recipient_id(self):",
"\"\"\" self._tab_label = tab_label @property def tab_type(self): \"\"\"Gets the tab_type",
"attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value,",
"# noqa: E501 if _configuration is None: _configuration = Configuration()",
"operator): \"\"\"Sets the operator of this ConditionalRecipientRuleFilter. # noqa: E501",
"\"\"\" self._tab_type = tab_type @property def value(self): \"\"\"Gets the value",
"setattr(self, \"_{}\".format('recipient_id'), kwargs.get('recipient_id', None)) setattr(self, \"_{}\".format('scope'), kwargs.get('scope', None)) setattr(self, \"_{}\".format('tab_id'),",
"is attribute type. attribute_map (dict): The key is attribute name",
"other.to_dict() def __ne__(self, other): \"\"\"Returns true if both objects are",
"operator: The operator of this ConditionalRecipientRuleFilter. # noqa: E501 :type:",
"Swagger\"\"\" # noqa: E501 if _configuration is None: _configuration ="
] |
[
"import checks class RouteConfig(AppConfig): \"\"\"The AppConfig for conman routes.\"\"\" name",
"'conman.routes' def ready(self): \"\"\"Register checks for conman routes.\"\"\" register(checks.polymorphic_installed) register(checks.subclasses_available)",
"= 'conman.routes' def ready(self): \"\"\"Register checks for conman routes.\"\"\" register(checks.polymorphic_installed)",
"register from . import checks class RouteConfig(AppConfig): \"\"\"The AppConfig for",
"routes.\"\"\" name = 'conman.routes' def ready(self): \"\"\"Register checks for conman",
"def ready(self): \"\"\"Register checks for conman routes.\"\"\" register(checks.polymorphic_installed) register(checks.subclasses_available) register(checks.subclasses_in_admin)",
"import AppConfig from django.core.checks import register from . import checks",
"import register from . import checks class RouteConfig(AppConfig): \"\"\"The AppConfig",
"\"\"\"The AppConfig for conman routes.\"\"\" name = 'conman.routes' def ready(self):",
"from django.apps import AppConfig from django.core.checks import register from .",
"name = 'conman.routes' def ready(self): \"\"\"Register checks for conman routes.\"\"\"",
"for conman routes.\"\"\" name = 'conman.routes' def ready(self): \"\"\"Register checks",
"from . import checks class RouteConfig(AppConfig): \"\"\"The AppConfig for conman",
". import checks class RouteConfig(AppConfig): \"\"\"The AppConfig for conman routes.\"\"\"",
"django.core.checks import register from . import checks class RouteConfig(AppConfig): \"\"\"The",
"checks class RouteConfig(AppConfig): \"\"\"The AppConfig for conman routes.\"\"\" name =",
"<reponame>meshy/django-conman from django.apps import AppConfig from django.core.checks import register from",
"django.apps import AppConfig from django.core.checks import register from . import",
"from django.core.checks import register from . import checks class RouteConfig(AppConfig):",
"conman routes.\"\"\" name = 'conman.routes' def ready(self): \"\"\"Register checks for",
"class RouteConfig(AppConfig): \"\"\"The AppConfig for conman routes.\"\"\" name = 'conman.routes'",
"AppConfig for conman routes.\"\"\" name = 'conman.routes' def ready(self): \"\"\"Register",
"RouteConfig(AppConfig): \"\"\"The AppConfig for conman routes.\"\"\" name = 'conman.routes' def",
"AppConfig from django.core.checks import register from . import checks class"
] |
[
"\"\"\" Get all TM1 transactions for all cubes starting to",
"to a specific date. \"\"\" import configparser config = configparser.ConfigParser()",
"second=0) # Get all entries since timestamp entries = tm1.server.get_transaction_log_entries(since=timestamp)",
"= tm1.server.get_transaction_log_entries(since=timestamp) # loop through entries for entry in entries:",
"# Get all entries since timestamp entries = tm1.server.get_transaction_log_entries(since=timestamp) #",
"date. \"\"\" import configparser config = configparser.ConfigParser() config.read('..\\config.ini') from datetime",
"from datetime import datetime from TM1py.Services import TM1Service with TM1Service(**config['tm1srv01'])",
"timestamp = datetime(year=2018, month=2, day=15, hour=16, minute=2, second=0) # Get",
"Message-Log parsing timestamp = datetime(year=2018, month=2, day=15, hour=16, minute=2, second=0)",
"TM1 transactions for all cubes starting to a specific date.",
"specific date. \"\"\" import configparser config = configparser.ConfigParser() config.read('..\\config.ini') from",
"timestamp entries = tm1.server.get_transaction_log_entries(since=timestamp) # loop through entries for entry",
"from TM1py.Services import TM1Service with TM1Service(**config['tm1srv01']) as tm1: # Timestamp",
"hour=16, minute=2, second=0) # Get all entries since timestamp entries",
"starting to a specific date. \"\"\" import configparser config =",
"# loop through entries for entry in entries: # Do",
"TM1py.Services import TM1Service with TM1Service(**config['tm1srv01']) as tm1: # Timestamp for",
"configparser.ConfigParser() config.read('..\\config.ini') from datetime import datetime from TM1py.Services import TM1Service",
"Timestamp for Message-Log parsing timestamp = datetime(year=2018, month=2, day=15, hour=16,",
"entries since timestamp entries = tm1.server.get_transaction_log_entries(since=timestamp) # loop through entries",
"config = configparser.ConfigParser() config.read('..\\config.ini') from datetime import datetime from TM1py.Services",
"month=2, day=15, hour=16, minute=2, second=0) # Get all entries since",
"timestamp.py \"\"\" Get all TM1 transactions for all cubes starting",
"parsing timestamp = datetime(year=2018, month=2, day=15, hour=16, minute=2, second=0) #",
"Get all entries since timestamp entries = tm1.server.get_transaction_log_entries(since=timestamp) # loop",
"import datetime from TM1py.Services import TM1Service with TM1Service(**config['tm1srv01']) as tm1:",
"since timestamp.py \"\"\" Get all TM1 transactions for all cubes",
"cubes starting to a specific date. \"\"\" import configparser config",
"import TM1Service with TM1Service(**config['tm1srv01']) as tm1: # Timestamp for Message-Log",
"all TM1 transactions for all cubes starting to a specific",
"day=15, hour=16, minute=2, second=0) # Get all entries since timestamp",
"minute=2, second=0) # Get all entries since timestamp entries =",
"# Timestamp for Message-Log parsing timestamp = datetime(year=2018, month=2, day=15,",
"TM1Service(**config['tm1srv01']) as tm1: # Timestamp for Message-Log parsing timestamp =",
"= datetime(year=2018, month=2, day=15, hour=16, minute=2, second=0) # Get all",
"= configparser.ConfigParser() config.read('..\\config.ini') from datetime import datetime from TM1py.Services import",
"datetime from TM1py.Services import TM1Service with TM1Service(**config['tm1srv01']) as tm1: #",
"\"\"\" import configparser config = configparser.ConfigParser() config.read('..\\config.ini') from datetime import",
"with TM1Service(**config['tm1srv01']) as tm1: # Timestamp for Message-Log parsing timestamp",
"a specific date. \"\"\" import configparser config = configparser.ConfigParser() config.read('..\\config.ini')",
"import configparser config = configparser.ConfigParser() config.read('..\\config.ini') from datetime import datetime",
"datetime import datetime from TM1py.Services import TM1Service with TM1Service(**config['tm1srv01']) as",
"all cubes starting to a specific date. \"\"\" import configparser",
"datetime(year=2018, month=2, day=15, hour=16, minute=2, second=0) # Get all entries",
"all entries since timestamp entries = tm1.server.get_transaction_log_entries(since=timestamp) # loop through",
"through entries for entry in entries: # Do stuff print(entry['TimeStamp'],",
"<filename>Other/transactionlog entries since timestamp.py \"\"\" Get all TM1 transactions for",
"entries since timestamp.py \"\"\" Get all TM1 transactions for all",
"config.read('..\\config.ini') from datetime import datetime from TM1py.Services import TM1Service with",
"as tm1: # Timestamp for Message-Log parsing timestamp = datetime(year=2018,",
"entries for entry in entries: # Do stuff print(entry['TimeStamp'], entry)",
"for all cubes starting to a specific date. \"\"\" import",
"since timestamp entries = tm1.server.get_transaction_log_entries(since=timestamp) # loop through entries for",
"Get all TM1 transactions for all cubes starting to a",
"TM1Service with TM1Service(**config['tm1srv01']) as tm1: # Timestamp for Message-Log parsing",
"tm1: # Timestamp for Message-Log parsing timestamp = datetime(year=2018, month=2,",
"tm1.server.get_transaction_log_entries(since=timestamp) # loop through entries for entry in entries: #",
"for Message-Log parsing timestamp = datetime(year=2018, month=2, day=15, hour=16, minute=2,",
"loop through entries for entry in entries: # Do stuff",
"entries = tm1.server.get_transaction_log_entries(since=timestamp) # loop through entries for entry in",
"transactions for all cubes starting to a specific date. \"\"\"",
"configparser config = configparser.ConfigParser() config.read('..\\config.ini') from datetime import datetime from"
] |
[
"{}'.format(rna)) sequences_dict[rna] = ''.join(['N'] * len(observations_dict[rna])) for rna in sequences_rnas.difference(observations_rnas):",
"np.percentile(finite_obs, (25, 75)) self.stats['P40'], self.stats['P60'] = np.percentile(finite_obs, (40, 60)) self.stats['n_obs']",
"training. \"\"\" finite_obs = [] total_obs = 0 up_ref =",
"\"\"\" training_transcripts = [] training_obs = [] kl_div_set = 1.0",
"bins=self.stats['histogram_bins'], density=True) def spawn_training_set(self, kl_div): \"\"\" Spawn a training set",
"log_flag=False): observations_dict = filelib.parse_observations(self.fp_obs) observations_rnas = set(observations_dict.keys()) dataset_rnas = observations_rnas",
"<filename>src/patteRNA/Dataset.py import logging import numpy as np from scipy.stats import",
"Cross reference input files to confirm all transcripts for rna",
"Parse all finite observations in the input file and compute",
"== 'DOM': for rna in self.rnas: model.emission_model.discretize(self.rnas[rna]) if scoring: for",
"return spawned_set def spawn_reference_set(self): spawned_set = Dataset(fp_observations=None, fp_references=None, fp_sequences=None) references",
"up_ref += int(np.sum(self.rnas[rna].ref == 0)) p_ref += int(np.sum(self.rnas[rna].ref == 1))",
"key=lambda transcript: transcript.density, reverse=True) logger.info(' ... selecting') while kl_div_set >",
"scoring: for rna in self.rnas.values(): model.e_step(rna) rna.compute_log_B_ratios() def get_emissions(self, model):",
"for rna in self.rnas: model.emission_model.compute_emissions(self.rnas[rna]) def spawn_set(self, rnas): spawned_set =",
"self.spawn_set(rnas=training_transcripts) training_set.compute_stats() return training_set, kl_div_set def pre_process(self, model, scoring=False): if",
"75)) self.stats['P40'], self.stats['P60'] = np.percentile(finite_obs, (40, 60)) self.stats['n_obs'] = len(finite_obs)",
"in self.rnas if self.rnas[rna].ref is not None] spawned_set.rnas = {rna:",
"transcripts first) until the training set's KL divergence from the",
"model.emission_model.type == 'DOM': for rna in self.rnas: model.emission_model.discretize(self.rnas[rna]) if scoring:",
"= Transcript(rna_name, sequences_dict[rna_name], observations_dict[rna_name]) else: self.rnas[rna_name] = Transcript(rna_name, 'N' *",
"numpy as np from scipy.stats import entropy from patteRNA.Transcript import",
"model.emission_model.discretize(self.rnas[rna]) if scoring: for rna in self.rnas.values(): model.e_step(rna) rna.compute_log_B_ratios() def",
"rna in references} spawned_set.compute_stats() return spawned_set def clear(self): self.rnas =",
"scoring=False): if model.emission_model.type == 'DOM': for rna in self.rnas: model.emission_model.discretize(self.rnas[rna])",
"spawn_set(self, rnas): spawned_set = Dataset(fp_observations=None, fp_sequences=None, fp_references=None) spawned_set.rnas = {rna:",
"rna in self.rnas: finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)]) total_obs += len(self.rnas[rna].obs) up_ref += int(np.sum(self.rnas[rna].ref",
"= total_obs self.stats['continuous_variance'] = np.var(finite_obs) self.stats['minimum'] = np.min(finite_obs) self.stats['maximum'] =",
"for rna in references} spawned_set.compute_stats() return spawned_set def clear(self): self.rnas",
"dict() def load_rnas(self, log_flag=False): observations_dict = filelib.parse_observations(self.fp_obs) observations_rnas = set(observations_dict.keys())",
"np.linspace(self.stats['minimum'], self.stats['maximum'], 20) self.stats['histogram'], _ = np.histogram(finite_obs, bins=self.stats['histogram_bins'], density=True) def",
"\"\"\" Spawn a training set (smaller than or equal size",
"for rna in self.rnas: model.emission_model.discretize(self.rnas[rna]) if scoring: for rna in",
"self.rnas[rna] for rna in references} spawned_set.compute_stats() return spawned_set def clear(self):",
"= None if self.fp_fasta: sequences_dict = filelib.parse_fasta(self.fp_fasta) sequences_rnas = set(sequences_dict.keys())",
"rna in self.rnas.values(): model.e_step(rna) rna.compute_log_B_ratios() def get_emissions(self, model): for rna",
"= dict() self.stats = dict() def load_rnas(self, log_flag=False): observations_dict =",
"observations_dict[rna_name]) if log_flag: for rna in self.rnas: self.rnas[rna].log_transform() self.compute_stats() def",
"set's KL divergence from the overall data falls below the",
"self.rnas: model.emission_model.compute_emissions(self.rnas[rna]) def spawn_set(self, rnas): spawned_set = Dataset(fp_observations=None, fp_sequences=None, fp_references=None)",
"from scipy.stats import entropy from patteRNA.Transcript import Transcript from patteRNA",
"if log_flag: for rna in self.rnas: self.rnas[rna].log_transform() self.compute_stats() def compute_stats(self):",
"set (smaller than or equal size to overall data) based",
"fp_references=None): self.fp_obs = fp_observations self.fp_fasta = fp_sequences self.fp_refs = fp_references",
"np.tile(np.nan, len(sequences_dict[rna])) dataset_rnas.update(sequences_rnas) for rna_name in dataset_rnas: if self.fp_fasta: self.rnas[rna_name]",
"self.rnas: model.emission_model.discretize(self.rnas[rna]) if scoring: for rna in self.rnas.values(): model.e_step(rna) rna.compute_log_B_ratios()",
"fp_references=None, fp_sequences=None) references = [rna for rna in self.rnas if",
"RNA: {}'.format(rna)) sequences_dict[rna] = ''.join(['N'] * len(observations_dict[rna])) for rna in",
"np from scipy.stats import entropy from patteRNA.Transcript import Transcript from",
"based on KL divergence criteria. Transcripts are incrementally added to",
"rna.compute_log_B_ratios() def get_emissions(self, model): for rna in self.rnas: model.emission_model.compute_emissions(self.rnas[rna]) def",
"= [] training_obs = [] kl_div_set = 1.0 group_size =",
"in self.rnas: self.rnas[rna].log_transform() self.compute_stats() def compute_stats(self): \"\"\" Parse all finite",
"threshold. \"\"\" training_transcripts = [] training_obs = [] kl_div_set =",
"if self.fp_fasta: sequences_dict = filelib.parse_fasta(self.fp_fasta) sequences_rnas = set(sequences_dict.keys()) # Cross",
"up_ref self.stats['p_ref'] = p_ref self.stats['total_obs'] = total_obs self.stats['continuous_variance'] = np.var(finite_obs)",
"= {rna: self.rnas[rna] for rna in rnas} return spawned_set def",
"self.stats['P60'] = np.percentile(finite_obs, (40, 60)) self.stats['n_obs'] = len(finite_obs) self.stats['up_ref'] =",
"observations in the input file and compute some statistics on",
"len(sequences_dict[rna])) dataset_rnas.update(sequences_rnas) for rna_name in dataset_rnas: if self.fp_fasta: self.rnas[rna_name] =",
"= np.quantile(finite_obs, self.stats[\"quantile_basis\"]) self.stats['P25'], self.stats['P75'] = np.percentile(finite_obs, (25, 75)) self.stats['P40'],",
"kl_div_set = 1.0 group_size = 20 logger.info(' ... sorting') rnas_sd",
"self.stats['maximum'] = np.max(finite_obs) self.stats['finite_obs'] = finite_obs self.stats['histogram_bins'] = np.linspace(self.stats['minimum'], self.stats['maximum'],",
"on the data. These statistics are mostly used to initialize",
"in rnas: training_transcripts.append(rna.name) training_obs.extend(rna.obs[rna.mask_finite]) training_histogram, _ = np.histogram(training_obs, bins=self.stats['histogram_bins'], density=True)",
"to initialize parameters of the emission model before training. \"\"\"",
"provided threshold. \"\"\" training_transcripts = [] training_obs = [] kl_div_set",
"= [] for rna in rnas: training_transcripts.append(rna.name) training_obs.extend(rna.obs[rna.mask_finite]) training_histogram, _",
"for rna in sequences_rnas.difference(observations_rnas): print('WARNING - No probing data found",
"20) self.stats['histogram'], _ = np.histogram(finite_obs, bins=self.stats['histogram_bins'], density=True) def spawn_training_set(self, kl_div):",
"finite observations in the input file and compute some statistics",
"+= int(np.sum(self.rnas[rna].ref == 0)) p_ref += int(np.sum(self.rnas[rna].ref == 1)) self.stats['quantile_basis']",
"training_transcripts = [] training_obs = [] kl_div_set = 1.0 group_size",
"some statistics on the data. These statistics are mostly used",
"kl_div): \"\"\" Spawn a training set (smaller than or equal",
"training_set.compute_stats() return training_set, kl_div_set def pre_process(self, model, scoring=False): if model.emission_model.type",
"fp_references self.rnas = dict() self.stats = dict() def load_rnas(self, log_flag=False):",
"kl_div_set = entropy(training_histogram, self.stats['histogram']) training_set = self.spawn_set(rnas=training_transcripts) training_set.compute_stats() return training_set,",
"self.fp_fasta = fp_sequences self.fp_refs = fp_references self.rnas = dict() self.stats",
"than or equal size to overall data) based on KL",
"'DOM': for rna in self.rnas: model.emission_model.discretize(self.rnas[rna]) if scoring: for rna",
"not None] spawned_set.rnas = {rna: self.rnas[rna] for rna in references}",
"self.rnas[rna].ref is not None] spawned_set.rnas = {rna: self.rnas[rna] for rna",
"= len(finite_obs) self.stats['up_ref'] = up_ref self.stats['p_ref'] = p_ref self.stats['total_obs'] =",
"= rnas_sd[:group_size] rnas_sd[:group_size] = [] for rna in rnas: training_transcripts.append(rna.name)",
"np.quantile(finite_obs, self.stats[\"quantile_basis\"]) self.stats['P25'], self.stats['P75'] = np.percentile(finite_obs, (25, 75)) self.stats['P40'], self.stats['P60']",
"import logging import numpy as np from scipy.stats import entropy",
"= Dataset(fp_observations=None, fp_references=None, fp_sequences=None) references = [rna for rna in",
"sequence found for RNA: {}'.format(rna)) sequences_dict[rna] = ''.join(['N'] * len(observations_dict[rna]))",
"the data. These statistics are mostly used to initialize parameters",
"= sorted(self.rnas.values(), key=lambda transcript: transcript.density, reverse=True) logger.info(' ... selecting') while",
"fp_sequences=None) references = [rna for rna in self.rnas if self.rnas[rna].ref",
"= np.histogram(finite_obs, bins=self.stats['histogram_bins'], density=True) def spawn_training_set(self, kl_div): \"\"\" Spawn a",
"self.stats['n_obs'] = len(finite_obs) self.stats['up_ref'] = up_ref self.stats['p_ref'] = p_ref self.stats['total_obs']",
"= self.spawn_set(rnas=training_transcripts) training_set.compute_stats() return training_set, kl_div_set def pre_process(self, model, scoring=False):",
"rna in observations_rnas.difference(sequences_rnas): print('WARNING - No sequence found for RNA:",
"'N' * len(observations_dict[rna_name]), observations_dict[rna_name]) if log_flag: for rna in self.rnas:",
"rnas} return spawned_set def spawn_reference_set(self): spawned_set = Dataset(fp_observations=None, fp_references=None, fp_sequences=None)",
"while kl_div_set > kl_div and rnas_sd: rnas = rnas_sd[:group_size] rnas_sd[:group_size]",
"in dataset_rnas: if self.fp_fasta: self.rnas[rna_name] = Transcript(rna_name, sequences_dict[rna_name], observations_dict[rna_name]) else:",
"emission model before training. \"\"\" finite_obs = [] total_obs =",
"probing data found for RNA: {}'.format(rna)) observations_dict[rna] = np.tile(np.nan, len(sequences_dict[rna]))",
"return training_set, kl_div_set def pre_process(self, model, scoring=False): if model.emission_model.type ==",
"files to confirm all transcripts for rna in observations_rnas.difference(sequences_rnas): print('WARNING",
"= dict() def load_rnas(self, log_flag=False): observations_dict = filelib.parse_observations(self.fp_obs) observations_rnas =",
"self.stats['quantiles'] = np.quantile(finite_obs, self.stats[\"quantile_basis\"]) self.stats['P25'], self.stats['P75'] = np.percentile(finite_obs, (25, 75))",
"get_emissions(self, model): for rna in self.rnas: model.emission_model.compute_emissions(self.rnas[rna]) def spawn_set(self, rnas):",
"below the provided threshold. \"\"\" training_transcripts = [] training_obs =",
"log_flag: for rna in self.rnas: self.rnas[rna].log_transform() self.compute_stats() def compute_stats(self): \"\"\"",
"found for RNA: {}'.format(rna)) sequences_dict[rna] = ''.join(['N'] * len(observations_dict[rna])) for",
"compute some statistics on the data. These statistics are mostly",
"[] kl_div_set = 1.0 group_size = 20 logger.info(' ... sorting')",
"rna in self.rnas: model.emission_model.discretize(self.rnas[rna]) if scoring: for rna in self.rnas.values():",
"spawned_set = Dataset(fp_observations=None, fp_sequences=None, fp_references=None) spawned_set.rnas = {rna: self.rnas[rna] for",
"= np.tile(np.nan, len(sequences_dict[rna])) dataset_rnas.update(sequences_rnas) for rna_name in dataset_rnas: if self.fp_fasta:",
"p_ref += int(np.sum(self.rnas[rna].ref == 1)) self.stats['quantile_basis'] = np.linspace(0, 1, 1000)",
"model.e_step(rna) rna.compute_log_B_ratios() def get_emissions(self, model): for rna in self.rnas: model.emission_model.compute_emissions(self.rnas[rna])",
"def load_rnas(self, log_flag=False): observations_dict = filelib.parse_observations(self.fp_obs) observations_rnas = set(observations_dict.keys()) dataset_rnas",
"if self.fp_fasta: self.rnas[rna_name] = Transcript(rna_name, sequences_dict[rna_name], observations_dict[rna_name]) else: self.rnas[rna_name] =",
"- No probing data found for RNA: {}'.format(rna)) observations_dict[rna] =",
"self.stats['finite_obs'] = finite_obs self.stats['histogram_bins'] = np.linspace(self.stats['minimum'], self.stats['maximum'], 20) self.stats['histogram'], _",
"= [] kl_div_set = 1.0 group_size = 20 logger.info(' ...",
"filelib.parse_fasta(self.fp_fasta) sequences_rnas = set(sequences_dict.keys()) # Cross reference input files to",
"for rna in self.rnas.values(): model.e_step(rna) rna.compute_log_B_ratios() def get_emissions(self, model): for",
"rnas): spawned_set = Dataset(fp_observations=None, fp_sequences=None, fp_references=None) spawned_set.rnas = {rna: self.rnas[rna]",
"or equal size to overall data) based on KL divergence",
"= 0 up_ref = 0 p_ref = 0 for rna",
"logger.info(' ... selecting') while kl_div_set > kl_div and rnas_sd: rnas",
"self.rnas.values(): model.e_step(rna) rna.compute_log_B_ratios() def get_emissions(self, model): for rna in self.rnas:",
"set(sequences_dict.keys()) # Cross reference input files to confirm all transcripts",
"= np.min(finite_obs) self.stats['maximum'] = np.max(finite_obs) self.stats['finite_obs'] = finite_obs self.stats['histogram_bins'] =",
"+= len(self.rnas[rna].obs) up_ref += int(np.sum(self.rnas[rna].ref == 0)) p_ref += int(np.sum(self.rnas[rna].ref",
"Dataset (high quality transcripts first) until the training set's KL",
"self.stats['histogram']) training_set = self.spawn_set(rnas=training_transcripts) training_set.compute_stats() return training_set, kl_div_set def pre_process(self,",
"* len(observations_dict[rna_name]), observations_dict[rna_name]) if log_flag: for rna in self.rnas: self.rnas[rna].log_transform()",
"and compute some statistics on the data. These statistics are",
"rnas_sd[:group_size] = [] for rna in rnas: training_transcripts.append(rna.name) training_obs.extend(rna.obs[rna.mask_finite]) training_histogram,",
"= Transcript(rna_name, 'N' * len(observations_dict[rna_name]), observations_dict[rna_name]) if log_flag: for rna",
"\"\"\" Parse all finite observations in the input file and",
"0 up_ref = 0 p_ref = 0 for rna in",
"if self.rnas[rna].ref is not None] spawned_set.rnas = {rna: self.rnas[rna] for",
"1.0 group_size = 20 logger.info(' ... sorting') rnas_sd = sorted(self.rnas.values(),",
"def __init__(self, fp_observations, fp_sequences=None, fp_references=None): self.fp_obs = fp_observations self.fp_fasta =",
"spawned_set def spawn_reference_set(self): spawned_set = Dataset(fp_observations=None, fp_references=None, fp_sequences=None) references =",
"self.stats['quantile_basis'] = np.linspace(0, 1, 1000) self.stats['quantiles'] = np.quantile(finite_obs, self.stats[\"quantile_basis\"]) self.stats['P25'],",
"data falls below the provided threshold. \"\"\" training_transcripts = []",
"0 p_ref = 0 for rna in self.rnas: finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)]) total_obs",
"spawn_reference_set(self): spawned_set = Dataset(fp_observations=None, fp_references=None, fp_sequences=None) references = [rna for",
"+= int(np.sum(self.rnas[rna].ref == 1)) self.stats['quantile_basis'] = np.linspace(0, 1, 1000) self.stats['quantiles']",
"= 0 p_ref = 0 for rna in self.rnas: finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)])",
"in self.rnas.values(): model.e_step(rna) rna.compute_log_B_ratios() def get_emissions(self, model): for rna in",
"sequences_rnas = set(sequences_dict.keys()) # Cross reference input files to confirm",
"= filelib.parse_fasta(self.fp_fasta) sequences_rnas = set(sequences_dict.keys()) # Cross reference input files",
"statistics on the data. These statistics are mostly used to",
"np.min(finite_obs) self.stats['maximum'] = np.max(finite_obs) self.stats['finite_obs'] = finite_obs self.stats['histogram_bins'] = np.linspace(self.stats['minimum'],",
"self.rnas = dict() self.stats = dict() def load_rnas(self, log_flag=False): observations_dict",
"len(finite_obs) self.stats['up_ref'] = up_ref self.stats['p_ref'] = p_ref self.stats['total_obs'] = total_obs",
"if scoring: for rna in self.rnas.values(): model.e_step(rna) rna.compute_log_B_ratios() def get_emissions(self,",
"fp_references=None) spawned_set.rnas = {rna: self.rnas[rna] for rna in rnas} return",
"len(self.rnas[rna].obs) up_ref += int(np.sum(self.rnas[rna].ref == 0)) p_ref += int(np.sum(self.rnas[rna].ref ==",
"p_ref = 0 for rna in self.rnas: finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)]) total_obs +=",
"= ''.join(['N'] * len(observations_dict[rna])) for rna in sequences_rnas.difference(observations_rnas): print('WARNING -",
"These statistics are mostly used to initialize parameters of the",
"* len(observations_dict[rna])) for rna in sequences_rnas.difference(observations_rnas): print('WARNING - No probing",
"= entropy(training_histogram, self.stats['histogram']) training_set = self.spawn_set(rnas=training_transcripts) training_set.compute_stats() return training_set, kl_div_set",
"the emission model before training. \"\"\" finite_obs = [] total_obs",
"bins=self.stats['histogram_bins'], density=True) kl_div_set = entropy(training_histogram, self.stats['histogram']) training_set = self.spawn_set(rnas=training_transcripts) training_set.compute_stats()",
"group_size = 20 logger.info(' ... sorting') rnas_sd = sorted(self.rnas.values(), key=lambda",
"= np.var(finite_obs) self.stats['minimum'] = np.min(finite_obs) self.stats['maximum'] = np.max(finite_obs) self.stats['finite_obs'] =",
"{rna: self.rnas[rna] for rna in rnas} return spawned_set def spawn_reference_set(self):",
"in self.rnas: model.emission_model.compute_emissions(self.rnas[rna]) def spawn_set(self, rnas): spawned_set = Dataset(fp_observations=None, fp_sequences=None,",
"= [rna for rna in self.rnas if self.rnas[rna].ref is not",
"60)) self.stats['n_obs'] = len(finite_obs) self.stats['up_ref'] = up_ref self.stats['p_ref'] = p_ref",
"rna in rnas: training_transcripts.append(rna.name) training_obs.extend(rna.obs[rna.mask_finite]) training_histogram, _ = np.histogram(training_obs, bins=self.stats['histogram_bins'],",
"= 1.0 group_size = 20 logger.info(' ... sorting') rnas_sd =",
"np.var(finite_obs) self.stats['minimum'] = np.min(finite_obs) self.stats['maximum'] = np.max(finite_obs) self.stats['finite_obs'] = finite_obs",
"sequences_rnas.difference(observations_rnas): print('WARNING - No probing data found for RNA: {}'.format(rna))",
"divergence criteria. Transcripts are incrementally added to a training Dataset",
"self.compute_stats() def compute_stats(self): \"\"\" Parse all finite observations in the",
"rna_name in dataset_rnas: if self.fp_fasta: self.rnas[rna_name] = Transcript(rna_name, sequences_dict[rna_name], observations_dict[rna_name])",
"Transcript(rna_name, sequences_dict[rna_name], observations_dict[rna_name]) else: self.rnas[rna_name] = Transcript(rna_name, 'N' * len(observations_dict[rna_name]),",
"the overall data falls below the provided threshold. \"\"\" training_transcripts",
"input files to confirm all transcripts for rna in observations_rnas.difference(sequences_rnas):",
"self.stats = dict() def load_rnas(self, log_flag=False): observations_dict = filelib.parse_observations(self.fp_obs) observations_rnas",
"references = [rna for rna in self.rnas if self.rnas[rna].ref is",
"np.histogram(training_obs, bins=self.stats['histogram_bins'], density=True) kl_div_set = entropy(training_histogram, self.stats['histogram']) training_set = self.spawn_set(rnas=training_transcripts)",
"for rna in self.rnas: self.rnas[rna].log_transform() self.compute_stats() def compute_stats(self): \"\"\" Parse",
"for rna in self.rnas if self.rnas[rna].ref is not None] spawned_set.rnas",
"observations_rnas sequences_dict = None if self.fp_fasta: sequences_dict = filelib.parse_fasta(self.fp_fasta) sequences_rnas",
"import filelib logger = logging.getLogger(__name__) class Dataset: def __init__(self, fp_observations,",
"selecting') while kl_div_set > kl_div and rnas_sd: rnas = rnas_sd[:group_size]",
"input file and compute some statistics on the data. These",
"model before training. \"\"\" finite_obs = [] total_obs = 0",
"int(np.sum(self.rnas[rna].ref == 1)) self.stats['quantile_basis'] = np.linspace(0, 1, 1000) self.stats['quantiles'] =",
"training_obs = [] kl_div_set = 1.0 group_size = 20 logger.info('",
"confirm all transcripts for rna in observations_rnas.difference(sequences_rnas): print('WARNING - No",
"= [] total_obs = 0 up_ref = 0 p_ref =",
"print('WARNING - No sequence found for RNA: {}'.format(rna)) sequences_dict[rna] =",
"in references} spawned_set.compute_stats() return spawned_set def clear(self): self.rnas = None",
"Transcript(rna_name, 'N' * len(observations_dict[rna_name]), observations_dict[rna_name]) if log_flag: for rna in",
"load_rnas(self, log_flag=False): observations_dict = filelib.parse_observations(self.fp_obs) observations_rnas = set(observations_dict.keys()) dataset_rnas =",
"self.rnas[rna_name] = Transcript(rna_name, 'N' * len(observations_dict[rna_name]), observations_dict[rna_name]) if log_flag: for",
"dict() self.stats = dict() def load_rnas(self, log_flag=False): observations_dict = filelib.parse_observations(self.fp_obs)",
"observations_rnas = set(observations_dict.keys()) dataset_rnas = observations_rnas sequences_dict = None if",
"logging import numpy as np from scipy.stats import entropy from",
"np.linspace(0, 1, 1000) self.stats['quantiles'] = np.quantile(finite_obs, self.stats[\"quantile_basis\"]) self.stats['P25'], self.stats['P75'] =",
"patteRNA.Transcript import Transcript from patteRNA import filelib logger = logging.getLogger(__name__)",
"= finite_obs self.stats['histogram_bins'] = np.linspace(self.stats['minimum'], self.stats['maximum'], 20) self.stats['histogram'], _ =",
"import entropy from patteRNA.Transcript import Transcript from patteRNA import filelib",
"observations_rnas.difference(sequences_rnas): print('WARNING - No sequence found for RNA: {}'.format(rna)) sequences_dict[rna]",
"self.rnas[rna].log_transform() self.compute_stats() def compute_stats(self): \"\"\" Parse all finite observations in",
"self.stats['histogram_bins'] = np.linspace(self.stats['minimum'], self.stats['maximum'], 20) self.stats['histogram'], _ = np.histogram(finite_obs, bins=self.stats['histogram_bins'],",
"rnas_sd[:group_size] rnas_sd[:group_size] = [] for rna in rnas: training_transcripts.append(rna.name) training_obs.extend(rna.obs[rna.mask_finite])",
"rnas: training_transcripts.append(rna.name) training_obs.extend(rna.obs[rna.mask_finite]) training_histogram, _ = np.histogram(training_obs, bins=self.stats['histogram_bins'], density=True) kl_div_set",
"in self.rnas: finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)]) total_obs += len(self.rnas[rna].obs) up_ref += int(np.sum(self.rnas[rna].ref ==",
"entropy from patteRNA.Transcript import Transcript from patteRNA import filelib logger",
"int(np.sum(self.rnas[rna].ref == 0)) p_ref += int(np.sum(self.rnas[rna].ref == 1)) self.stats['quantile_basis'] =",
"rna in self.rnas if self.rnas[rna].ref is not None] spawned_set.rnas =",
"= logging.getLogger(__name__) class Dataset: def __init__(self, fp_observations, fp_sequences=None, fp_references=None): self.fp_obs",
"RNA: {}'.format(rna)) observations_dict[rna] = np.tile(np.nan, len(sequences_dict[rna])) dataset_rnas.update(sequences_rnas) for rna_name in",
"density=True) def spawn_training_set(self, kl_div): \"\"\" Spawn a training set (smaller",
"_ = np.histogram(finite_obs, bins=self.stats['histogram_bins'], density=True) def spawn_training_set(self, kl_div): \"\"\" Spawn",
"self.stats['up_ref'] = up_ref self.stats['p_ref'] = p_ref self.stats['total_obs'] = total_obs self.stats['continuous_variance']",
"transcripts for rna in observations_rnas.difference(sequences_rnas): print('WARNING - No sequence found",
"self.rnas[rna_name] = Transcript(rna_name, sequences_dict[rna_name], observations_dict[rna_name]) else: self.rnas[rna_name] = Transcript(rna_name, 'N'",
"compute_stats(self): \"\"\" Parse all finite observations in the input file",
"for rna in self.rnas: finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)]) total_obs += len(self.rnas[rna].obs) up_ref +=",
"No probing data found for RNA: {}'.format(rna)) observations_dict[rna] = np.tile(np.nan,",
"training_histogram, _ = np.histogram(training_obs, bins=self.stats['histogram_bins'], density=True) kl_div_set = entropy(training_histogram, self.stats['histogram'])",
"filelib.parse_observations(self.fp_obs) observations_rnas = set(observations_dict.keys()) dataset_rnas = observations_rnas sequences_dict = None",
"rnas_sd = sorted(self.rnas.values(), key=lambda transcript: transcript.density, reverse=True) logger.info(' ... selecting')",
"the input file and compute some statistics on the data.",
"return spawned_set def clear(self): self.rnas = None self.stats = None",
"density=True) kl_div_set = entropy(training_histogram, self.stats['histogram']) training_set = self.spawn_set(rnas=training_transcripts) training_set.compute_stats() return",
"else: self.rnas[rna_name] = Transcript(rna_name, 'N' * len(observations_dict[rna_name]), observations_dict[rna_name]) if log_flag:",
"spawned_set = Dataset(fp_observations=None, fp_references=None, fp_sequences=None) references = [rna for rna",
"spawned_set.rnas = {rna: self.rnas[rna] for rna in references} spawned_set.compute_stats() return",
"= fp_sequences self.fp_refs = fp_references self.rnas = dict() self.stats =",
"= p_ref self.stats['total_obs'] = total_obs self.stats['continuous_variance'] = np.var(finite_obs) self.stats['minimum'] =",
"patteRNA import filelib logger = logging.getLogger(__name__) class Dataset: def __init__(self,",
"Dataset(fp_observations=None, fp_sequences=None, fp_references=None) spawned_set.rnas = {rna: self.rnas[rna] for rna in",
"(25, 75)) self.stats['P40'], self.stats['P60'] = np.percentile(finite_obs, (40, 60)) self.stats['n_obs'] =",
"import numpy as np from scipy.stats import entropy from patteRNA.Transcript",
"divergence from the overall data falls below the provided threshold.",
"filelib logger = logging.getLogger(__name__) class Dataset: def __init__(self, fp_observations, fp_sequences=None,",
"on KL divergence criteria. Transcripts are incrementally added to a",
"p_ref self.stats['total_obs'] = total_obs self.stats['continuous_variance'] = np.var(finite_obs) self.stats['minimum'] = np.min(finite_obs)",
"entropy(training_histogram, self.stats['histogram']) training_set = self.spawn_set(rnas=training_transcripts) training_set.compute_stats() return training_set, kl_div_set def",
"= np.linspace(self.stats['minimum'], self.stats['maximum'], 20) self.stats['histogram'], _ = np.histogram(finite_obs, bins=self.stats['histogram_bins'], density=True)",
"first) until the training set's KL divergence from the overall",
"for RNA: {}'.format(rna)) sequences_dict[rna] = ''.join(['N'] * len(observations_dict[rna])) for rna",
"sorting') rnas_sd = sorted(self.rnas.values(), key=lambda transcript: transcript.density, reverse=True) logger.info(' ...",
"self.rnas if self.rnas[rna].ref is not None] spawned_set.rnas = {rna: self.rnas[rna]",
"self.stats[\"quantile_basis\"]) self.stats['P25'], self.stats['P75'] = np.percentile(finite_obs, (25, 75)) self.stats['P40'], self.stats['P60'] =",
"for RNA: {}'.format(rna)) observations_dict[rna] = np.tile(np.nan, len(sequences_dict[rna])) dataset_rnas.update(sequences_rnas) for rna_name",
"quality transcripts first) until the training set's KL divergence from",
"rnas_sd: rnas = rnas_sd[:group_size] rnas_sd[:group_size] = [] for rna in",
"sequences_dict = None if self.fp_fasta: sequences_dict = filelib.parse_fasta(self.fp_fasta) sequences_rnas =",
"def spawn_reference_set(self): spawned_set = Dataset(fp_observations=None, fp_references=None, fp_sequences=None) references = [rna",
"self.fp_fasta: sequences_dict = filelib.parse_fasta(self.fp_fasta) sequences_rnas = set(sequences_dict.keys()) # Cross reference",
"== 1)) self.stats['quantile_basis'] = np.linspace(0, 1, 1000) self.stats['quantiles'] = np.quantile(finite_obs,",
"observations_dict[rna] = np.tile(np.nan, len(sequences_dict[rna])) dataset_rnas.update(sequences_rnas) for rna_name in dataset_rnas: if",
"in rnas} return spawned_set def spawn_reference_set(self): spawned_set = Dataset(fp_observations=None, fp_references=None,",
"class Dataset: def __init__(self, fp_observations, fp_sequences=None, fp_references=None): self.fp_obs = fp_observations",
"equal size to overall data) based on KL divergence criteria.",
"= np.percentile(finite_obs, (40, 60)) self.stats['n_obs'] = len(finite_obs) self.stats['up_ref'] = up_ref",
"= filelib.parse_observations(self.fp_obs) observations_rnas = set(observations_dict.keys()) dataset_rnas = observations_rnas sequences_dict =",
"used to initialize parameters of the emission model before training.",
"pre_process(self, model, scoring=False): if model.emission_model.type == 'DOM': for rna in",
"finite_obs = [] total_obs = 0 up_ref = 0 p_ref",
"== 0)) p_ref += int(np.sum(self.rnas[rna].ref == 1)) self.stats['quantile_basis'] = np.linspace(0,",
"sorted(self.rnas.values(), key=lambda transcript: transcript.density, reverse=True) logger.info(' ... selecting') while kl_div_set",
"added to a training Dataset (high quality transcripts first) until",
"dataset_rnas: if self.fp_fasta: self.rnas[rna_name] = Transcript(rna_name, sequences_dict[rna_name], observations_dict[rna_name]) else: self.rnas[rna_name]",
"sequences_dict[rna] = ''.join(['N'] * len(observations_dict[rna])) for rna in sequences_rnas.difference(observations_rnas): print('WARNING",
"overall data falls below the provided threshold. \"\"\" training_transcripts =",
"= set(observations_dict.keys()) dataset_rnas = observations_rnas sequences_dict = None if self.fp_fasta:",
"20 logger.info(' ... sorting') rnas_sd = sorted(self.rnas.values(), key=lambda transcript: transcript.density,",
"def get_emissions(self, model): for rna in self.rnas: model.emission_model.compute_emissions(self.rnas[rna]) def spawn_set(self,",
"found for RNA: {}'.format(rna)) observations_dict[rna] = np.tile(np.nan, len(sequences_dict[rna])) dataset_rnas.update(sequences_rnas) for",
"training_transcripts.append(rna.name) training_obs.extend(rna.obs[rna.mask_finite]) training_histogram, _ = np.histogram(training_obs, bins=self.stats['histogram_bins'], density=True) kl_div_set =",
"\"\"\" finite_obs = [] total_obs = 0 up_ref = 0",
"dataset_rnas = observations_rnas sequences_dict = None if self.fp_fasta: sequences_dict =",
"kl_div_set def pre_process(self, model, scoring=False): if model.emission_model.type == 'DOM': for",
"reverse=True) logger.info(' ... selecting') while kl_div_set > kl_div and rnas_sd:",
"all transcripts for rna in observations_rnas.difference(sequences_rnas): print('WARNING - No sequence",
"rna in self.rnas: self.rnas[rna].log_transform() self.compute_stats() def compute_stats(self): \"\"\" Parse all",
"np.percentile(finite_obs, (40, 60)) self.stats['n_obs'] = len(finite_obs) self.stats['up_ref'] = up_ref self.stats['p_ref']",
"(high quality transcripts first) until the training set's KL divergence",
"= fp_references self.rnas = dict() self.stats = dict() def load_rnas(self,",
"a training Dataset (high quality transcripts first) until the training",
"... sorting') rnas_sd = sorted(self.rnas.values(), key=lambda transcript: transcript.density, reverse=True) logger.info('",
"criteria. Transcripts are incrementally added to a training Dataset (high",
"np.max(finite_obs) self.stats['finite_obs'] = finite_obs self.stats['histogram_bins'] = np.linspace(self.stats['minimum'], self.stats['maximum'], 20) self.stats['histogram'],",
"= observations_rnas sequences_dict = None if self.fp_fasta: sequences_dict = filelib.parse_fasta(self.fp_fasta)",
"0)) p_ref += int(np.sum(self.rnas[rna].ref == 1)) self.stats['quantile_basis'] = np.linspace(0, 1,",
"self.stats['continuous_variance'] = np.var(finite_obs) self.stats['minimum'] = np.min(finite_obs) self.stats['maximum'] = np.max(finite_obs) self.stats['finite_obs']",
"= 0 for rna in self.rnas: finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)]) total_obs += len(self.rnas[rna].obs)",
"parameters of the emission model before training. \"\"\" finite_obs =",
"all finite observations in the input file and compute some",
"print('WARNING - No probing data found for RNA: {}'.format(rna)) observations_dict[rna]",
"Transcripts are incrementally added to a training Dataset (high quality",
"observations_dict[rna_name]) else: self.rnas[rna_name] = Transcript(rna_name, 'N' * len(observations_dict[rna_name]), observations_dict[rna_name]) if",
"from the overall data falls below the provided threshold. \"\"\"",
"1000) self.stats['quantiles'] = np.quantile(finite_obs, self.stats[\"quantile_basis\"]) self.stats['P25'], self.stats['P75'] = np.percentile(finite_obs, (25,",
"fp_observations self.fp_fasta = fp_sequences self.fp_refs = fp_references self.rnas = dict()",
"spawned_set.compute_stats() return spawned_set def clear(self): self.rnas = None self.stats =",
"for rna_name in dataset_rnas: if self.fp_fasta: self.rnas[rna_name] = Transcript(rna_name, sequences_dict[rna_name],",
"import Transcript from patteRNA import filelib logger = logging.getLogger(__name__) class",
"kl_div and rnas_sd: rnas = rnas_sd[:group_size] rnas_sd[:group_size] = [] for",
"1, 1000) self.stats['quantiles'] = np.quantile(finite_obs, self.stats[\"quantile_basis\"]) self.stats['P25'], self.stats['P75'] = np.percentile(finite_obs,",
"None] spawned_set.rnas = {rna: self.rnas[rna] for rna in references} spawned_set.compute_stats()",
"= fp_observations self.fp_fasta = fp_sequences self.fp_refs = fp_references self.rnas =",
"self.rnas[rna] for rna in rnas} return spawned_set def spawn_reference_set(self): spawned_set",
"sequences_dict = filelib.parse_fasta(self.fp_fasta) sequences_rnas = set(sequences_dict.keys()) # Cross reference input",
"logger.info(' ... sorting') rnas_sd = sorted(self.rnas.values(), key=lambda transcript: transcript.density, reverse=True)",
"from patteRNA import filelib logger = logging.getLogger(__name__) class Dataset: def",
"before training. \"\"\" finite_obs = [] total_obs = 0 up_ref",
"for rna in rnas} return spawned_set def spawn_reference_set(self): spawned_set =",
"the training set's KL divergence from the overall data falls",
"''.join(['N'] * len(observations_dict[rna])) for rna in sequences_rnas.difference(observations_rnas): print('WARNING - No",
"scipy.stats import entropy from patteRNA.Transcript import Transcript from patteRNA import",
"{}'.format(rna)) observations_dict[rna] = np.tile(np.nan, len(sequences_dict[rna])) dataset_rnas.update(sequences_rnas) for rna_name in dataset_rnas:",
"as np from scipy.stats import entropy from patteRNA.Transcript import Transcript",
"of the emission model before training. \"\"\" finite_obs = []",
"No sequence found for RNA: {}'.format(rna)) sequences_dict[rna] = ''.join(['N'] *",
"training Dataset (high quality transcripts first) until the training set's",
"rna in sequences_rnas.difference(observations_rnas): print('WARNING - No probing data found for",
"np.histogram(finite_obs, bins=self.stats['histogram_bins'], density=True) def spawn_training_set(self, kl_div): \"\"\" Spawn a training",
"_ = np.histogram(training_obs, bins=self.stats['histogram_bins'], density=True) kl_div_set = entropy(training_histogram, self.stats['histogram']) training_set",
"- No sequence found for RNA: {}'.format(rna)) sequences_dict[rna] = ''.join(['N']",
"a training set (smaller than or equal size to overall",
"self.fp_refs = fp_references self.rnas = dict() self.stats = dict() def",
"Dataset(fp_observations=None, fp_references=None, fp_sequences=None) references = [rna for rna in self.rnas",
"to a training Dataset (high quality transcripts first) until the",
"references} spawned_set.compute_stats() return spawned_set def clear(self): self.rnas = None self.stats",
"to overall data) based on KL divergence criteria. Transcripts are",
"training_set = self.spawn_set(rnas=training_transcripts) training_set.compute_stats() return training_set, kl_div_set def pre_process(self, model,",
"logging.getLogger(__name__) class Dataset: def __init__(self, fp_observations, fp_sequences=None, fp_references=None): self.fp_obs =",
"are mostly used to initialize parameters of the emission model",
"size to overall data) based on KL divergence criteria. Transcripts",
"... selecting') while kl_div_set > kl_div and rnas_sd: rnas =",
"data. These statistics are mostly used to initialize parameters of",
"observations_dict = filelib.parse_observations(self.fp_obs) observations_rnas = set(observations_dict.keys()) dataset_rnas = observations_rnas sequences_dict",
"model): for rna in self.rnas: model.emission_model.compute_emissions(self.rnas[rna]) def spawn_set(self, rnas): spawned_set",
"self.rnas: finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)]) total_obs += len(self.rnas[rna].obs) up_ref += int(np.sum(self.rnas[rna].ref == 0))",
"self.stats['total_obs'] = total_obs self.stats['continuous_variance'] = np.var(finite_obs) self.stats['minimum'] = np.min(finite_obs) self.stats['maximum']",
"reference input files to confirm all transcripts for rna in",
"len(observations_dict[rna])) for rna in sequences_rnas.difference(observations_rnas): print('WARNING - No probing data",
"self.fp_obs = fp_observations self.fp_fasta = fp_sequences self.fp_refs = fp_references self.rnas",
"self.rnas: self.rnas[rna].log_transform() self.compute_stats() def compute_stats(self): \"\"\" Parse all finite observations",
"self.stats['P75'] = np.percentile(finite_obs, (25, 75)) self.stats['P40'], self.stats['P60'] = np.percentile(finite_obs, (40,",
"spawned_set.rnas = {rna: self.rnas[rna] for rna in rnas} return spawned_set",
"> kl_div and rnas_sd: rnas = rnas_sd[:group_size] rnas_sd[:group_size] = []",
"= np.percentile(finite_obs, (25, 75)) self.stats['P40'], self.stats['P60'] = np.percentile(finite_obs, (40, 60))",
"finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)]) total_obs += len(self.rnas[rna].obs) up_ref += int(np.sum(self.rnas[rna].ref == 0)) p_ref",
"to confirm all transcripts for rna in observations_rnas.difference(sequences_rnas): print('WARNING -",
"rna in rnas} return spawned_set def spawn_reference_set(self): spawned_set = Dataset(fp_observations=None,",
"# Cross reference input files to confirm all transcripts for",
"= 20 logger.info(' ... sorting') rnas_sd = sorted(self.rnas.values(), key=lambda transcript:",
"fp_sequences=None, fp_references=None) spawned_set.rnas = {rna: self.rnas[rna] for rna in rnas}",
"rnas = rnas_sd[:group_size] rnas_sd[:group_size] = [] for rna in rnas:",
"spawn_training_set(self, kl_div): \"\"\" Spawn a training set (smaller than or",
"total_obs self.stats['continuous_variance'] = np.var(finite_obs) self.stats['minimum'] = np.min(finite_obs) self.stats['maximum'] = np.max(finite_obs)",
"self.stats['histogram'], _ = np.histogram(finite_obs, bins=self.stats['histogram_bins'], density=True) def spawn_training_set(self, kl_div): \"\"\"",
"self.stats['P25'], self.stats['P75'] = np.percentile(finite_obs, (25, 75)) self.stats['P40'], self.stats['P60'] = np.percentile(finite_obs,",
"{rna: self.rnas[rna] for rna in references} spawned_set.compute_stats() return spawned_set def",
"total_obs = 0 up_ref = 0 p_ref = 0 for",
"for rna in rnas: training_transcripts.append(rna.name) training_obs.extend(rna.obs[rna.mask_finite]) training_histogram, _ = np.histogram(training_obs,",
"transcript: transcript.density, reverse=True) logger.info(' ... selecting') while kl_div_set > kl_div",
"in self.rnas: model.emission_model.discretize(self.rnas[rna]) if scoring: for rna in self.rnas.values(): model.e_step(rna)",
"training set's KL divergence from the overall data falls below",
"None if self.fp_fasta: sequences_dict = filelib.parse_fasta(self.fp_fasta) sequences_rnas = set(sequences_dict.keys()) #",
"logger = logging.getLogger(__name__) class Dataset: def __init__(self, fp_observations, fp_sequences=None, fp_references=None):",
"the provided threshold. \"\"\" training_transcripts = [] training_obs = []",
"= {rna: self.rnas[rna] for rna in references} spawned_set.compute_stats() return spawned_set",
"are incrementally added to a training Dataset (high quality transcripts",
"until the training set's KL divergence from the overall data",
"= up_ref self.stats['p_ref'] = p_ref self.stats['total_obs'] = total_obs self.stats['continuous_variance'] =",
"= np.linspace(0, 1, 1000) self.stats['quantiles'] = np.quantile(finite_obs, self.stats[\"quantile_basis\"]) self.stats['P25'], self.stats['P75']",
"len(observations_dict[rna_name]), observations_dict[rna_name]) if log_flag: for rna in self.rnas: self.rnas[rna].log_transform() self.compute_stats()",
"for rna in observations_rnas.difference(sequences_rnas): print('WARNING - No sequence found for",
"= np.histogram(training_obs, bins=self.stats['histogram_bins'], density=True) kl_div_set = entropy(training_histogram, self.stats['histogram']) training_set =",
"if model.emission_model.type == 'DOM': for rna in self.rnas: model.emission_model.discretize(self.rnas[rna]) if",
"self.stats['maximum'], 20) self.stats['histogram'], _ = np.histogram(finite_obs, bins=self.stats['histogram_bins'], density=True) def spawn_training_set(self,",
"initialize parameters of the emission model before training. \"\"\" finite_obs",
"up_ref = 0 p_ref = 0 for rna in self.rnas:",
"1)) self.stats['quantile_basis'] = np.linspace(0, 1, 1000) self.stats['quantiles'] = np.quantile(finite_obs, self.stats[\"quantile_basis\"])",
"training set (smaller than or equal size to overall data)",
"incrementally added to a training Dataset (high quality transcripts first)",
"training_obs.extend(rna.obs[rna.mask_finite]) training_histogram, _ = np.histogram(training_obs, bins=self.stats['histogram_bins'], density=True) kl_div_set = entropy(training_histogram,",
"[] for rna in rnas: training_transcripts.append(rna.name) training_obs.extend(rna.obs[rna.mask_finite]) training_histogram, _ =",
"self.stats['minimum'] = np.min(finite_obs) self.stats['maximum'] = np.max(finite_obs) self.stats['finite_obs'] = finite_obs self.stats['histogram_bins']",
"def compute_stats(self): \"\"\" Parse all finite observations in the input",
"fp_sequences self.fp_refs = fp_references self.rnas = dict() self.stats = dict()",
"KL divergence criteria. Transcripts are incrementally added to a training",
"0 for rna in self.rnas: finite_obs.extend(self.rnas[rna].obs[np.isfinite(self.rnas[rna].obs)]) total_obs += len(self.rnas[rna].obs) up_ref",
"overall data) based on KL divergence criteria. Transcripts are incrementally",
"model.emission_model.compute_emissions(self.rnas[rna]) def spawn_set(self, rnas): spawned_set = Dataset(fp_observations=None, fp_sequences=None, fp_references=None) spawned_set.rnas",
"self.fp_fasta: self.rnas[rna_name] = Transcript(rna_name, sequences_dict[rna_name], observations_dict[rna_name]) else: self.rnas[rna_name] = Transcript(rna_name,",
"set(observations_dict.keys()) dataset_rnas = observations_rnas sequences_dict = None if self.fp_fasta: sequences_dict",
"= set(sequences_dict.keys()) # Cross reference input files to confirm all",
"Spawn a training set (smaller than or equal size to",
"falls below the provided threshold. \"\"\" training_transcripts = [] training_obs",
"Transcript from patteRNA import filelib logger = logging.getLogger(__name__) class Dataset:",
"[] training_obs = [] kl_div_set = 1.0 group_size = 20",
"rna in self.rnas: model.emission_model.compute_emissions(self.rnas[rna]) def spawn_set(self, rnas): spawned_set = Dataset(fp_observations=None,",
"in observations_rnas.difference(sequences_rnas): print('WARNING - No sequence found for RNA: {}'.format(rna))",
"training_set, kl_div_set def pre_process(self, model, scoring=False): if model.emission_model.type == 'DOM':",
"and rnas_sd: rnas = rnas_sd[:group_size] rnas_sd[:group_size] = [] for rna",
"def spawn_set(self, rnas): spawned_set = Dataset(fp_observations=None, fp_sequences=None, fp_references=None) spawned_set.rnas =",
"in the input file and compute some statistics on the",
"fp_observations, fp_sequences=None, fp_references=None): self.fp_obs = fp_observations self.fp_fasta = fp_sequences self.fp_refs",
"[rna for rna in self.rnas if self.rnas[rna].ref is not None]",
"is not None] spawned_set.rnas = {rna: self.rnas[rna] for rna in",
"def spawn_training_set(self, kl_div): \"\"\" Spawn a training set (smaller than",
"def pre_process(self, model, scoring=False): if model.emission_model.type == 'DOM': for rna",
"from patteRNA.Transcript import Transcript from patteRNA import filelib logger =",
"dataset_rnas.update(sequences_rnas) for rna_name in dataset_rnas: if self.fp_fasta: self.rnas[rna_name] = Transcript(rna_name,",
"fp_sequences=None, fp_references=None): self.fp_obs = fp_observations self.fp_fasta = fp_sequences self.fp_refs =",
"KL divergence from the overall data falls below the provided",
"__init__(self, fp_observations, fp_sequences=None, fp_references=None): self.fp_obs = fp_observations self.fp_fasta = fp_sequences",
"transcript.density, reverse=True) logger.info(' ... selecting') while kl_div_set > kl_div and",
"in sequences_rnas.difference(observations_rnas): print('WARNING - No probing data found for RNA:",
"finite_obs self.stats['histogram_bins'] = np.linspace(self.stats['minimum'], self.stats['maximum'], 20) self.stats['histogram'], _ = np.histogram(finite_obs,",
"data) based on KL divergence criteria. Transcripts are incrementally added",
"(smaller than or equal size to overall data) based on",
"model, scoring=False): if model.emission_model.type == 'DOM': for rna in self.rnas:",
"sequences_dict[rna_name], observations_dict[rna_name]) else: self.rnas[rna_name] = Transcript(rna_name, 'N' * len(observations_dict[rna_name]), observations_dict[rna_name])",
"data found for RNA: {}'.format(rna)) observations_dict[rna] = np.tile(np.nan, len(sequences_dict[rna])) dataset_rnas.update(sequences_rnas)",
"[] total_obs = 0 up_ref = 0 p_ref = 0",
"kl_div_set > kl_div and rnas_sd: rnas = rnas_sd[:group_size] rnas_sd[:group_size] =",
"file and compute some statistics on the data. These statistics",
"statistics are mostly used to initialize parameters of the emission",
"total_obs += len(self.rnas[rna].obs) up_ref += int(np.sum(self.rnas[rna].ref == 0)) p_ref +=",
"= np.max(finite_obs) self.stats['finite_obs'] = finite_obs self.stats['histogram_bins'] = np.linspace(self.stats['minimum'], self.stats['maximum'], 20)",
"mostly used to initialize parameters of the emission model before",
"self.stats['p_ref'] = p_ref self.stats['total_obs'] = total_obs self.stats['continuous_variance'] = np.var(finite_obs) self.stats['minimum']",
"= Dataset(fp_observations=None, fp_sequences=None, fp_references=None) spawned_set.rnas = {rna: self.rnas[rna] for rna",
"Dataset: def __init__(self, fp_observations, fp_sequences=None, fp_references=None): self.fp_obs = fp_observations self.fp_fasta",
"self.stats['P40'], self.stats['P60'] = np.percentile(finite_obs, (40, 60)) self.stats['n_obs'] = len(finite_obs) self.stats['up_ref']",
"(40, 60)) self.stats['n_obs'] = len(finite_obs) self.stats['up_ref'] = up_ref self.stats['p_ref'] ="
] |
[
"Prev. part and next part could be merged for efficiency",
"getting shape of 3D array number_clients = len(list_weights) size_outer =",
"/= number_clients # now update the model using the learning",
"for j in range(size_inner)] for i in range(size_outer)] # validate",
"in enumerate(outerList): model[outerIndex][innerIndex] *= 1-alpha model[outerIndex][innerIndex] += alpha * newModel[outerIndex][innerIndex]",
"all the models for each client \"\"\" # this part",
"@library.export def getModel(args): return library.get(\"model\") @library.export def getRound(args): return library.get(\"ROUND\")",
"= [ [0 for j in range(size_inner)] for i in",
"size_inner) # sum for all the clients for weights in",
"0.2 library.put(\"alpha\", alpha) @library.export def clientUpload(args): # get client model",
"this part will change developer to developer # one can",
"array of zeros of same size newModel = [ [0",
"return model @library.export def getModel(args): return library.get(\"model\") @library.export def getRound(args):",
"just takes avg without use of external library alpha =",
"update the model using the learning rate using below formula",
"library.count_bucket(k) > 20: ROUND = library.get(\"ROUND\") # check client rounds",
"\"\"\" list_weights : 3D list of shape : (clientNumber,modelOuter, modelInner)",
"formula # model = (1-a) * model + a *",
"two loops # Iterate over model for outerIndex, outerList in",
"range(size_outer)] # validate new created shape assert(len(newModel) == size_outer) assert(len(newModel[0])",
"for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] += innerVal # average",
"range(size_inner)] for i in range(size_outer)] # validate new created shape",
": 3D list of shape : (clientNumber,modelOuter, modelInner) It contains",
"size_outer = len(list_weights[0]) size_inner = len(list_weights[0][0]) # constructing a new",
"0 library.put(\"ROUND\", ROUND) alpha = 0.2 library.put(\"alpha\", alpha) @library.export def",
"# constructing a new 2D array of zeros of same",
"in range(size_inner)] for i in range(size_outer)] # validate new created",
"the models for each client \"\"\" # this part will",
"implemented with two loops # Iterate over model for outerIndex,",
"[8.2, 0.22, 0.21], [7.2, 1.21, 2.41], [1.2, 2.21, 0.29]] library.put(\"model\",",
"efficiency but readability they implemented with two loops # Iterate",
"# average it by number of clients for outerIndex, outerList",
"= len(list_weights[0][0]) # constructing a new 2D array of zeros",
"k = \"round\" + str(client[\"round\"]) # save model to buckets",
"avg # or one can discard smallest and largest than",
"library.put(\"model\", model) ROUND = 0 library.put(\"ROUND\", ROUND) alpha = 0.2",
"round library.put(\"model\", model) library.put(\"ROUND\", ROUND+1) return True def updateModel(model, list_weights):",
"library.put(\"ROUND\", -1) model = library.get(\"model\") list_weights = library.get_bucket(k) model =",
"validate new created shape assert(len(newModel) == size_outer) assert(len(newModel[0]) == size_inner)",
"alpha = 0.2 library.put(\"alpha\", alpha) @library.export def clientUpload(args): # get",
"each client \"\"\" # this part will change developer to",
"for efficiency but readability they implemented with two loops #",
"clients for weights in list_weights: for outerIndex, outerList in enumerate(weights):",
"new_model # Prev. part and next part could be merged",
"alpha * newModel[outerIndex][innerIndex] # Finally update round number return model",
"library.put(\"ROUND\", ROUND) alpha = 0.2 library.put(\"alpha\", alpha) @library.export def clientUpload(args):",
"if library.count_bucket(k) > 20: ROUND = library.get(\"ROUND\") # check client",
"for i in range(size_outer)] # validate new created shape assert(len(newModel)",
"than take average # this example just takes avg without",
"innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] += innerVal # average it by",
"largest than take average # this example just takes avg",
"enumerate(weights): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] += innerVal #",
"\"round\" + str(client[\"round\"]) # save model to buckets library.put_bucket(k, client[\"model\"])",
"in enumerate(outerList): newModel[outerIndex][innerIndex] += innerVal # average it by number",
"Iterate over model for outerIndex, outerList in enumerate(newModel): for innerIndex,",
"== size_outer) assert(len(newModel[0]) == size_inner) # sum for all the",
"model = updateModel(model, list_weights) # save calculated model and restore",
"innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] /= number_clients # now update the",
"takes avg without use of external library alpha = library.get(\"alpha\")",
"+ str(client[\"round\"]) # save model to buckets library.put_bucket(k, client[\"model\"]) #",
"3D list of shape : (clientNumber,modelOuter, modelInner) It contains all",
"to -1 to prevent clients uploading to this bucket library.put(\"ROUND\",",
"list_weights : 3D list of shape : (clientNumber,modelOuter, modelInner) It",
"number return model @library.export def getModel(args): return library.get(\"model\") @library.export def",
"calculated model and restore round library.put(\"model\", model) library.put(\"ROUND\", ROUND+1) return",
"number_clients = len(list_weights) size_outer = len(list_weights[0]) size_inner = len(list_weights[0][0]) #",
"library.get(\"alpha\") # getting shape of 3D array number_clients = len(list_weights)",
"list_weights) # save calculated model and restore round library.put(\"model\", model)",
"It contains all the models for each client \"\"\" #",
"20: ROUND = library.get(\"ROUND\") # check client rounds == current",
"1.21, 2.41], [1.2, 2.21, 0.29]] library.put(\"model\", model) ROUND = 0",
"this example just takes avg without use of external library",
"= library.get_bucket(k) model = updateModel(model, list_weights) # save calculated model",
"model) library.put(\"ROUND\", ROUND+1) return True def updateModel(model, list_weights): \"\"\" list_weights",
"zeros of same size newModel = [ [0 for j",
"round number return model @library.export def getModel(args): return library.get(\"model\") @library.export",
"of external library alpha = library.get(\"alpha\") # getting shape of",
"newModel[outerIndex][innerIndex] += innerVal # average it by number of clients",
"external library alpha = library.get(\"alpha\") # getting shape of 3D",
"= json.loads(args[\"data\"]) # client round k = \"round\" + str(client[\"round\"])",
"number_clients # now update the model using the learning rate",
"innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] += innerVal # average it",
"restore round library.put(\"model\", model) library.put(\"ROUND\", ROUND+1) return True def updateModel(model,",
"client[\"round\"]: return False # set round to -1 to prevent",
"# model = (1-a) * model + a * new_model",
"enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] /= number_clients #",
"using the learning rate using below formula # model =",
"with two loops # Iterate over model for outerIndex, outerList",
"+= innerVal # average it by number of clients for",
"the learning rate using below formula # model = (1-a)",
"len(list_weights) size_outer = len(list_weights[0]) size_inner = len(list_weights[0][0]) # constructing a",
"# Finally update round number return model @library.export def getModel(args):",
"of same size newModel = [ [0 for j in",
"library import json @library.export def init(args): model = [[9.2, 0.21,",
"# validate new created shape assert(len(newModel) == size_outer) assert(len(newModel[0]) ==",
"# one can just take avg # or one can",
"def updateModel(model, list_weights): \"\"\" list_weights : 3D list of shape",
"readability they implemented with two loops # Iterate over model",
"new created shape assert(len(newModel) == size_outer) assert(len(newModel[0]) == size_inner) #",
"model = [[9.2, 0.21, 0.21], [8.2, 0.22, 0.21], [7.2, 1.21,",
"model client = json.loads(args[\"data\"]) # client round k = \"round\"",
"ROUND = library.get(\"ROUND\") # check client rounds == current rounds",
"constructing a new 2D array of zeros of same size",
"model for outerIndex, outerList in enumerate(newModel): for innerIndex, innerVal in",
"next part could be merged for efficiency but readability they",
"i in range(size_outer)] # validate new created shape assert(len(newModel) ==",
"# get client model client = json.loads(args[\"data\"]) # client round",
"for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] /= number_clients # now",
"example just takes avg without use of external library alpha",
"# if enough models if library.count_bucket(k) > 20: ROUND =",
"learning rate using below formula # model = (1-a) *",
"clients for outerIndex, outerList in enumerate(newModel): for innerIndex, innerVal in",
"sum for all the clients for weights in list_weights: for",
"enumerate(outerList): model[outerIndex][innerIndex] *= 1-alpha model[outerIndex][innerIndex] += alpha * newModel[outerIndex][innerIndex] #",
"bucket library.put(\"ROUND\", -1) model = library.get(\"model\") list_weights = library.get_bucket(k) model",
"# this part will change developer to developer # one",
"set round to -1 to prevent clients uploading to this",
"return False # set round to -1 to prevent clients",
"ROUND = 0 library.put(\"ROUND\", ROUND) alpha = 0.2 library.put(\"alpha\", alpha)",
"size_inner = len(list_weights[0][0]) # constructing a new 2D array of",
"take avg # or one can discard smallest and largest",
"newModel = [ [0 for j in range(size_inner)] for i",
"@library.export def init(args): model = [[9.2, 0.21, 0.21], [8.2, 0.22,",
"a * new_model # Prev. part and next part could",
"they implemented with two loops # Iterate over model for",
"shape : (clientNumber,modelOuter, modelInner) It contains all the models for",
"part and next part could be merged for efficiency but",
"import library import json @library.export def init(args): model = [[9.2,",
"json @library.export def init(args): model = [[9.2, 0.21, 0.21], [8.2,",
"to this bucket library.put(\"ROUND\", -1) model = library.get(\"model\") list_weights =",
"in enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] /= number_clients",
"model = library.get(\"model\") list_weights = library.get_bucket(k) model = updateModel(model, list_weights)",
"list_weights: for outerIndex, outerList in enumerate(weights): for innerIndex, innerVal in",
"[ [0 for j in range(size_inner)] for i in range(size_outer)]",
"= [[9.2, 0.21, 0.21], [8.2, 0.22, 0.21], [7.2, 1.21, 2.41],",
"and next part could be merged for efficiency but readability",
"model[outerIndex][innerIndex] *= 1-alpha model[outerIndex][innerIndex] += alpha * newModel[outerIndex][innerIndex] # Finally",
"if enough models if library.count_bucket(k) > 20: ROUND = library.get(\"ROUND\")",
"library.get(\"model\") list_weights = library.get_bucket(k) model = updateModel(model, list_weights) # save",
"now update the model using the learning rate using below",
"one can discard smallest and largest than take average #",
"len(list_weights[0][0]) # constructing a new 2D array of zeros of",
"library.put(\"model\", model) library.put(\"ROUND\", ROUND+1) return True def updateModel(model, list_weights): \"\"\"",
"# save calculated model and restore round library.put(\"model\", model) library.put(\"ROUND\",",
"alpha) @library.export def clientUpload(args): # get client model client =",
"== current rounds if ROUND != client[\"round\"]: return False #",
"[7.2, 1.21, 2.41], [1.2, 2.21, 0.29]] library.put(\"model\", model) ROUND =",
"developer to developer # one can just take avg #",
"library.put_bucket(k, client[\"model\"]) # if enough models if library.count_bucket(k) > 20:",
"library alpha = library.get(\"alpha\") # getting shape of 3D array",
"weights in list_weights: for outerIndex, outerList in enumerate(weights): for innerIndex,",
"= library.get(\"alpha\") # getting shape of 3D array number_clients =",
"part will change developer to developer # one can just",
"in list_weights: for outerIndex, outerList in enumerate(weights): for innerIndex, innerVal",
"False # set round to -1 to prevent clients uploading",
"return True def updateModel(model, list_weights): \"\"\" list_weights : 3D list",
"[[9.2, 0.21, 0.21], [8.2, 0.22, 0.21], [7.2, 1.21, 2.41], [1.2,",
"and largest than take average # this example just takes",
"= (1-a) * model + a * new_model # Prev.",
"True def updateModel(model, list_weights): \"\"\" list_weights : 3D list of",
"0.21, 0.21], [8.2, 0.22, 0.21], [7.2, 1.21, 2.41], [1.2, 2.21,",
"client[\"model\"]) # if enough models if library.count_bucket(k) > 20: ROUND",
"-1 to prevent clients uploading to this bucket library.put(\"ROUND\", -1)",
"= updateModel(model, list_weights) # save calculated model and restore round",
"of zeros of same size newModel = [ [0 for",
"developer # one can just take avg # or one",
"client round k = \"round\" + str(client[\"round\"]) # save model",
"alpha = library.get(\"alpha\") # getting shape of 3D array number_clients",
"client rounds == current rounds if ROUND != client[\"round\"]: return",
"can just take avg # or one can discard smallest",
"<reponame>GYRY-NEU/CS7610-Experiments import library import json @library.export def init(args): model =",
"model[outerIndex][innerIndex] += alpha * newModel[outerIndex][innerIndex] # Finally update round number",
"outerIndex, outerList in enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex]",
"assert(len(newModel) == size_outer) assert(len(newModel[0]) == size_inner) # sum for all",
"in range(size_outer)] # validate new created shape assert(len(newModel) == size_outer)",
"len(list_weights[0]) size_inner = len(list_weights[0][0]) # constructing a new 2D array",
"without use of external library alpha = library.get(\"alpha\") # getting",
"def init(args): model = [[9.2, 0.21, 0.21], [8.2, 0.22, 0.21],",
"contains all the models for each client \"\"\" # this",
"of clients for outerIndex, outerList in enumerate(newModel): for innerIndex, innerVal",
"created shape assert(len(newModel) == size_outer) assert(len(newModel[0]) == size_inner) # sum",
"# save model to buckets library.put_bucket(k, client[\"model\"]) # if enough",
"enumerate(outerList): newModel[outerIndex][innerIndex] /= number_clients # now update the model using",
"in enumerate(outerList): newModel[outerIndex][innerIndex] /= number_clients # now update the model",
"over model for outerIndex, outerList in enumerate(newModel): for innerIndex, innerVal",
"current rounds if ROUND != client[\"round\"]: return False # set",
"model + a * new_model # Prev. part and next",
"library.put(\"alpha\", alpha) @library.export def clientUpload(args): # get client model client",
"or one can discard smallest and largest than take average",
"+ a * new_model # Prev. part and next part",
"= library.get(\"model\") list_weights = library.get_bucket(k) model = updateModel(model, list_weights) #",
"number of clients for outerIndex, outerList in enumerate(newModel): for innerIndex,",
"outerList in enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] /=",
"by number of clients for outerIndex, outerList in enumerate(newModel): for",
"-1) model = library.get(\"model\") list_weights = library.get_bucket(k) model = updateModel(model,",
"ROUND != client[\"round\"]: return False # set round to -1",
"+= alpha * newModel[outerIndex][innerIndex] # Finally update round number return",
"# this example just takes avg without use of external",
"size newModel = [ [0 for j in range(size_inner)] for",
"below formula # model = (1-a) * model + a",
"# set round to -1 to prevent clients uploading to",
"# Prev. part and next part could be merged for",
"newModel[outerIndex][innerIndex] # Finally update round number return model @library.export def",
"enough models if library.count_bucket(k) > 20: ROUND = library.get(\"ROUND\") #",
"assert(len(newModel[0]) == size_inner) # sum for all the clients for",
"for weights in list_weights: for outerIndex, outerList in enumerate(weights): for",
"1-alpha model[outerIndex][innerIndex] += alpha * newModel[outerIndex][innerIndex] # Finally update round",
"library.put(\"ROUND\", ROUND+1) return True def updateModel(model, list_weights): \"\"\" list_weights :",
"the clients for weights in list_weights: for outerIndex, outerList in",
"rate using below formula # model = (1-a) * model",
"*= 1-alpha model[outerIndex][innerIndex] += alpha * newModel[outerIndex][innerIndex] # Finally update",
"# or one can discard smallest and largest than take",
"to developer # one can just take avg # or",
"import json @library.export def init(args): model = [[9.2, 0.21, 0.21],",
"# getting shape of 3D array number_clients = len(list_weights) size_outer",
"just take avg # or one can discard smallest and",
"innerIndex, innerVal in enumerate(outerList): model[outerIndex][innerIndex] *= 1-alpha model[outerIndex][innerIndex] += alpha",
"this bucket library.put(\"ROUND\", -1) model = library.get(\"model\") list_weights = library.get_bucket(k)",
"# now update the model using the learning rate using",
"innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] /= number_clients # now update",
"(clientNumber,modelOuter, modelInner) It contains all the models for each client",
"client = json.loads(args[\"data\"]) # client round k = \"round\" +",
"\"\"\" # this part will change developer to developer #",
"list_weights = library.get_bucket(k) model = updateModel(model, list_weights) # save calculated",
"average # this example just takes avg without use of",
"prevent clients uploading to this bucket library.put(\"ROUND\", -1) model =",
"# sum for all the clients for weights in list_weights:",
"array number_clients = len(list_weights) size_outer = len(list_weights[0]) size_inner = len(list_weights[0][0])",
"buckets library.put_bucket(k, client[\"model\"]) # if enough models if library.count_bucket(k) >",
"2D array of zeros of same size newModel = [",
"* new_model # Prev. part and next part could be",
"shape assert(len(newModel) == size_outer) assert(len(newModel[0]) == size_inner) # sum for",
"shape of 3D array number_clients = len(list_weights) size_outer = len(list_weights[0])",
"it by number of clients for outerIndex, outerList in enumerate(newModel):",
"clientUpload(args): # get client model client = json.loads(args[\"data\"]) # client",
"clients uploading to this bucket library.put(\"ROUND\", -1) model = library.get(\"model\")",
"2.21, 0.29]] library.put(\"model\", model) ROUND = 0 library.put(\"ROUND\", ROUND) alpha",
"outerIndex, outerList in enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): model[outerIndex][innerIndex]",
"get client model client = json.loads(args[\"data\"]) # client round k",
"for innerIndex, innerVal in enumerate(outerList): model[outerIndex][innerIndex] *= 1-alpha model[outerIndex][innerIndex] +=",
"= \"round\" + str(client[\"round\"]) # save model to buckets library.put_bucket(k,",
"== size_inner) # sum for all the clients for weights",
"= 0 library.put(\"ROUND\", ROUND) alpha = 0.2 library.put(\"alpha\", alpha) @library.export",
"[1.2, 2.21, 0.29]] library.put(\"model\", model) ROUND = 0 library.put(\"ROUND\", ROUND)",
"rounds if ROUND != client[\"round\"]: return False # set round",
"same size newModel = [ [0 for j in range(size_inner)]",
"average it by number of clients for outerIndex, outerList in",
"0.29]] library.put(\"model\", model) ROUND = 0 library.put(\"ROUND\", ROUND) alpha =",
"change developer to developer # one can just take avg",
"one can just take avg # or one can discard",
"outerList in enumerate(weights): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] +=",
"updateModel(model, list_weights): \"\"\" list_weights : 3D list of shape :",
"client \"\"\" # this part will change developer to developer",
"3D array number_clients = len(list_weights) size_outer = len(list_weights[0]) size_inner =",
"but readability they implemented with two loops # Iterate over",
"# Iterate over model for outerIndex, outerList in enumerate(newModel): for",
"innerVal # average it by number of clients for outerIndex,",
"library.get_bucket(k) model = updateModel(model, list_weights) # save calculated model and",
"a new 2D array of zeros of same size newModel",
"2.41], [1.2, 2.21, 0.29]] library.put(\"model\", model) ROUND = 0 library.put(\"ROUND\",",
"uploading to this bucket library.put(\"ROUND\", -1) model = library.get(\"model\") list_weights",
"(1-a) * model + a * new_model # Prev. part",
"discard smallest and largest than take average # this example",
"the model using the learning rate using below formula #",
"can discard smallest and largest than take average # this",
"avg without use of external library alpha = library.get(\"alpha\") #",
"= library.get(\"ROUND\") # check client rounds == current rounds if",
"all the clients for weights in list_weights: for outerIndex, outerList",
"ROUND) alpha = 0.2 library.put(\"alpha\", alpha) @library.export def clientUpload(args): #",
"client model client = json.loads(args[\"data\"]) # client round k =",
"for each client \"\"\" # this part will change developer",
"str(client[\"round\"]) # save model to buckets library.put_bucket(k, client[\"model\"]) # if",
"loops # Iterate over model for outerIndex, outerList in enumerate(newModel):",
"for outerIndex, outerList in enumerate(weights): for innerIndex, innerVal in enumerate(outerList):",
"be merged for efficiency but readability they implemented with two",
": (clientNumber,modelOuter, modelInner) It contains all the models for each",
"0.21], [8.2, 0.22, 0.21], [7.2, 1.21, 2.41], [1.2, 2.21, 0.29]]",
"of 3D array number_clients = len(list_weights) size_outer = len(list_weights[0]) size_inner",
"[0 for j in range(size_inner)] for i in range(size_outer)] #",
"model) ROUND = 0 library.put(\"ROUND\", ROUND) alpha = 0.2 library.put(\"alpha\",",
"round to -1 to prevent clients uploading to this bucket",
"model = (1-a) * model + a * new_model #",
"smallest and largest than take average # this example just",
"use of external library alpha = library.get(\"alpha\") # getting shape",
"models if library.count_bucket(k) > 20: ROUND = library.get(\"ROUND\") # check",
"def clientUpload(args): # get client model client = json.loads(args[\"data\"]) #",
"* model + a * new_model # Prev. part and",
"outerList in enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): model[outerIndex][innerIndex] *=",
"for outerIndex, outerList in enumerate(newModel): for innerIndex, innerVal in enumerate(outerList):",
"model to buckets library.put_bucket(k, client[\"model\"]) # if enough models if",
"updateModel(model, list_weights) # save calculated model and restore round library.put(\"model\",",
"json.loads(args[\"data\"]) # client round k = \"round\" + str(client[\"round\"]) #",
"models for each client \"\"\" # this part will change",
"model and restore round library.put(\"model\", model) library.put(\"ROUND\", ROUND+1) return True",
"j in range(size_inner)] for i in range(size_outer)] # validate new",
"model using the learning rate using below formula # model",
"if ROUND != client[\"round\"]: return False # set round to",
"save model to buckets library.put_bucket(k, client[\"model\"]) # if enough models",
"in enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): model[outerIndex][innerIndex] *= 1-alpha",
"and restore round library.put(\"model\", model) library.put(\"ROUND\", ROUND+1) return True def",
"will change developer to developer # one can just take",
"# check client rounds == current rounds if ROUND !=",
"new 2D array of zeros of same size newModel =",
"# client round k = \"round\" + str(client[\"round\"]) # save",
"* newModel[outerIndex][innerIndex] # Finally update round number return model @library.export",
"ROUND+1) return True def updateModel(model, list_weights): \"\"\" list_weights : 3D",
"enumerate(newModel): for innerIndex, innerVal in enumerate(outerList): model[outerIndex][innerIndex] *= 1-alpha model[outerIndex][innerIndex]",
"size_outer) assert(len(newModel[0]) == size_inner) # sum for all the clients",
"using below formula # model = (1-a) * model +",
"part could be merged for efficiency but readability they implemented",
"innerVal in enumerate(outerList): model[outerIndex][innerIndex] *= 1-alpha model[outerIndex][innerIndex] += alpha *",
"for all the clients for weights in list_weights: for outerIndex,",
"round k = \"round\" + str(client[\"round\"]) # save model to",
"outerIndex, outerList in enumerate(weights): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex]",
"list_weights): \"\"\" list_weights : 3D list of shape : (clientNumber,modelOuter,",
"@library.export def clientUpload(args): # get client model client = json.loads(args[\"data\"])",
"= 0.2 library.put(\"alpha\", alpha) @library.export def clientUpload(args): # get client",
"model @library.export def getModel(args): return library.get(\"model\") @library.export def getRound(args): return",
"> 20: ROUND = library.get(\"ROUND\") # check client rounds ==",
"Finally update round number return model @library.export def getModel(args): return",
"modelInner) It contains all the models for each client \"\"\"",
"could be merged for efficiency but readability they implemented with",
"update round number return model @library.export def getModel(args): return library.get(\"model\")",
"to buckets library.put_bucket(k, client[\"model\"]) # if enough models if library.count_bucket(k)",
"take average # this example just takes avg without use",
"newModel[outerIndex][innerIndex] /= number_clients # now update the model using the",
"in enumerate(weights): for innerIndex, innerVal in enumerate(outerList): newModel[outerIndex][innerIndex] += innerVal",
"0.22, 0.21], [7.2, 1.21, 2.41], [1.2, 2.21, 0.29]] library.put(\"model\", model)",
"save calculated model and restore round library.put(\"model\", model) library.put(\"ROUND\", ROUND+1)",
"check client rounds == current rounds if ROUND != client[\"round\"]:",
"enumerate(outerList): newModel[outerIndex][innerIndex] += innerVal # average it by number of",
"init(args): model = [[9.2, 0.21, 0.21], [8.2, 0.22, 0.21], [7.2,",
"0.21], [7.2, 1.21, 2.41], [1.2, 2.21, 0.29]] library.put(\"model\", model) ROUND",
"!= client[\"round\"]: return False # set round to -1 to",
"list of shape : (clientNumber,modelOuter, modelInner) It contains all the",
"rounds == current rounds if ROUND != client[\"round\"]: return False",
"merged for efficiency but readability they implemented with two loops",
"of shape : (clientNumber,modelOuter, modelInner) It contains all the models",
"= len(list_weights[0]) size_inner = len(list_weights[0][0]) # constructing a new 2D",
"to prevent clients uploading to this bucket library.put(\"ROUND\", -1) model",
"library.get(\"ROUND\") # check client rounds == current rounds if ROUND",
"= len(list_weights) size_outer = len(list_weights[0]) size_inner = len(list_weights[0][0]) # constructing"
] |
[
"test_driver_is_detected(): driver_name = __name__.split(\".\")[0].split(\"_\")[-1] assert driver_name in [str(d) for d",
"import api def test_driver_is_detected(): driver_name = __name__.split(\".\")[0].split(\"_\")[-1] assert driver_name in",
"molecule import api def test_driver_is_detected(): driver_name = __name__.split(\".\")[0].split(\"_\")[-1] assert driver_name",
"def test_driver_is_detected(): driver_name = __name__.split(\".\")[0].split(\"_\")[-1] assert driver_name in [str(d) for",
"= __name__.split(\".\")[0].split(\"_\")[-1] assert driver_name in [str(d) for d in api.drivers()]",
"driver_name = __name__.split(\".\")[0].split(\"_\")[-1] assert driver_name in [str(d) for d in",
"<reponame>ragingpastry/molecule-ignite from molecule import api def test_driver_is_detected(): driver_name = __name__.split(\".\")[0].split(\"_\")[-1]",
"from molecule import api def test_driver_is_detected(): driver_name = __name__.split(\".\")[0].split(\"_\")[-1] assert",
"api def test_driver_is_detected(): driver_name = __name__.split(\".\")[0].split(\"_\")[-1] assert driver_name in [str(d)"
] |
[
"sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import",
"pipeline for classification with filter bank model. Prepare filter bank",
"computed from M/EEG signals in different frequency bands. Then transformations",
"---------- [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Predictive regression",
"https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" # put defaults here for projection and vectorization",
"frequency bands. Then transformations are applied to improve the applicability",
"100)) filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor",
"np from coffeine.covariance_transformers import ( Diag, LogDiag, ExpandFeatures, Riemann, RiemannSnp,",
"the projection step. vectorization_params : dict | None The parameters",
"| None The parameters for the vectorization step. categorical_interaction :",
"practice, we recommend comparing `riemann', `spoc' and `diag' as a",
"The method used for extracting features from covariances. Defaults to",
"classification with filter bank model. Prepare filter bank models as",
"pipeline for regression with filter bank model. Prepare filter bank",
"pipeline for filterbank models. Prepare filter bank models as used",
"not in projection_defaults: raise ValueError( f\"The `method` ('{method}') you specified",
"estimator : scikit-learn Estimator object. The estimator object. Defaults to",
"to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``,",
"estimator_ = RidgeCV(alphas=np.logspace(-3, 5, 100)) filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_,",
"\"\"\"Generate pipeline for classification with filter bank model. Prepare filter",
"estimator=None): \"\"\"Generate pipeline for classification with filter bank model. Prepare",
"on the diagonal). .. note:: The resulting model expects as",
"for filterbank models. Prepare filter bank models as used in",
"filter_bank_transformer = make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough') if categorical_interaction is not None:",
"estimator=None): \"\"\"Generate pipeline for regression with filter bank model. Prepare",
"which different covarances (e.g. for different frequencies) are stored inside",
"performed with default values. References ---------- [1] <NAME>, <NAME>, <NAME>,",
"estimator object. Defaults to None. If None, RidgeCV is performed",
"'riemann_wasserstein': dict() } vectorization_defaults = { 'riemann': dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'),",
"spread. In terms of implementation, this involves 1) projection (e.g.",
"vectorization): return [(make_pipeline(* [projection(**projection_params_), vectorization(**vectorization_params_)]), name) for name in names]",
"interaction effects after projection and vectorization steps are performed. ..",
"scale='auto', reg=1.e-05, shrink=1), 'riemann_wasserstein': dict() } vectorization_defaults = { 'riemann':",
"for name in names] # setup pipelines (projection + vectorization",
"to fit 2-way interaction effects. scaling : scikit-learn Transformer object",
"of linear regression techniques by reducing the impact of field",
"by the underlying column transformers. The pipeline also supports fitting",
"dict(scale=1, n_compo='full', reg=1.e-05), 'lw_riemann': dict(shrink=1), 'diag': dict(), 'log_diag': dict(), 'random':",
"remainder='passthrough') if categorical_interaction is not None: filter_bank_transformer = ExpandFeatures( filter_bank_transformer,",
"columns indexed by ``names``. Other columns will be passed through",
"coffeine.spatial_filters import ( ProjIdentitySpace, ProjCommonSpace, ProjLWSpace, ProjRandomSpace, ProjSPoCSpace) from sklearn.compose",
"'lw_riemann': steps = (ProjLWSpace, Riemann) elif method == 'diag': steps",
"Parameters ---------- names : list of str The column names",
"steps = (ProjIdentitySpace, NaiveVec) elif method == 'spoc': steps =",
"signals and cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893",
"== 'riemann': steps = (ProjCommonSpace, Riemann) elif method == 'lw_riemann':",
"'riemann': steps = (ProjCommonSpace, Riemann) elif method == 'lw_riemann': steps",
"Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``,",
"(ProjRandomSpace, LogDiag) elif method == 'naive': steps = (ProjIdentitySpace, NaiveVec)",
"``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict |",
"ProjSPoCSpace) from sklearn.compose import make_column_transformer from sklearn.pipeline import make_pipeline from",
"from sklearn.preprocessing import StandardScaler from sklearn.linear_model import RidgeCV, LogisticRegression def",
"covariances. method : str The method used for extracting features",
"input data frame containing a binary descriptor used to fit",
"and cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\"",
"# update defaults projection_params_ = projection_defaults[method] if projection_params is not",
"projection_params_ = projection_defaults[method] if projection_params is not None: projection_params_.update(**projection_params) vectorization_params_",
"used. estimator : scikit-learn Estimator object. The estimator object. Defaults",
"estimator_ is None: estimator_ = LogisticRegression(solver='liblinear') filter_bank_regressor = make_pipeline( filter_bank_transformer,",
"def _get_projector_vectorizer(projection, vectorization): return [(make_pipeline(* [projection(**projection_params_), vectorization(**vectorization_params_)]), name) for name",
"method == 'riemann': steps = (ProjCommonSpace, Riemann) elif method ==",
"# put defaults here for projection and vectorization step projection_defaults",
"are applied to improve the applicability of linear regression techniques",
"projection step. vectorization_params : dict | None The parameters for",
"dict(), 'riemann_wasserstein': dict(rank='full') } assert set(projection_defaults) == set(vectorization_defaults) if method",
"for different frequencies) are stored inside columns indexed by ``names``.",
"will be passed through by the underlying column transformers. The",
"= (ProjIdentitySpace, NaiveVec) elif method == 'spoc': steps = (ProjSPoCSpace,",
"method == 'diag': steps = (ProjIdentitySpace, Diag) elif method ==",
"vectorization_params_ = vectorization_defaults[method] if vectorization_params is not None: vectorization_params_.update(**vectorization_params) def",
"116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" filter_bank_transformer = make_filter_bank_transformer( names=names, method=method,",
"if categorical_interaction is not None: filter_bank_transformer = ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction)",
"matrices computed from M/EEG signals in different frequency bands. Then",
": scikit-learn Estimator object. The estimator object. Defaults to None.",
"StandardScaler() estimator_ = estimator if estimator_ is None: estimator_ =",
"Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``.",
"| None Method for re-rescaling the features. Defaults to None.",
"In terms of implementation, this involves 1) projection (e.g. spatial",
"``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None The parameters for",
"= (ProjIdentitySpace, Diag) elif method == 'log_diag': steps = (ProjIdentitySpace,",
"vectorization steps are performed. .. note:: All essential methods from",
"the log on the diagonal). .. note:: The resulting model",
"dict(), 'log_diag': dict(), 'random': dict(), 'naive': dict(method='upper'), 'spoc': dict(), 'riemann_wasserstein':",
"These models take as input sensor-space covariance matrices computed from",
"vectorization_params=None, categorical_interaction=None): \"\"\"Generate pipeline for filterbank models. Prepare filter bank",
"None The parameters for the projection step. vectorization_params : dict",
"not None: vectorization_params_.update(**vectorization_params) def _get_projector_vectorizer(projection, vectorization): return [(make_pipeline(* [projection(**projection_params_), vectorization(**vectorization_params_)]),",
"steps = (ProjIdentitySpace, LogDiag) elif method == 'random': steps =",
"projection_defaults: raise ValueError( f\"The `method` ('{method}') you specified is unknown.\")",
"update defaults projection_params_ = projection_defaults[method] if projection_params is not None:",
"'diag': dict(), 'log_diag': dict(), 'random': dict(), 'naive': dict(method='upper'), 'spoc': dict(),",
"= (ProjLWSpace, Riemann) elif method == 'diag': steps = (ProjIdentitySpace,",
"steps = (ProjSPoCSpace, LogDiag) elif method == 'riemann_wasserstein': steps =",
"reg=1.e-05, shrink=1), 'riemann_wasserstein': dict() } vectorization_defaults = { 'riemann': dict(metric='riemann'),",
"vectorization step) steps = tuple() if method == 'riemann': steps",
"[projection(**projection_params_), vectorization(**vectorization_params_)]), name) for name in names] # setup pipelines",
"if method == 'riemann': steps = (ProjCommonSpace, Riemann) elif method",
"regression techniques by reducing the impact of field spread. In",
"LogDiag) elif method == 'riemann_wasserstein': steps = (ProjIdentitySpace, RiemannSnp) filter_bank_transformer",
"is not None: vectorization_params_.update(**vectorization_params) def _get_projector_vectorizer(projection, vectorization): return [(make_pipeline(* [projection(**projection_params_),",
"== 'spoc': steps = (ProjSPoCSpace, LogDiag) elif method == 'riemann_wasserstein':",
"from sklearn.linear_model import RidgeCV, LogisticRegression def make_filter_bank_transformer(names, method='riemann', projection_params=None, vectorization_params=None,",
"def make_filter_bank_transformer(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None): \"\"\"Generate pipeline for filterbank",
"Other columns will be passed through by the underlying column",
"techniques by reducing the impact of field spread. In terms",
"method == 'naive': steps = (ProjIdentitySpace, NaiveVec) elif method ==",
"object. Defaults to None. If None, LogisticRegression is performed with",
"= RidgeCV(alphas=np.logspace(-3, 5, 100)) filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_",
"applicability of linear regression techniques by reducing the impact of",
"method : str The method used for extracting features from",
"sklearn.compose import make_column_transformer from sklearn.pipeline import make_pipeline from sklearn.preprocessing import",
"elif method == 'spoc': steps = (ProjSPoCSpace, LogDiag) elif method",
"'riemann_wasserstein': steps = (ProjIdentitySpace, RiemannSnp) filter_bank_transformer = make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough')",
"put defaults here for projection and vectorization step projection_defaults =",
"``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params :",
"return filter_bank_regressor def make_filter_bank_classifier(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None):",
"filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor def",
"dict(), 'random': dict(n_compo='full'), 'naive': dict(), 'spoc': dict(n_compo='full', scale='auto', reg=1.e-05, shrink=1),",
"(e.g. for different frequencies) are stored inside columns indexed by",
"reducing the impact of field spread. In terms of implementation,",
"fit 2-way interaction effects. scaling : scikit-learn Transformer object |",
"The resulting model expects as inputs data frames in which",
"source power to signals and cognitive states. *NeuroImage*, page 116893,2020.",
"('{method}') you specified is unknown.\") # update defaults projection_params_ =",
"steps = (ProjLWSpace, Riemann) elif method == 'diag': steps =",
"make_column_transformer from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from",
"= ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction) return filter_bank_transformer def make_filter_bank_regressor(names, method='riemann', projection_params=None,",
"``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict",
"RidgeCV, LogisticRegression def make_filter_bank_transformer(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None): \"\"\"Generate pipeline",
"as input sensor-space covariance matrices computed from M/EEG signals in",
"vectorization_params_.update(**vectorization_params) def _get_projector_vectorizer(projection, vectorization): return [(make_pipeline(* [projection(**projection_params_), vectorization(**vectorization_params_)]), name) for",
"models. Prepare filter bank models as used in [1]_. These",
"are implemented here. In practice, we recommend comparing `riemann', `spoc'",
"Riemann) elif method == 'diag': steps = (ProjIdentitySpace, Diag) elif",
"*_get_projector_vectorizer(*steps), remainder='passthrough') if categorical_interaction is not None: filter_bank_transformer = ExpandFeatures(",
"expects as inputs data frames in which different covarances (e.g.",
"for re-rescaling the features. Defaults to None. If None, StandardScaler",
"ProjIdentitySpace, ProjCommonSpace, ProjLWSpace, ProjRandomSpace, ProjSPoCSpace) from sklearn.compose import make_column_transformer from",
"The estimator object. Defaults to None. If None, RidgeCV is",
"make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough') if categorical_interaction is not None: filter_bank_transformer =",
"containing a binary descriptor used to fit 2-way interaction effects.",
"unknown.\") # update defaults projection_params_ = projection_defaults[method] if projection_params is",
"after projection and vectorization steps are performed. .. note:: All",
"make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor def make_filter_bank_classifier(names, method='riemann',",
"Estimator object. The estimator object. Defaults to None. If None,",
"None: vectorization_params_.update(**vectorization_params) def _get_projector_vectorizer(projection, vectorization): return [(make_pipeline(* [projection(**projection_params_), vectorization(**vectorization_params_)]), name)",
"Diag, LogDiag, ExpandFeatures, Riemann, RiemannSnp, NaiveVec) from coffeine.spatial_filters import (",
"categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for regression with filter bank",
"The parameters for the projection step. vectorization_params : dict |",
"projection_defaults[method] if projection_params is not None: projection_params_.update(**projection_params) vectorization_params_ = vectorization_defaults[method]",
"dict(), 'naive': dict(method='upper'), 'spoc': dict(), 'riemann_wasserstein': dict(rank='full') } assert set(projection_defaults)",
"cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" #",
"Riemann, RiemannSnp, NaiveVec) from coffeine.spatial_filters import ( ProjIdentitySpace, ProjCommonSpace, ProjLWSpace,",
"binary descriptor used to fit 2-way interaction effects. scaling :",
"method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for classification",
"elif method == 'diag': steps = (ProjIdentitySpace, Diag) elif method",
"the data frame corresponding to different covariances. method : str",
": str The column in the input data frame containing",
"in names] # setup pipelines (projection + vectorization step) steps",
": dict | None The parameters for the vectorization step.",
"} assert set(projection_defaults) == set(vectorization_defaults) if method not in projection_defaults:",
"frame corresponding to different covariances. method : str The method",
"= tuple() if method == 'riemann': steps = (ProjCommonSpace, Riemann)",
"import make_column_transformer from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler",
"column in the input data frame containing a binary descriptor",
"bank model. Prepare filter bank models as used in [1]_.",
"1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" # put defaults here for projection and",
"= make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor def make_filter_bank_classifier(names,",
"scaling_ = scaling if scaling_ is None: scaling_ = StandardScaler()",
"[(make_pipeline(* [projection(**projection_params_), vectorization(**vectorization_params_)]), name) for name in names] # setup",
"(ProjIdentitySpace, RiemannSnp) filter_bank_transformer = make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough') if categorical_interaction is",
"recommend comparing `riemann', `spoc' and `diag' as a baseline. Parameters",
"If None, StandardScaler is used. estimator : scikit-learn Estimator object.",
"for classification with filter bank model. Prepare filter bank models",
"if estimator_ is None: estimator_ = LogisticRegression(solver='liblinear') filter_bank_regressor = make_pipeline(",
"spatial filters) and 2) vectorization (e.g. taking the log on",
"a baseline. Parameters ---------- names : list of str The",
"used to fit 2-way interaction effects. References ---------- [1] <NAME>,",
"states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" # put",
"the diagonal). .. note:: The resulting model expects as inputs",
"projection_params=None, vectorization_params=None, categorical_interaction=None): \"\"\"Generate pipeline for filterbank models. Prepare filter",
"sklearn.linear_model import RidgeCV, LogisticRegression def make_filter_bank_transformer(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None):",
"LogisticRegression is performed with default values. References ---------- [1] <NAME>,",
"the applicability of linear regression techniques by reducing the impact",
"<NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Predictive regression modeling with",
"to None. If None, RidgeCV is performed with default values.",
"tuple() if method == 'riemann': steps = (ProjCommonSpace, Riemann) elif",
"binary descriptor used to fit 2-way interaction effects. References ----------",
"'lw_riemann': dict(shrink=1), 'diag': dict(), 'log_diag': dict(), 'random': dict(n_compo='full'), 'naive': dict(),",
"projection_params_.update(**projection_params) vectorization_params_ = vectorization_defaults[method] if vectorization_params is not None: vectorization_params_.update(**vectorization_params)",
"None: estimator_ = RidgeCV(alphas=np.logspace(-3, 5, 100)) filter_bank_regressor = make_pipeline( filter_bank_transformer,",
"ProjLWSpace, ProjRandomSpace, ProjSPoCSpace) from sklearn.compose import make_column_transformer from sklearn.pipeline import",
"'random': steps = (ProjRandomSpace, LogDiag) elif method == 'naive': steps",
"vectorization_params is not None: vectorization_params_.update(**vectorization_params) def _get_projector_vectorizer(projection, vectorization): return [(make_pipeline(*",
"'random': dict(), 'naive': dict(method='upper'), 'spoc': dict(), 'riemann_wasserstein': dict(rank='full') } assert",
"All essential methods from [1]_ are implemented here. In practice,",
"names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ = scaling if",
"setup pipelines (projection + vectorization step) steps = tuple() if",
"None, RidgeCV is performed with default values. References ---------- [1]",
"reg=1.e-05), 'lw_riemann': dict(shrink=1), 'diag': dict(), 'log_diag': dict(), 'random': dict(n_compo='full'), 'naive':",
"Predictive regression modeling with MEG/EEG: from source power to signals",
"categorical_interaction : str The column in the input data frame",
"The column names of the data frame corresponding to different",
"method == 'spoc': steps = (ProjSPoCSpace, LogDiag) elif method ==",
"names of the data frame corresponding to different covariances. method",
") scaling_ = scaling if scaling_ is None: scaling_ =",
"assert set(projection_defaults) == set(vectorization_defaults) if method not in projection_defaults: raise",
"filter_bank_transformer = ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction) return filter_bank_transformer def make_filter_bank_regressor(names, method='riemann',",
"inputs data frames in which different covarances (e.g. for different",
"'naive': dict(), 'spoc': dict(n_compo='full', scale='auto', reg=1.e-05, shrink=1), 'riemann_wasserstein': dict() }",
"*NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" # put defaults",
"scaling if scaling_ is None: scaling_ = StandardScaler() estimator_ =",
"'log_diag': steps = (ProjIdentitySpace, LogDiag) elif method == 'random': steps",
"str The column in the input data frame containing a",
"filter bank model. Prepare filter bank models as used in",
"here for projection and vectorization step projection_defaults = { 'riemann':",
"be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params",
"Prepare filter bank models as used in [1]_. These models",
"baseline. Parameters ---------- names : list of str The column",
"\"\"\"Generate pipeline for filterbank models. Prepare filter bank models as",
"RidgeCV is performed with default values. References ---------- [1] <NAME>,",
"the input data frame containing a binary descriptor used to",
"features. Defaults to None. If None, StandardScaler is used. estimator",
"2) vectorization (e.g. taking the log on the diagonal). ..",
"data frame containing a binary descriptor used to fit 2-way",
"as inputs data frames in which different covarances (e.g. for",
"'spoc': dict(n_compo='full', scale='auto', reg=1.e-05, shrink=1), 'riemann_wasserstein': dict() } vectorization_defaults =",
"= (ProjCommonSpace, Riemann) elif method == 'lw_riemann': steps = (ProjLWSpace,",
"`riemann', `spoc' and `diag' as a baseline. Parameters ---------- names",
"scikit-learn Estimator object. The estimator object. Defaults to None. If",
"input sensor-space covariance matrices computed from M/EEG signals in different",
"== 'log_diag': steps = (ProjIdentitySpace, LogDiag) elif method == 'random':",
"estimator_ = estimator if estimator_ is None: estimator_ = LogisticRegression(solver='liblinear')",
"covariances. Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``,",
"import StandardScaler from sklearn.linear_model import RidgeCV, LogisticRegression def make_filter_bank_transformer(names, method='riemann',",
"categorical_interaction is not None: filter_bank_transformer = ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction) return",
"Riemann) elif method == 'lw_riemann': steps = (ProjLWSpace, Riemann) elif",
"= { 'riemann': dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'), 'diag': dict(), 'log_diag': dict(),",
"(ProjIdentitySpace, Diag) elif method == 'log_diag': steps = (ProjIdentitySpace, LogDiag)",
"scaling=None, estimator=None): \"\"\"Generate pipeline for regression with filter bank model.",
"f\"The `method` ('{method}') you specified is unknown.\") # update defaults",
"raise ValueError( f\"The `method` ('{method}') you specified is unknown.\") #",
"is not None: filter_bank_transformer = ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction) return filter_bank_transformer",
"signals in different frequency bands. Then transformations are applied to",
"categorical_interaction=categorical_interaction ) scaling_ = scaling if scaling_ is None: scaling_",
"``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None",
"= (ProjIdentitySpace, RiemannSnp) filter_bank_transformer = make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough') if categorical_interaction",
"by ``names``. Other columns will be passed through by the",
"dict(n_compo='full', scale='auto', reg=1.e-05, shrink=1), 'riemann_wasserstein': dict() } vectorization_defaults = {",
"step. vectorization_params : dict | None The parameters for the",
"elif method == 'random': steps = (ProjRandomSpace, LogDiag) elif method",
"of the data frame corresponding to different covariances. method :",
"LogisticRegression(solver='liblinear') filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor",
"estimator_ = LogisticRegression(solver='liblinear') filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ )",
"object. Defaults to None. If None, RidgeCV is performed with",
"for the projection step. vectorization_params : dict | None The",
"be passed through by the underlying column transformers. The pipeline",
"steps = (ProjIdentitySpace, Diag) elif method == 'log_diag': steps =",
"Transformer object | None Method for re-rescaling the features. Defaults",
"(ProjIdentitySpace, NaiveVec) elif method == 'spoc': steps = (ProjSPoCSpace, LogDiag)",
"the vectorization step. categorical_interaction : str The column in the",
"[1]_. These models take as input sensor-space covariance matrices computed",
"ValueError( f\"The `method` ('{method}') you specified is unknown.\") # update",
"is unknown.\") # update defaults projection_params_ = projection_defaults[method] if projection_params",
"expander_column=categorical_interaction) return filter_bank_transformer def make_filter_bank_regressor(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None,",
"1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" filter_bank_transformer = make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params,",
"vectorization_params : dict | None The parameters for the vectorization",
"step. categorical_interaction : str The column in the input data",
"object | None Method for re-rescaling the features. Defaults to",
"inside columns indexed by ``names``. Other columns will be passed",
"ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" # put defaults here for projection",
"*NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" filter_bank_transformer = make_filter_bank_transformer(",
"method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for regression",
"shrink=1), 'riemann_wasserstein': dict() } vectorization_defaults = { 'riemann': dict(metric='riemann'), 'lw_riemann':",
"column names of the data frame corresponding to different covariances.",
"interaction effects. References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>, and",
"'log_diag': dict(), 'random': dict(n_compo='full'), 'naive': dict(), 'spoc': dict(n_compo='full', scale='auto', reg=1.e-05,",
"extracting features from covariances. Defaults to ``'riemann'``. Can be ``'riemann'``,",
"filterbank models. Prepare filter bank models as used in [1]_.",
"LogisticRegression def make_filter_bank_transformer(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None): \"\"\"Generate pipeline for",
"dict(rank='full') } assert set(projection_defaults) == set(vectorization_defaults) if method not in",
"Diag) elif method == 'log_diag': steps = (ProjIdentitySpace, LogDiag) elif",
"frame containing a binary descriptor used to fit 2-way interaction",
"passed through by the underlying column transformers. The pipeline also",
"None: scaling_ = StandardScaler() estimator_ = estimator if estimator_ is",
"for regression with filter bank model. Prepare filter bank models",
"is None: estimator_ = LogisticRegression(solver='liblinear') filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_,",
"effects. scaling : scikit-learn Transformer object | None Method for",
"make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ = scaling",
"fit 2-way interaction effects. References ---------- [1] <NAME>, <NAME>, <NAME>,",
"vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for classification with filter",
"= vectorization_defaults[method] if vectorization_params is not None: vectorization_params_.update(**vectorization_params) def _get_projector_vectorizer(projection,",
"and vectorization steps are performed. .. note:: All essential methods",
"descriptor used to fit 2-way interaction effects. References ---------- [1]",
"filter_bank_transformer def make_filter_bank_regressor(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate",
"pipeline also supports fitting categorical interaction effects after projection and",
"data frames in which different covarances (e.g. for different frequencies)",
"'diag': dict(), 'log_diag': dict(), 'random': dict(n_compo='full'), 'naive': dict(), 'spoc': dict(n_compo='full',",
"projection and vectorization steps are performed. .. note:: All essential",
"None: filter_bank_transformer = ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction) return filter_bank_transformer def make_filter_bank_regressor(names,",
"None, StandardScaler is used. estimator : scikit-learn Estimator object. The",
"None. If None, StandardScaler is used. estimator : scikit-learn Estimator",
"def make_filter_bank_regressor(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline",
"if projection_params is not None: projection_params_.update(**projection_params) vectorization_params_ = vectorization_defaults[method] if",
"steps are performed. .. note:: All essential methods from [1]_",
"import RidgeCV, LogisticRegression def make_filter_bank_transformer(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None): \"\"\"Generate",
": str The method used for extracting features from covariances.",
"for the vectorization step. categorical_interaction : str The column in",
"fitting categorical interaction effects after projection and vectorization steps are",
"dict(n_compo='full'), 'naive': dict(), 'spoc': dict(n_compo='full', scale='auto', reg=1.e-05, shrink=1), 'riemann_wasserstein': dict()",
"== 'lw_riemann': steps = (ProjLWSpace, Riemann) elif method == 'diag':",
"improve the applicability of linear regression techniques by reducing the",
"to signals and cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119.",
"scaling_ = StandardScaler() estimator_ = estimator if estimator_ is None:",
"is None: scaling_ = StandardScaler() estimator_ = estimator if estimator_",
"method used for extracting features from covariances. Defaults to ``'riemann'``.",
"columns will be passed through by the underlying column transformers.",
"taking the log on the diagonal). .. note:: The resulting",
"= (ProjIdentitySpace, LogDiag) elif method == 'random': steps = (ProjRandomSpace,",
"Then transformations are applied to improve the applicability of linear",
"ProjCommonSpace, ProjLWSpace, ProjRandomSpace, ProjSPoCSpace) from sklearn.compose import make_column_transformer from sklearn.pipeline",
"in different frequency bands. Then transformations are applied to improve",
"return [(make_pipeline(* [projection(**projection_params_), vectorization(**vectorization_params_)]), name) for name in names] #",
"through by the underlying column transformers. The pipeline also supports",
"defaults projection_params_ = projection_defaults[method] if projection_params is not None: projection_params_.update(**projection_params)",
"bank models as used in [1]_. These models take as",
"dict(metric='riemann'), 'diag': dict(), 'log_diag': dict(), 'random': dict(), 'naive': dict(method='upper'), 'spoc':",
"frames in which different covarances (e.g. for different frequencies) are",
"resulting model expects as inputs data frames in which different",
"different covariances. method : str The method used for extracting",
"LogDiag) elif method == 'random': steps = (ProjRandomSpace, LogDiag) elif",
"make_filter_bank_transformer(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None): \"\"\"Generate pipeline for filterbank models.",
"step projection_defaults = { 'riemann': dict(scale=1, n_compo='full', reg=1.e-05), 'lw_riemann': dict(shrink=1),",
"1) projection (e.g. spatial filters) and 2) vectorization (e.g. taking",
"page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" # put defaults here",
"'riemann': dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'), 'diag': dict(), 'log_diag': dict(), 'random': dict(),",
"from coffeine.spatial_filters import ( ProjIdentitySpace, ProjCommonSpace, ProjLWSpace, ProjRandomSpace, ProjSPoCSpace) from",
"`method` ('{method}') you specified is unknown.\") # update defaults projection_params_",
"vectorization step. categorical_interaction : str The column in the input",
"= estimator if estimator_ is None: estimator_ = LogisticRegression(solver='liblinear') filter_bank_regressor",
"to None. If None, LogisticRegression is performed with default values.",
"are stored inside columns indexed by ``names``. Other columns will",
"bands. Then transformations are applied to improve the applicability of",
"not None: projection_params_.update(**projection_params) vectorization_params_ = vectorization_defaults[method] if vectorization_params is not",
"= { 'riemann': dict(scale=1, n_compo='full', reg=1.e-05), 'lw_riemann': dict(shrink=1), 'diag': dict(),",
"with default values. References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>,",
"<NAME>, and <NAME>. Predictive regression modeling with MEG/EEG: from source",
"ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" filter_bank_transformer = make_filter_bank_transformer( names=names, method=method, projection_params=projection_params,",
"estimator if estimator_ is None: estimator_ = RidgeCV(alphas=np.logspace(-3, 5, 100))",
"dict | None The parameters for the vectorization step. categorical_interaction",
"name in names] # setup pipelines (projection + vectorization step)",
"Defaults to None. If None, LogisticRegression is performed with default",
"and `diag' as a baseline. Parameters ---------- names : list",
"scikit-learn Transformer object | None Method for re-rescaling the features.",
"} vectorization_defaults = { 'riemann': dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'), 'diag': dict(),",
"projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for regression with",
".. note:: All essential methods from [1]_ are implemented here.",
"= make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough') if categorical_interaction is not None: filter_bank_transformer",
"field spread. In terms of implementation, this involves 1) projection",
"data frame corresponding to different covariances. method : str The",
"n_compo='full', reg=1.e-05), 'lw_riemann': dict(shrink=1), 'diag': dict(), 'log_diag': dict(), 'random': dict(n_compo='full'),",
"features from covariances. Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``,",
"pipelines (projection + vectorization step) steps = tuple() if method",
"\"\"\" filter_bank_transformer = make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction )",
"<NAME>. Predictive regression modeling with MEG/EEG: from source power to",
"\"\"\"Generate pipeline for regression with filter bank model. Prepare filter",
"terms of implementation, this involves 1) projection (e.g. spatial filters)",
"of implementation, this involves 1) projection (e.g. spatial filters) and",
"method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ = scaling if scaling_",
"is used. estimator : scikit-learn Estimator object. The estimator object.",
"_get_projector_vectorizer(projection, vectorization): return [(make_pipeline(* [projection(**projection_params_), vectorization(**vectorization_params_)]), name) for name in",
"in the input data frame containing a binary descriptor used",
"column transformers. The pipeline also supports fitting categorical interaction effects",
"None: projection_params_.update(**projection_params) vectorization_params_ = vectorization_defaults[method] if vectorization_params is not None:",
"(ProjCommonSpace, Riemann) elif method == 'lw_riemann': steps = (ProjLWSpace, Riemann)",
"coffeine.covariance_transformers import ( Diag, LogDiag, ExpandFeatures, Riemann, RiemannSnp, NaiveVec) from",
"to improve the applicability of linear regression techniques by reducing",
"to different covariances. method : str The method used for",
"None The parameters for the vectorization step. categorical_interaction : str",
"None: estimator_ = LogisticRegression(solver='liblinear') filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_",
"we recommend comparing `riemann', `spoc' and `diag' as a baseline.",
"== 'random': steps = (ProjRandomSpace, LogDiag) elif method == 'naive':",
"and vectorization step projection_defaults = { 'riemann': dict(scale=1, n_compo='full', reg=1.e-05),",
"estimator object. Defaults to None. If None, LogisticRegression is performed",
"numpy as np from coffeine.covariance_transformers import ( Diag, LogDiag, ExpandFeatures,",
"default values. References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>, and",
"---------- names : list of str The column names of",
"{ 'riemann': dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'), 'diag': dict(), 'log_diag': dict(), 'random':",
"from source power to signals and cognitive states. *NeuroImage*, page",
"(ProjLWSpace, Riemann) elif method == 'diag': steps = (ProjIdentitySpace, Diag)",
"impact of field spread. In terms of implementation, this involves",
"== 'riemann_wasserstein': steps = (ProjIdentitySpace, RiemannSnp) filter_bank_transformer = make_column_transformer( *_get_projector_vectorizer(*steps),",
"``'random'``, ``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None The",
"by reducing the impact of field spread. In terms of",
"[1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Predictive regression modeling",
"linear regression techniques by reducing the impact of field spread.",
"a binary descriptor used to fit 2-way interaction effects. References",
"'spoc': steps = (ProjSPoCSpace, LogDiag) elif method == 'riemann_wasserstein': steps",
"diagonal). .. note:: The resulting model expects as inputs data",
"object. The estimator object. Defaults to None. If None, LogisticRegression",
"in [1]_. These models take as input sensor-space covariance matrices",
"a binary descriptor used to fit 2-way interaction effects. scaling",
"dict(shrink=1), 'diag': dict(), 'log_diag': dict(), 'random': dict(n_compo='full'), 'naive': dict(), 'spoc':",
"2-way interaction effects. scaling : scikit-learn Transformer object | None",
"in projection_defaults: raise ValueError( f\"The `method` ('{method}') you specified is",
"is performed with default values. References ---------- [1] <NAME>, <NAME>,",
"StandardScaler from sklearn.linear_model import RidgeCV, LogisticRegression def make_filter_bank_transformer(names, method='riemann', projection_params=None,",
"The estimator object. Defaults to None. If None, LogisticRegression is",
"make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import RidgeCV, LogisticRegression",
"= scaling if scaling_ is None: scaling_ = StandardScaler() estimator_",
"elif method == 'riemann_wasserstein': steps = (ProjIdentitySpace, RiemannSnp) filter_bank_transformer =",
"import ( Diag, LogDiag, ExpandFeatures, Riemann, RiemannSnp, NaiveVec) from coffeine.spatial_filters",
"vectorization(**vectorization_params_)]), name) for name in names] # setup pipelines (projection",
"sensor-space covariance matrices computed from M/EEG signals in different frequency",
"``'riemann_wasserstein'``. projection_params : dict | None The parameters for the",
"stored inside columns indexed by ``names``. Other columns will be",
"StandardScaler is used. estimator : scikit-learn Estimator object. The estimator",
"transformers. The pipeline also supports fitting categorical interaction effects after",
"make_filter_bank_regressor(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for",
"set(projection_defaults) == set(vectorization_defaults) if method not in projection_defaults: raise ValueError(",
"used for extracting features from covariances. Defaults to ``'riemann'``. Can",
"cognitive states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" filter_bank_transformer",
"[1]_ are implemented here. In practice, we recommend comparing `riemann',",
"categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for classification with filter bank",
"filter bank models as used in [1]_. These models take",
"estimator_ = estimator if estimator_ is None: estimator_ = RidgeCV(alphas=np.logspace(-3,",
"methods from [1]_ are implemented here. In practice, we recommend",
"elif method == 'log_diag': steps = (ProjIdentitySpace, LogDiag) elif method",
"projection (e.g. spatial filters) and 2) vectorization (e.g. taking the",
"frequencies) are stored inside columns indexed by ``names``. Other columns",
") return filter_bank_regressor def make_filter_bank_classifier(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None,",
"power to signals and cognitive states. *NeuroImage*, page 116893,2020. ISSN",
"estimator_ is None: estimator_ = RidgeCV(alphas=np.logspace(-3, 5, 100)) filter_bank_regressor =",
"parameters for the vectorization step. categorical_interaction : str The column",
"projection_params is not None: projection_params_.update(**projection_params) vectorization_params_ = vectorization_defaults[method] if vectorization_params",
"RidgeCV(alphas=np.logspace(-3, 5, 100)) filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ )",
"import numpy as np from coffeine.covariance_transformers import ( Diag, LogDiag,",
"dict(), 'log_diag': dict(), 'random': dict(n_compo='full'), 'naive': dict(), 'spoc': dict(n_compo='full', scale='auto',",
"'riemann_wasserstein': dict(rank='full') } assert set(projection_defaults) == set(vectorization_defaults) if method not",
"Method for re-rescaling the features. Defaults to None. If None,",
"RiemannSnp) filter_bank_transformer = make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough') if categorical_interaction is not",
"from covariances. Defaults to ``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``,",
"(ProjSPoCSpace, LogDiag) elif method == 'riemann_wasserstein': steps = (ProjIdentitySpace, RiemannSnp)",
": scikit-learn Transformer object | None Method for re-rescaling the",
"categorical interaction effects after projection and vectorization steps are performed.",
"= LogisticRegression(solver='liblinear') filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return",
"with filter bank model. Prepare filter bank models as used",
"References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Predictive",
"<NAME>, <NAME>, <NAME>, and <NAME>. Predictive regression modeling with MEG/EEG:",
"method == 'random': steps = (ProjRandomSpace, LogDiag) elif method ==",
"implemented here. In practice, we recommend comparing `riemann', `spoc' and",
"'lw_riemann': dict(metric='riemann'), 'diag': dict(), 'log_diag': dict(), 'random': dict(), 'naive': dict(method='upper'),",
"this involves 1) projection (e.g. spatial filters) and 2) vectorization",
"steps = (ProjIdentitySpace, RiemannSnp) filter_bank_transformer = make_column_transformer( *_get_projector_vectorizer(*steps), remainder='passthrough') if",
"vectorization step projection_defaults = { 'riemann': dict(scale=1, n_compo='full', reg=1.e-05), 'lw_riemann':",
"= StandardScaler() estimator_ = estimator if estimator_ is None: estimator_",
"if estimator_ is None: estimator_ = RidgeCV(alphas=np.logspace(-3, 5, 100)) filter_bank_regressor",
"``'naive'``, ``'spoc'``, ``'riemann_wasserstein'``. projection_params : dict | None The parameters",
"(e.g. spatial filters) and 2) vectorization (e.g. taking the log",
"The parameters for the vectorization step. categorical_interaction : str The",
"dict() } vectorization_defaults = { 'riemann': dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'), 'diag':",
"you specified is unknown.\") # update defaults projection_params_ = projection_defaults[method]",
"here. In practice, we recommend comparing `riemann', `spoc' and `diag'",
"is not None: projection_params_.update(**projection_params) vectorization_params_ = vectorization_defaults[method] if vectorization_params is",
"LogDiag) elif method == 'naive': steps = (ProjIdentitySpace, NaiveVec) elif",
"str The method used for extracting features from covariances. Defaults",
"+ vectorization step) steps = tuple() if method == 'riemann':",
"comparing `riemann', `spoc' and `diag' as a baseline. Parameters ----------",
"elif method == 'naive': steps = (ProjIdentitySpace, NaiveVec) elif method",
"indexed by ``names``. Other columns will be passed through by",
"corresponding to different covariances. method : str The method used",
"If None, RidgeCV is performed with default values. References ----------",
"parameters for the projection step. vectorization_params : dict | None",
"if vectorization_params is not None: vectorization_params_.update(**vectorization_params) def _get_projector_vectorizer(projection, vectorization): return",
"Defaults to None. If None, RidgeCV is performed with default",
": list of str The column names of the data",
"not None: filter_bank_transformer = ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction) return filter_bank_transformer def",
"# setup pipelines (projection + vectorization step) steps = tuple()",
"regression modeling with MEG/EEG: from source power to signals and",
"descriptor used to fit 2-way interaction effects. scaling : scikit-learn",
"used to fit 2-way interaction effects. scaling : scikit-learn Transformer",
"116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" # put defaults here for",
"= make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ =",
"method == 'riemann_wasserstein': steps = (ProjIdentitySpace, RiemannSnp) filter_bank_transformer = make_column_transformer(",
"scaling_, estimator_ ) return filter_bank_regressor def make_filter_bank_classifier(names, method='riemann', projection_params=None, vectorization_params=None,",
"are performed. .. note:: All essential methods from [1]_ are",
"None Method for re-rescaling the features. Defaults to None. If",
"dict | None The parameters for the projection step. vectorization_params",
"sklearn.preprocessing import StandardScaler from sklearn.linear_model import RidgeCV, LogisticRegression def make_filter_bank_transformer(names,",
"== set(vectorization_defaults) if method not in projection_defaults: raise ValueError( f\"The",
"states. *NeuroImage*, page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" filter_bank_transformer =",
"the impact of field spread. In terms of implementation, this",
"involves 1) projection (e.g. spatial filters) and 2) vectorization (e.g.",
"filter_bank_transformer, expander_column=categorical_interaction) return filter_bank_transformer def make_filter_bank_regressor(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None,",
"supports fitting categorical interaction effects after projection and vectorization steps",
"== 'diag': steps = (ProjIdentitySpace, Diag) elif method == 'log_diag':",
"is None: estimator_ = RidgeCV(alphas=np.logspace(-3, 5, 100)) filter_bank_regressor = make_pipeline(",
"with MEG/EEG: from source power to signals and cognitive states.",
"object. The estimator object. Defaults to None. If None, RidgeCV",
"'riemann': dict(scale=1, n_compo='full', reg=1.e-05), 'lw_riemann': dict(shrink=1), 'diag': dict(), 'log_diag': dict(),",
"( ProjIdentitySpace, ProjCommonSpace, ProjLWSpace, ProjRandomSpace, ProjSPoCSpace) from sklearn.compose import make_column_transformer",
"filters) and 2) vectorization (e.g. taking the log on the",
"= (ProjRandomSpace, LogDiag) elif method == 'naive': steps = (ProjIdentitySpace,",
"list of str The column names of the data frame",
"page 116893,2020. ISSN 1053-8119. https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" filter_bank_transformer = make_filter_bank_transformer( names=names,",
"performed. .. note:: All essential methods from [1]_ are implemented",
"implementation, this involves 1) projection (e.g. spatial filters) and 2)",
"regression with filter bank model. Prepare filter bank models as",
"(ProjIdentitySpace, LogDiag) elif method == 'random': steps = (ProjRandomSpace, LogDiag)",
"``names``. Other columns will be passed through by the underlying",
"set(vectorization_defaults) if method not in projection_defaults: raise ValueError( f\"The `method`",
"and <NAME>. Predictive regression modeling with MEG/EEG: from source power",
"models take as input sensor-space covariance matrices computed from M/EEG",
"scaling_ is None: scaling_ = StandardScaler() estimator_ = estimator if",
"categorical_interaction=None): \"\"\"Generate pipeline for filterbank models. Prepare filter bank models",
"\"\"\" # put defaults here for projection and vectorization step",
"ProjRandomSpace, ProjSPoCSpace) from sklearn.compose import make_column_transformer from sklearn.pipeline import make_pipeline",
"model. Prepare filter bank models as used in [1]_. These",
"models as used in [1]_. These models take as input",
"import ( ProjIdentitySpace, ProjCommonSpace, ProjLWSpace, ProjRandomSpace, ProjSPoCSpace) from sklearn.compose import",
"the underlying column transformers. The pipeline also supports fitting categorical",
"note:: The resulting model expects as inputs data frames in",
"step) steps = tuple() if method == 'riemann': steps =",
"the features. Defaults to None. If None, StandardScaler is used.",
"as np from coffeine.covariance_transformers import ( Diag, LogDiag, ExpandFeatures, Riemann,",
"method == 'log_diag': steps = (ProjIdentitySpace, LogDiag) elif method ==",
"https://doi.org/10.1016/j.neuroimage.2020.116893 \"\"\" filter_bank_transformer = make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction",
"NaiveVec) elif method == 'spoc': steps = (ProjSPoCSpace, LogDiag) elif",
"effects. References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>.",
"vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ = scaling if scaling_ is None:",
"MEG/EEG: from source power to signals and cognitive states. *NeuroImage*,",
"also supports fitting categorical interaction effects after projection and vectorization",
"for projection and vectorization step projection_defaults = { 'riemann': dict(scale=1,",
"vectorization (e.g. taking the log on the diagonal). .. note::",
".. note:: The resulting model expects as inputs data frames",
"import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import RidgeCV,",
"log on the diagonal). .. note:: The resulting model expects",
"filter_bank_regressor def make_filter_bank_classifier(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate",
"elif method == 'lw_riemann': steps = (ProjLWSpace, Riemann) elif method",
"( Diag, LogDiag, ExpandFeatures, Riemann, RiemannSnp, NaiveVec) from coffeine.spatial_filters import",
"different covarances (e.g. for different frequencies) are stored inside columns",
"specified is unknown.\") # update defaults projection_params_ = projection_defaults[method] if",
"from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model",
"scaling=None, estimator=None): \"\"\"Generate pipeline for classification with filter bank model.",
"steps = tuple() if method == 'riemann': steps = (ProjCommonSpace,",
"vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for regression with filter",
"'random': dict(n_compo='full'), 'naive': dict(), 'spoc': dict(n_compo='full', scale='auto', reg=1.e-05, shrink=1), 'riemann_wasserstein':",
"In practice, we recommend comparing `riemann', `spoc' and `diag' as",
"in which different covarances (e.g. for different frequencies) are stored",
"The pipeline also supports fitting categorical interaction effects after projection",
"2-way interaction effects. References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>,",
"defaults here for projection and vectorization step projection_defaults = {",
"take as input sensor-space covariance matrices computed from M/EEG signals",
"scaling : scikit-learn Transformer object | None Method for re-rescaling",
"`diag' as a baseline. Parameters ---------- names : list of",
"5, 100)) filter_bank_regressor = make_pipeline( filter_bank_transformer, scaling_, estimator_ ) return",
"def make_filter_bank_classifier(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline",
"projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for classification with",
"as used in [1]_. These models take as input sensor-space",
"used in [1]_. These models take as input sensor-space covariance",
"names] # setup pipelines (projection + vectorization step) steps =",
"NaiveVec) from coffeine.spatial_filters import ( ProjIdentitySpace, ProjCommonSpace, ProjLWSpace, ProjRandomSpace, ProjSPoCSpace)",
"projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_ = scaling if scaling_ is",
"= estimator if estimator_ is None: estimator_ = RidgeCV(alphas=np.logspace(-3, 5,",
"of field spread. In terms of implementation, this involves 1)",
"'spoc': dict(), 'riemann_wasserstein': dict(rank='full') } assert set(projection_defaults) == set(vectorization_defaults) if",
"interaction effects. scaling : scikit-learn Transformer object | None Method",
"ExpandFeatures( filter_bank_transformer, expander_column=categorical_interaction) return filter_bank_transformer def make_filter_bank_regressor(names, method='riemann', projection_params=None, vectorization_params=None,",
"and 2) vectorization (e.g. taking the log on the diagonal).",
"RiemannSnp, NaiveVec) from coffeine.spatial_filters import ( ProjIdentitySpace, ProjCommonSpace, ProjLWSpace, ProjRandomSpace,",
"of str The column names of the data frame corresponding",
"'diag': steps = (ProjIdentitySpace, Diag) elif method == 'log_diag': steps",
"covariance matrices computed from M/EEG signals in different frequency bands.",
"values. References ---------- [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>.",
"= (ProjSPoCSpace, LogDiag) elif method == 'riemann_wasserstein': steps = (ProjIdentitySpace,",
"<NAME>, <NAME>, and <NAME>. Predictive regression modeling with MEG/EEG: from",
"make_filter_bank_classifier(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None): \"\"\"Generate pipeline for",
"method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None): \"\"\"Generate pipeline for filterbank models. Prepare",
"| None The parameters for the projection step. vectorization_params :",
"to None. If None, StandardScaler is used. estimator : scikit-learn",
"= projection_defaults[method] if projection_params is not None: projection_params_.update(**projection_params) vectorization_params_ =",
"dict(), 'random': dict(), 'naive': dict(method='upper'), 'spoc': dict(), 'riemann_wasserstein': dict(rank='full') }",
"to fit 2-way interaction effects. References ---------- [1] <NAME>, <NAME>,",
"filter_bank_transformer, scaling_, estimator_ ) return filter_bank_regressor def make_filter_bank_classifier(names, method='riemann', projection_params=None,",
"vectorization_defaults[method] if vectorization_params is not None: vectorization_params_.update(**vectorization_params) def _get_projector_vectorizer(projection, vectorization):",
"dict(method='upper'), 'spoc': dict(), 'riemann_wasserstein': dict(rank='full') } assert set(projection_defaults) == set(vectorization_defaults)",
"None. If None, LogisticRegression is performed with default values. References",
"covarances (e.g. for different frequencies) are stored inside columns indexed",
"Defaults to None. If None, StandardScaler is used. estimator :",
"If None, LogisticRegression is performed with default values. References ----------",
"estimator_ ) return filter_bank_regressor def make_filter_bank_classifier(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None,",
"different frequencies) are stored inside columns indexed by ``names``. Other",
"different frequency bands. Then transformations are applied to improve the",
"dict(), 'spoc': dict(n_compo='full', scale='auto', reg=1.e-05, shrink=1), 'riemann_wasserstein': dict() } vectorization_defaults",
"estimator if estimator_ is None: estimator_ = LogisticRegression(solver='liblinear') filter_bank_regressor =",
"essential methods from [1]_ are implemented here. In practice, we",
"projection_defaults = { 'riemann': dict(scale=1, n_compo='full', reg=1.e-05), 'lw_riemann': dict(shrink=1), 'diag':",
"re-rescaling the features. Defaults to None. If None, StandardScaler is",
"== 'naive': steps = (ProjIdentitySpace, NaiveVec) elif method == 'spoc':",
"return filter_bank_transformer def make_filter_bank_regressor(names, method='riemann', projection_params=None, vectorization_params=None, categorical_interaction=None, scaling=None, estimator=None):",
"names : list of str The column names of the",
"{ 'riemann': dict(scale=1, n_compo='full', reg=1.e-05), 'lw_riemann': dict(shrink=1), 'diag': dict(), 'log_diag':",
"if method not in projection_defaults: raise ValueError( f\"The `method` ('{method}')",
"method == 'lw_riemann': steps = (ProjLWSpace, Riemann) elif method ==",
"note:: All essential methods from [1]_ are implemented here. In",
"model expects as inputs data frames in which different covarances",
"steps = (ProjRandomSpace, LogDiag) elif method == 'naive': steps =",
"from coffeine.covariance_transformers import ( Diag, LogDiag, ExpandFeatures, Riemann, RiemannSnp, NaiveVec)",
"dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'), 'diag': dict(), 'log_diag': dict(), 'random': dict(), 'naive':",
"effects after projection and vectorization steps are performed. .. note::",
"for extracting features from covariances. Defaults to ``'riemann'``. Can be",
"underlying column transformers. The pipeline also supports fitting categorical interaction",
"ExpandFeatures, Riemann, RiemannSnp, NaiveVec) from coffeine.spatial_filters import ( ProjIdentitySpace, ProjCommonSpace,",
"(e.g. taking the log on the diagonal). .. note:: The",
"vectorization_defaults = { 'riemann': dict(metric='riemann'), 'lw_riemann': dict(metric='riemann'), 'diag': dict(), 'log_diag':",
"'log_diag': dict(), 'random': dict(), 'naive': dict(method='upper'), 'spoc': dict(), 'riemann_wasserstein': dict(rank='full')",
"None. If None, RidgeCV is performed with default values. References",
"applied to improve the applicability of linear regression techniques by",
"LogDiag, ExpandFeatures, Riemann, RiemannSnp, NaiveVec) from coffeine.spatial_filters import ( ProjIdentitySpace,",
"transformations are applied to improve the applicability of linear regression",
"from [1]_ are implemented here. In practice, we recommend comparing",
"steps = (ProjCommonSpace, Riemann) elif method == 'lw_riemann': steps =",
"modeling with MEG/EEG: from source power to signals and cognitive",
"`spoc' and `diag' as a baseline. Parameters ---------- names :",
"str The column names of the data frame corresponding to",
"projection_params : dict | None The parameters for the projection",
"(projection + vectorization step) steps = tuple() if method ==",
"``'riemann'``. Can be ``'riemann'``, ``'lw_riemann'``, ``'diag'``, ``'log_diag'``, ``'random'``, ``'naive'``, ``'spoc'``,",
"The column in the input data frame containing a binary",
"method not in projection_defaults: raise ValueError( f\"The `method` ('{method}') you",
"from sklearn.compose import make_column_transformer from sklearn.pipeline import make_pipeline from sklearn.preprocessing",
"projection and vectorization step projection_defaults = { 'riemann': dict(scale=1, n_compo='full',",
"from M/EEG signals in different frequency bands. Then transformations are",
"None, LogisticRegression is performed with default values. References ---------- [1]",
"'naive': steps = (ProjIdentitySpace, NaiveVec) elif method == 'spoc': steps",
"M/EEG signals in different frequency bands. Then transformations are applied",
"as a baseline. Parameters ---------- names : list of str",
"filter_bank_transformer = make_filter_bank_transformer( names=names, method=method, projection_params=projection_params, vectorization_params=vectorization_params, categorical_interaction=categorical_interaction ) scaling_",
"if scaling_ is None: scaling_ = StandardScaler() estimator_ = estimator",
"'naive': dict(method='upper'), 'spoc': dict(), 'riemann_wasserstein': dict(rank='full') } assert set(projection_defaults) ==",
": dict | None The parameters for the projection step.",
"name) for name in names] # setup pipelines (projection +"
] |
[
"side, currMover): board[row][col]['lines'].append(side) if row <= size - 1 and",
"row in range(0, len(board)): for col in range(0, len(board[row])): board_string",
"self.label is None: return super(DotLineState, self).__str__() return self.label class DotsAndLines(Game):",
"dotLine: [ won, lost, tied, winin1Dots, winIn5_3x3, play ] }",
"import isnumber from grading.util import print_table class GameState: def __init__(self,",
"in sides: if side in board[row][col]['lines']: continue complete = False",
"scores['A'] += 1 if board[row][col]['winner'] == 'B': scores['B'] += 1",
"label='losein1' ) winin2 = GameState( to_move='H', position=(0, 0), board=[[nan, 3,",
"board_string += ' |' else: board_string += ' ' board_string",
"len(board) - 1: for col in range(0, len(board[row])): board_string +=",
"= currMover return board def countScore(board): scores = {'A': 0,",
"yet taken.\" r, c = state.position if state.to_move == 'H':",
"def opponent(self, player): if player == 'A': return 'B' if",
"= countScore(newState.board) return newState def utility(self, state, player): \"Player relative",
"scores={'A': 3, 'B': 1}) dotLineBoard = [[{'winner': 'A', 'lines': ['T',",
"'B': 1}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L',",
"['L', 'R']}, {'winner': '', 'lines': ['L', 'R']}], [{'winner': '', 'lines':",
"'', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['T', 'L']}, {'winner':",
"|' else: board_string += ' ' board_string += '\\n' if",
"self.label class DotsAndLines(Game): \"\"\" An implementation of Dots and Lines",
"5], [9, 1, 3, 2], [8, 6, 4, 4], [9,",
"= nextMover newState.board = applyMove(newState.board, self.size, row, col, side, currMover)",
">= 0 and col != size - 1 and side",
"+= ' ' board_string += '\\n' if row == len(board)",
"if col <= size - 1 and col != 0",
"deepcopy from utils import isnumber from grading.util import print_table class",
"moves = availableMoves(state.board) return moves # defines the order of",
"'R']}], [{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B',",
"3, 'B': 1}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B',",
"side)) moveList = [] while not moves.empty(): moveList.append(moves.get(1)) return moveList",
"won = GameState( to_move='H', position=(0, 1), board=[[nan, nan], [9, nan]],",
"= {'A': 0, 'B': 0} for row in range(0, len(board)):",
"ThinkAhead(stolen) def availableMoves(board): sides = ['T', 'B', 'L', 'R'] moves",
"move assert state.board[r][c] == v currMover = state.to_move nextMover =",
"utility(self, state, player): \"Player relative score\" opponent = self.opponent(player) return",
"!= size - 1 and side == 'B': board[row +",
"{'winner': '', 'lines': ['L', 'R']}], [{'winner': '', 'lines': ['B', 'L',",
"def __init__(self, state): self.initial = state def actions(self, state): \"Legal",
"= board self.label = label self.scores = {'H': 0, 'V':",
"nan newState.scores[currMover] += v return newState def utility(self, state, player):",
"= 3 # http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen = GameState( to_move='H', position=(3, 1),",
"v = move assert state.board[r][c] == v currMover = state.to_move",
"taken.\" r, c = state.position if state.to_move == 'H': moves",
"0, 'B': 0} for row in range(0, len(board)): for col",
"lost.scores = {'H': 0, 'V': 9} winin1 = GameState( to_move='H',",
"'lines': ['L', 'B']}, {'winner': '', 'lines': ['B', 'R']}], ] winIn5_3x3",
"side == 'B': board[row + 1][col]['lines'].append('T') if col <= size",
"Lines \"\"\" def __init__(self, state): self.initial = state self.size =",
"[8, 6, 4, 4], [9, nan, 1, 5]], label='stolen' )",
"= to_move self.position = position self.board = board self.label =",
"== 'A': scores['A'] += 1 if board[row][col]['winner'] == 'B': scores['B']",
"+= ' |' else: board_string += ' ' board_string +=",
"PriorityQueue() for row in range(0, len(board)): for col in range(0,",
"return super(GameState, self).__str__() return self.label class Move: def __init__(self, r,",
"['T', 'L']}]] winin1Dots = DotLineState(board=dotLineBoard, to_move='A', label='Win in 1', scores={'A':",
"'R']}]] lost = DotLineState(board=dotLineBoard, to_move='A', label='Lost', scores={'A': 1, 'B': 3})",
"label='winin1' ) losein1 = GameState( to_move='V', position=(0, 0), board=[[nan, nan],",
"class GameState: def __init__(self, to_move, position, board, label=None): self.to_move =",
"'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]]",
"len(self.actions(state)) == 0 def display(self, state): print_table(state.board, njust='center', sep=',') print('Score:",
"+ str(state.scores)) won = GameState( to_move='H', position=(0, 1), board=[[nan, nan],",
"if complete: board[row][col]['winner'] = currMover return board def countScore(board): scores",
"0 and col != size - 1 and side ==",
"self.to_move = to_move self.position = position self.board = board self.label",
"{'H': 0, 'V': 0} def __str__(self): if self.label == None:",
"for c in range(len(row)): if isnan(row[c]): continue v = row[c]",
"col != size - 1 and side == 'R': board[row][col",
"self.col = c self.value = v def rcv(self): return self.row,",
"state.to_move == 'H': moves = movesInRow(state.board, r) return moves if",
"newState.position = r, c newState.board[r][c] = nan newState.scores[currMover] += v",
"nan]], label='won' ) won.scores = {'H': 9, 'V': 0} lost",
"1]], label='losein2' ) losein2.maxDepth = 3 # http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen =",
"'lines': ['B', 'L', 'R']}, {'winner': '', 'lines': ['L', 'B']}, {'winner':",
"'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}],",
"return self.label class Move: def __init__(self, r, c, v): self.row",
"if 'L' in board[row][space]['lines']: board_string += '| ' else: board_string",
"player): if player == 'A': return 'B' if player ==",
"3 # http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen = GameState( to_move='H', position=(3, 1), board=[[3,",
"player == 'H': return 'V' if player == 'V': return",
"' ' if col == len(board[row]) - 1: board_string +=",
"['T', 'B', 'L', 'R']}]] tied = DotLineState(board=dotLineBoard, to_move='A', label='Tied', scores={'A':",
") losein2.maxDepth = 3 # http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen = GameState( to_move='H',",
"super(GameState, self).__str__() return self.label class Move: def __init__(self, r, c,",
"movesInRow(state.board, r) return moves if state.to_move == 'V': moves =",
"col, side)) moveList = [] while not moves.empty(): moveList.append(moves.get(1)) return",
"position=(1, 1), board=[[nan, nan], [9, nan]], label='winin1' ) losein1 =",
"0} for row in range(0, len(board)): for col in range(0,",
"GameState( to_move='V', position=(0, 0), board=[[nan, nan, nan], [3, 9, nan],",
"'B', 'L', 'R']}, {'winner': '', 'lines': ['T', 'L']}]] winin1Dots =",
"v return newState def utility(self, state, player): \"Player relative score\"",
"= board self.label = label self.scores = scores def __str__(self):",
"squares.\" return len(self.actions(state)) == 0 def display(self, state): print_table(state.board, njust='center',",
"copy import deepcopy from utils import isnumber from grading.util import",
"size - 1 and side == 'B': board[row + 1][col]['lines'].append('T')",
"'*' if 'T' in board[row][col]['lines']: board_string += '---' else: board_string",
"'R']}, {'winner': '', 'lines': ['L', 'R']}], [{'winner': '', 'lines': ['B',",
"r self.col = c self.value = v def rcv(self): return",
"' else: board_string += ' ' if '' != board[row][space]['winner']:",
"label='Start') #amended by whh dotLine = DotsAndLines(play) #dotLine = DotsAndLines(winIn5_3x3)",
"[9, nan, 1, 5]], label='stolen' ) choose1 = GameState( to_move='H',",
"== v currMover = state.to_move nextMover = self.opponent(currMover) newState =",
"= PriorityQueue() for row in range(0, len(board)): for col in",
"== len(board[row]) - 1: board_string += '*\\n' for space in",
"nan, nan], [nan, nan, nan, nan], [nan, 6, 4, 5],",
"if 'B' in board[row][col]['lines']: board_string += '---' else: board_string +=",
"class DotLineState: def __init__(self, to_move, board, label=None, scores={'A': 0, 'B':",
"moves = movesInRow(state.board, r) return moves if state.to_move == 'V':",
"- 1 and col != 0 and side == 'L':",
"3, 2], [nan, 9, nan], [nan, nan, 1]], label='winin2' )",
"'B' if player == 'B': return 'A' return None def",
"col, side, currMover): board[row][col]['lines'].append(side) if row <= size - 1",
"in board[row][col]['lines']: moves.put((row, col, side)) moveList = [] while not",
"for col in range(0, len(board[row])): board_string += '*' if 'T'",
"self).__str__() return self.label class Move: def __init__(self, r, c, v):",
"DotLineState(board=dotLineBoard, to_move='A', label='Win in 1', scores={'A': 2, 'B': 1}) dotLineBoard",
"scores={'A': 2, 'B': 1}) dotLineBoard = [[{'winner': '', 'lines': ['L',",
"'', 'lines': []}]], to_move='A', label='Start') #amended by whh dotLine =",
"[{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines':",
"and 'R' in board[row][space]['lines']: board_string += ' |' else: board_string",
"board[row][space]['lines']: board_string += ' |' else: board_string += ' '",
"yet taken.\" moves = availableMoves(state.board) return moves # defines the",
"= { dotLine: [ won, lost, tied, winin1Dots, winIn5_3x3, play",
"'V': 0} def __str__(self): if self.label == None: return super(GameState,",
"len(board[row])): if 'L' in board[row][space]['lines']: board_string += '| ' else:",
"player == 'A': return 'B' if player == 'B': return",
"board[row][space]['winner'] else: board_string += ' ' if space == len(board[row])",
"'lines': ['T', 'B', 'L', 'R']}, {'winner': 'A', 'lines': ['T', 'B',",
"+= 1 return scores board = ''' *** *** ***",
"0}): self.to_move = to_move self.board = board self.label = label",
"in board[row][col]['lines']: continue complete = False if complete: board[row][col]['winner'] =",
"player == 'V': return 'H' return None def result(self, state,",
"= [] while not moves.empty(): moveList.append(moves.get(1)) return moveList def applyMove(board,",
"choose1 = GameState( to_move='H', position=(1, 0), board=[[3, 8, 9, 5],",
"col in range(0, len(board[row])): board_string += '*' if 'T' in",
"board=[[{'winner': '', 'lines': []}, {'winner': '', 'lines': []}], [{'winner': '',",
"not moves.empty(): moveList.append(moves.get(1)) return moveList def applyMove(board, size, row, col,",
"size - 1 and side == 'R': board[row][col + 1]['lines'].append('L')",
"'B', 'L', 'R'] complete = True for side in sides:",
"== 0 def display(self, state): # print_table(state.board, njust='center', sep=',') printDotsBoard(state.board)",
"'L': board[row][col - 1]['lines'].append('R') if col >= 0 and col",
"' + str(state.scores)) ''' Board represents the squares, whether the",
"newState.board[r][c] = nan newState.scores[currMover] += v return newState def utility(self,",
"1), board=[[nan, nan], [9, nan]], label='won' ) won.scores = {'H':",
"1, 3]], label='winby10' ) thinkA = ThinkAhead(stolen) def availableMoves(board): sides",
"board_string += ' ' if '' != board[row][space]['winner']: board_string +=",
"and which player owns the square. ''' dotLineBoard = [[{'winner':",
"'' != board[row][space]['winner']: board_string += board[row][space]['winner'] else: board_string += '",
"left, and right have been filled, and which player owns",
"= label self.scores = scores def __str__(self): if self.label is",
"'B', 'L', 'R']}], [{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']},",
"newState.scores[currMover] += v return newState def utility(self, state, player): \"Player",
"DotLineState( board=[[{'winner': '', 'lines': []}, {'winner': '', 'lines': []}], [{'winner':",
"0} lost = GameState( to_move='V', position=(0, 1), board=[[nan, nan], [9,",
"thinkA = ThinkAhead(stolen) def availableMoves(board): sides = ['T', 'B', 'L',",
"== None: return super(GameState, self).__str__() return self.label class Move: def",
"# print_table(state.board, njust='center', sep=',') printDotsBoard(state.board) print('Score: ' + str(state.scores)) '''",
"' if col == len(board[row]) - 1: board_string += '*\\n'",
"= row[c] move = Move(r, c, v) mQueue.put(move) return q2list(mQueue)",
"An implementation of Dots and Lines \"\"\" def __init__(self, state):",
"'R']}, {'winner': '', 'lines': ['T', 'L']}, {'winner': '', 'lines': ['R']}],",
"def __str__(self): if self.label == None: return super(GameState, self).__str__() return",
"1][col]['lines'].append('T') if col <= size - 1 and col !=",
"move = Move(r, c, v) mQueue.put(move) return q2list(mQueue) def movesInCol(board,",
"size - 1 and col != 0 and side ==",
"= r self.col = c self.value = v def rcv(self):",
"c) return moves return [] # defines the order of",
"def utility(self, state, player): \"Player relative score\" opponent = self.opponent(player)",
"if col >= 0 and col != size - 1",
"= DotsAndLines(play) #dotLine = DotsAndLines(winIn5_3x3) myGames = { dotLine: [",
"== 0 def display(self, state): print_table(state.board, njust='center', sep=',') print('Score: '",
"0 def display(self, state): # print_table(state.board, njust='center', sep=',') printDotsBoard(state.board) print('Score:",
"len(board)): for col in range(0, len(board)): if board[row][col]['winner'] == '':",
"moves = movesInCol(state.board, c) return moves return [] # defines",
"return len(self.actions(state)) == 0 def display(self, state): # print_table(state.board, njust='center',",
"nan], [nan, 6, 4, 5], [nan, nan, 1, 3]], label='winby10'",
"0} def __str__(self): if self.label == None: return super(GameState, self).__str__()",
"[]}, {'winner': '', 'lines': []}], [{'winner': '', 'lines': []}, {'winner':",
"board[row][col]['winner'] == '': for side in sides: if side not",
"it is won or there are no empty squares.\" return",
"'B']}, {'winner': '', 'lines': ['B', 'R']}], ] winIn5_3x3 = DotLineState(board=dotLineBoard,",
"2, 'B': 2}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B',",
"if it is won or there are no empty squares.\"",
"row[c] move = Move(r, c, v) mQueue.put(move) return q2list(mQueue) def",
"nan], [9, nan]], label='won' ) won.scores = {'H': 9, 'V':",
"side, currMover) newState.scores = countScore(newState.board) return newState def utility(self, state,",
"nextMover newState.position = r, c newState.board[r][c] = nan newState.scores[currMover] +=",
"other.value def q2list(mq): list = [] while not mq.empty(): list.append(mq.get(1).rcv())",
"self.value > other.value def q2list(mq): list = [] while not",
"label='lost' ) lost.scores = {'H': 0, 'V': 9} winin1 =",
"0 and row != size - 1 and side ==",
"== 'V': return 'H' return None def result(self, state, move):",
"'R'] moves = PriorityQueue() for row in range(0, len(board)): for",
"squares, whether the top, bottom, left, and right have been",
"moves if state.to_move == 'V': moves = movesInCol(state.board, c) return",
"= False if complete: board[row][col]['winner'] = currMover return board def",
"represents the squares, whether the top, bottom, left, and right",
"'', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['L', 'R']}, {'winner':",
"'| ' else: board_string += ' ' if '' !=",
"taken.\" moves = availableMoves(state.board) return moves # defines the order",
"state, player): \"Player relative score\" opponent = self.opponent(player) return state.scores[player]",
"= DotLineState(board=dotLineBoard, to_move='A', label='Win in 5', scores={'A': 0, 'B': 0})",
"DotsAndLines(winIn5_3x3) myGames = { dotLine: [ won, lost, tied, winin1Dots,",
"list = [] while not mq.empty(): list.append(mq.get(1).rcv()) return list def",
"len(board)): for col in range(0, len(board)): if board[row][col]['winner'] == 'A':",
"'R']}], [{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B',",
"in range(len(board)): if isnan(board[r][c]): continue v = board[r][c] move =",
"and col != size - 1 and side == 'R':",
"' ' if space == len(board[row]) - 1 and 'R'",
"class DotsAndLines(Game): \"\"\" An implementation of Dots and Lines \"\"\"",
"1, 'B': 3}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B',",
"availableMoves(state.board) return moves # defines the order of play def",
"to_move='A', label='Start') #amended by whh dotLine = DotsAndLines(play) #dotLine =",
"'lines': ['T', 'B', 'L', 'R']}]] won = DotLineState(board=dotLineBoard, to_move='A', label='Won',",
"'A', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A', 'lines': ['T',",
"col in range(0, len(board)): if board[row][col]['winner'] == 'A': scores['A'] +=",
"len(state.board) def actions(self, state): \"Legal moves are any square not",
"scores['B'] += 1 return scores board = ''' *** ***",
"availableMoves(board): sides = ['T', 'B', 'L', 'R'] moves = PriorityQueue()",
"board[row][col]['lines']: continue complete = False if complete: board[row][col]['winner'] = currMover",
"continue v = board[r][c] move = Move(r, c, v) mQueue.put(move)",
"[9, nan]], label='losein1' ) winin2 = GameState( to_move='H', position=(0, 0),",
"= movesInCol(state.board, c) return moves return [] # defines the",
"== 'H': return 'V' if player == 'V': return 'H'",
"moveList def applyMove(board, size, row, col, side, currMover): board[row][col]['lines'].append(side) if",
"and row != size - 1 and side == 'B':",
"moves are any square not yet taken.\" moves = availableMoves(state.board)",
"'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] won =",
"printDotsBoard(board): board_string = '' for row in range(0, len(board)): for",
"\"\"\" def __init__(self, state): self.initial = state def actions(self, state):",
"position=(2, 0), board=[[nan, nan, nan, nan], [nan, nan, nan, nan],",
"and side == 'R': board[row][col + 1]['lines'].append('L') sides = ['T',",
"1][col]['lines'].append('B') if row >= 0 and row != size -",
"' ' if '' != board[row][space]['winner']: board_string += board[row][space]['winner'] else:",
"PriorityQueue() row = board[r] for c in range(len(row)): if isnan(row[c]):",
"= move currMover = state.to_move nextMover = self.opponent(currMover) newState =",
"def display(self, state): # print_table(state.board, njust='center', sep=',') printDotsBoard(state.board) print('Score: '",
"c, v = move assert state.board[r][c] == v currMover =",
"display(self, state): print_table(state.board, njust='center', sep=',') print('Score: ' + str(state.scores)) won",
"9, nan], [2, nan, 1]], label='losein2' ) losein2.maxDepth = 3",
"nan]], label='losein1' ) winin2 = GameState( to_move='H', position=(0, 0), board=[[nan,",
"1), board=[[3, 8, 9, 5], [9, 1, 3, 2], [8,",
"col >= 0 and col != size - 1 and",
"while not mq.empty(): list.append(mq.get(1).rcv()) return list def movesInRow(board, r): mQueue",
"board[row][space]['winner']: board_string += board[row][space]['winner'] else: board_string += ' ' if",
"['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L',",
"nan], [3, 9, nan], [2, nan, 1]], label='losein2' ) losein2.maxDepth",
"player owns the square. ''' dotLineBoard = [[{'winner': 'A', 'lines':",
"top, bottom, left, and right have been filled, and which",
"for row in range(0, len(board)): for col in range(0, len(board)):",
"complete = True for side in sides: if side in",
"def __init__(self, state): self.initial = state self.size = len(state.board) def",
"'B', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'B', 'lines': ['T',",
"'', 'lines': []}], [{'winner': '', 'lines': []}, {'winner': '', 'lines':",
"return state.scores[player] - state.scores[opponent] def terminal_test(self, state): \"A state is",
"= {'H': 0, 'V': 0} def __str__(self): if self.label ==",
"'B', 'lines': ['T', 'B', 'L', 'R']}]] lost = DotLineState(board=dotLineBoard, to_move='A',",
"board_string += '*' if 'B' in board[row][col]['lines']: board_string += '---'",
"+= 1 if board[row][col]['winner'] == 'B': scores['B'] += 1 return",
"state.to_move nextMover = self.opponent(currMover) newState = deepcopy(state) newState.to_move = nextMover",
"range(0, len(board)): for col in range(0, len(board)): if board[row][col]['winner'] ==",
"= ''' *** *** *** ''' def printDotsBoard(board): board_string =",
"'R']}, {'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['L',",
"'L', 'R']}, {'winner': '', 'lines': ['L', 'B']}, {'winner': '', 'lines':",
"= GameState( to_move='V', position=(0, 0), board=[[nan, nan, nan], [3, 9,",
"and row != 0 and side == 'T': board[row -",
"mQueue = PriorityQueue() row = board[r] for c in range(len(row)):",
"state self.size = len(state.board) def actions(self, state): \"Legal moves are",
"in board[row][col]['lines']: board_string += '---' else: board_string += ' '",
"= GameState( to_move='V', position=(0, 0), board=[[nan, nan], [9, nan]], label='losein1'",
"to_move='H', position=(1, 0), board=[[3, 8, 9, 5], [nan, 1, 3,",
"whether the top, bottom, left, and right have been filled,",
"scores={'A': 1, 'B': 3}) dotLineBoard = [[{'winner': 'A', 'lines': ['T',",
"'\\n' if row == len(board) - 1: for col in",
"1]['lines'].append('R') if col >= 0 and col != size -",
"' ' board_string += '\\n' if row == len(board) -",
"in 5', scores={'A': 0, 'B': 0}) play = DotLineState( board=[[{'winner':",
"1 and 'R' in board[row][space]['lines']: board_string += ' |' else:",
"from queue import PriorityQueue from copy import deepcopy from utils",
"mQueue = PriorityQueue() for r in range(len(board)): if isnan(board[r][c]): continue",
"from copy import deepcopy from utils import isnumber from grading.util",
"'B': 0}) play = DotLineState( board=[[{'winner': '', 'lines': []}, {'winner':",
"Move(r, c, v) mQueue.put(move) return q2list(mQueue) def movesInCol(board, c): mQueue",
"== 'B': board[row + 1][col]['lines'].append('T') if col <= size -",
"- 1 and side == 'R': board[row][col + 1]['lines'].append('L') sides",
"player): \"Player relative score\" opponent = self.opponent(player) return state.scores[player] -",
"label='choose1' ) winby10 = GameState( to_move='H', position=(2, 0), board=[[nan, nan,",
"complete = False if complete: board[row][col]['winner'] = currMover return board",
"== 'A': return 'B' if player == 'B': return 'A'",
"col, side, currMover) newState.scores = countScore(newState.board) return newState def utility(self,",
"{ dotLine: [ won, lost, tied, winin1Dots, winIn5_3x3, play ]",
"= state.to_move nextMover = self.opponent(currMover) newState = deepcopy(state) newState.to_move =",
"0, 'V': 0} def __str__(self): if self.label == None: return",
"Game from math import nan, isnan from queue import PriorityQueue",
"+ 1][col]['lines'].append('T') if col <= size - 1 and col",
"been filled, and which player owns the square. ''' dotLineBoard",
"self.opponent(currMover) newState = deepcopy(state) newState.to_move = nextMover newState.board = applyMove(newState.board,",
"in range(0, len(board[row])): if 'L' in board[row][space]['lines']: board_string += '|",
"v) mQueue.put(move) return q2list(mQueue) class ThinkAhead(Game): \"\"\" An implementation of",
"newState = deepcopy(state) newState.to_move = nextMover newState.position = r, c",
"c, v) mQueue.put(move) return q2list(mQueue) class ThinkAhead(Game): \"\"\" An implementation",
"moveList = [] while not moves.empty(): moveList.append(moves.get(1)) return moveList def",
"if player == 'A': return 'B' if player == 'B':",
"'L', 'R'] complete = True for side in sides: if",
"self.board = board self.label = label self.scores = {'H': 0,",
"of ThinkAhead \"\"\" def __init__(self, state): self.initial = state def",
"c newState.board[r][c] = nan newState.scores[currMover] += v return newState def",
"which player owns the square. ''' dotLineBoard = [[{'winner': 'A',",
"board=[[nan, nan, nan, nan], [nan, nan, nan, nan], [nan, 6,",
"{'winner': '', 'lines': ['L', 'B']}, {'winner': '', 'lines': ['B', 'R']}],",
"'': for side in sides: if side not in board[row][col]['lines']:",
"lost = DotLineState(board=dotLineBoard, to_move='A', label='Lost', scores={'A': 1, 'B': 3}) dotLineBoard",
"= DotLineState( board=[[{'winner': '', 'lines': []}, {'winner': '', 'lines': []}],",
"nextMover newState.board = applyMove(newState.board, self.size, row, col, side, currMover) newState.scores",
"board self.label = label self.scores = scores def __str__(self): if",
"8, 9, 5], [9, 1, 3, 2], [8, 6, 4,",
"'B': return 'A' return None def result(self, state, move): row,",
"'B', 'L', 'R']}]] tied = DotLineState(board=dotLineBoard, to_move='A', label='Tied', scores={'A': 2,",
"['L', 'R']}, {'winner': '', 'lines': ['T', 'L']}, {'winner': '', 'lines':",
"'R' in board[row][space]['lines']: board_string += ' |' else: board_string +=",
"+ str(state.scores)) ''' Board represents the squares, whether the top,",
"njust='center', sep=',') print('Score: ' + str(state.scores)) won = GameState( to_move='H',",
"the top, bottom, left, and right have been filled, and",
"[nan, 6, 4, 5], [nan, nan, 1, 3]], label='winby10' )",
"''' Board represents the squares, whether the top, bottom, left,",
"{'winner': '', 'lines': []}]], to_move='A', label='Start') #amended by whh dotLine",
"'lines': ['L', 'R']}, {'winner': '', 'lines': ['T', 'L']}, {'winner': '',",
"self.row, self.col, self.value def __lt__(self, other): return self.value > other.value",
"' ' board_string += '*' print(board_string) class DotLineState: def __init__(self,",
"label='stolen' ) choose1 = GameState( to_move='H', position=(1, 0), board=[[3, 8,",
"+= '---' else: board_string += ' ' if col ==",
"= nan newState.scores[currMover] += v return newState def utility(self, state,",
"return 'V' if player == 'V': return 'H' return None",
"= deepcopy(state) newState.to_move = nextMover newState.board = applyMove(newState.board, self.size, row,",
"board=[[nan, nan], [9, nan]], label='lost' ) lost.scores = {'H': 0,",
"= GameState( to_move='H', position=(3, 1), board=[[3, 8, 9, 5], [9,",
"grading.util import print_table class GameState: def __init__(self, to_move, position, board,",
"DotLineState(board=dotLineBoard, to_move='A', label='Won', scores={'A': 3, 'B': 1}) dotLineBoard = [[{'winner':",
"!= board[row][space]['winner']: board_string += board[row][space]['winner'] else: board_string += ' '",
"moveList.append(moves.get(1)) return moveList def applyMove(board, size, row, col, side, currMover):",
"DotsAndLines(play) #dotLine = DotsAndLines(winIn5_3x3) myGames = { dotLine: [ won,",
"1 and row != 0 and side == 'T': board[row",
"row, col, side = move currMover = state.to_move nextMover =",
") losein2 = GameState( to_move='V', position=(0, 0), board=[[nan, nan, nan],",
"5]], label='choose1' ) winby10 = GameState( to_move='H', position=(2, 0), board=[[nan,",
"bottom, left, and right have been filled, and which player",
"'R']}, {'winner': '', 'lines': ['L', 'B']}, {'winner': '', 'lines': ['B',",
"nan, nan, nan], [nan, nan, nan, nan], [nan, 6, 4,",
"myGames = { dotLine: [ won, lost, tied, winin1Dots, winIn5_3x3,",
"GameState( to_move='V', position=(0, 0), board=[[nan, nan], [9, nan]], label='losein1' )",
"currMover return board def countScore(board): scores = {'A': 0, 'B':",
"4], [nan, nan, 1, 5]], label='choose1' ) winby10 = GameState(",
"label='Tied', scores={'A': 2, 'B': 2}) dotLineBoard = [[{'winner': 'A', 'lines':",
"__init__(self, to_move, position, board, label=None): self.to_move = to_move self.position =",
"__init__(self, r, c, v): self.row = r self.col = c",
"currMover): board[row][col]['lines'].append(side) if row <= size - 1 and row",
"'T' in board[row][col]['lines']: board_string += '---' else: board_string += '",
"GameState( to_move='H', position=(0, 0), board=[[nan, 3, 2], [nan, 9, nan],",
"= DotLineState(board=dotLineBoard, to_move='A', label='Tied', scores={'A': 2, 'B': 2}) dotLineBoard =",
"if isnan(row[c]): continue v = row[c] move = Move(r, c,",
"2}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']},",
"board_string += ' ' board_string += '*' print(board_string) class DotLineState:",
"side = move currMover = state.to_move nextMover = self.opponent(currMover) newState",
"utils import isnumber from grading.util import print_table class GameState: def",
"' |' else: board_string += ' ' board_string += '\\n'",
"terminal if it is won or there are no empty",
"board[row - 1][col]['lines'].append('B') if row >= 0 and row !=",
"self.board = board self.label = label self.scores = scores def",
"def __init__(self, to_move, board, label=None, scores={'A': 0, 'B': 0}): self.to_move",
"col, side = move currMover = state.to_move nextMover = self.opponent(currMover)",
"- 1: for col in range(0, len(board[row])): board_string += '*'",
"col != 0 and side == 'L': board[row][col - 1]['lines'].append('R')",
"for col in range(0, len(board)): if board[row][col]['winner'] == '': for",
"there are no empty squares.\" return len(self.actions(state)) == 0 def",
"PriorityQueue from copy import deepcopy from utils import isnumber from",
"1, 5]], label='stolen' ) choose1 = GameState( to_move='H', position=(1, 0),",
"DotsAndLines(Game): \"\"\" An implementation of Dots and Lines \"\"\" def",
"'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] tied",
"1]['lines'].append('L') sides = ['T', 'B', 'L', 'R'] complete = True",
"losein1 = GameState( to_move='V', position=(0, 0), board=[[nan, nan], [9, nan]],",
"['T', 'B', 'L', 'R']}, {'winner': 'A', 'lines': ['T', 'B', 'L',",
"whh dotLine = DotsAndLines(play) #dotLine = DotsAndLines(winIn5_3x3) myGames = {",
"filled, and which player owns the square. ''' dotLineBoard =",
"are any square not yet taken.\" r, c = state.position",
"state): # print_table(state.board, njust='center', sep=',') printDotsBoard(state.board) print('Score: ' + str(state.scores))",
"= position self.board = board self.label = label self.scores =",
"c, v) mQueue.put(move) return q2list(mQueue) def movesInCol(board, c): mQueue =",
"len(self.actions(state)) == 0 def display(self, state): # print_table(state.board, njust='center', sep=',')",
"'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A', 'lines': ['T', 'B',",
"sides = ['T', 'B', 'L', 'R'] moves = PriorityQueue() for",
"label='losein2' ) losein2.maxDepth = 3 # http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen = GameState(",
"= GameState( to_move='V', position=(0, 1), board=[[nan, nan], [9, nan]], label='lost'",
"9} winin1 = GameState( to_move='H', position=(1, 1), board=[[nan, nan], [9,",
"self.col, self.value def __lt__(self, other): return self.value > other.value def",
"return moves return [] # defines the order of play",
"- 1 and 'R' in board[row][space]['lines']: board_string += ' |'",
"DotLineState(board=dotLineBoard, to_move='A', label='Tied', scores={'A': 2, 'B': 2}) dotLineBoard = [[{'winner':",
"to_move, board, label=None, scores={'A': 0, 'B': 0}): self.to_move = to_move",
"return 'A' return None def result(self, state, move): row, col,",
"\"\"\" An implementation of Dots and Lines \"\"\" def __init__(self,",
"range(0, len(board[row])): board_string += '*' if 'B' in board[row][col]['lines']: board_string",
"'---' else: board_string += ' ' board_string += '*' print(board_string)",
"sides: if side in board[row][col]['lines']: continue complete = False if",
"= board[r] for c in range(len(row)): if isnan(row[c]): continue v",
"'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}], [{'winner':",
"range(len(board)): if isnan(board[r][c]): continue v = board[r][c] move = Move(r,",
"GameState( to_move='H', position=(1, 1), board=[[nan, nan], [9, nan]], label='winin1' )",
"[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': '', 'lines':",
"is terminal if it is won or there are no",
"won.scores = {'H': 9, 'V': 0} lost = GameState( to_move='V',",
"board=[[3, 8, 9, 5], [9, 1, 3, 2], [8, 6,",
"'R']}, {'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A',",
"import Game from math import nan, isnan from queue import",
"board=[[nan, nan], [9, nan]], label='losein1' ) winin2 = GameState( to_move='H',",
"and col != 0 and side == 'L': board[row][col -",
"'lines': []}]], to_move='A', label='Start') #amended by whh dotLine = DotsAndLines(play)",
"An implementation of ThinkAhead \"\"\" def __init__(self, state): self.initial =",
"\"Player relative score\" opponent = self.opponent(player) return state.scores[player] - state.scores[opponent]",
"isnan(row[c]): continue v = row[c] move = Move(r, c, v)",
"board_string += '*' if 'T' in board[row][col]['lines']: board_string += '---'",
"5', scores={'A': 0, 'B': 0}) play = DotLineState( board=[[{'winner': '',",
"r, c = state.position if state.to_move == 'H': moves =",
"= to_move self.board = board self.label = label self.scores =",
"return moveList def applyMove(board, size, row, col, side, currMover): board[row][col]['lines'].append(side)",
"winin1Dots = DotLineState(board=dotLineBoard, to_move='A', label='Win in 1', scores={'A': 2, 'B':",
"from games import Game from math import nan, isnan from",
"board[row][col]['winner'] == 'B': scores['B'] += 1 return scores board =",
"- 1: board_string += '*\\n' for space in range(0, len(board[row])):",
"square. ''' dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L',",
"{'H': 9, 'V': 0} lost = GameState( to_move='V', position=(0, 1),",
"== '': for side in sides: if side not in",
"{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A', 'lines':",
"= GameState( to_move='H', position=(2, 0), board=[[nan, nan, nan, nan], [nan,",
"self.position = position self.board = board self.label = label self.scores",
"scores={'A': 0, 'B': 0}) play = DotLineState( board=[[{'winner': '', 'lines':",
"'H' return None def result(self, state, move): r, c, v",
"'B' in board[row][col]['lines']: board_string += '---' else: board_string += '",
"= Move(r, c, v) mQueue.put(move) return q2list(mQueue) def movesInCol(board, c):",
"board[row][col]['lines']: moves.put((row, col, side)) moveList = [] while not moves.empty():",
"# http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen = GameState( to_move='H', position=(3, 1), board=[[3, 8,",
"'B', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A', 'lines': ['T',",
"queue import PriorityQueue from copy import deepcopy from utils import",
"q2list(mq): list = [] while not mq.empty(): list.append(mq.get(1).rcv()) return list",
"order of play def opponent(self, player): if player == 'H':",
"nan], [9, nan]], label='winin1' ) losein1 = GameState( to_move='V', position=(0,",
"print('Score: ' + str(state.scores)) won = GameState( to_move='H', position=(0, 1),",
"board_string = '' for row in range(0, len(board)): for col",
"of Dots and Lines \"\"\" def __init__(self, state): self.initial =",
"square not yet taken.\" moves = availableMoves(state.board) return moves #",
"self.row = r self.col = c self.value = v def",
"complete: board[row][col]['winner'] = currMover return board def countScore(board): scores =",
"to_move='A', label='Won', scores={'A': 3, 'B': 1}) dotLineBoard = [[{'winner': 'A',",
"winIn5_3x3 = DotLineState(board=dotLineBoard, to_move='A', label='Win in 5', scores={'A': 0, 'B':",
"[]}]], to_move='A', label='Start') #amended by whh dotLine = DotsAndLines(play) #dotLine",
"= ['T', 'B', 'L', 'R'] complete = True for side",
"'', 'lines': []}, {'winner': '', 'lines': []}]], to_move='A', label='Start') #amended",
"print_table(state.board, njust='center', sep=',') print('Score: ' + str(state.scores)) won = GameState(",
"+= '| ' else: board_string += ' ' if ''",
"def __str__(self): if self.label is None: return super(DotLineState, self).__str__() return",
"winin1 = GameState( to_move='H', position=(1, 1), board=[[nan, nan], [9, nan]],",
"4, 4], [nan, nan, 1, 5]], label='choose1' ) winby10 =",
"= ['T', 'B', 'L', 'R'] moves = PriorityQueue() for row",
"side == 'T': board[row - 1][col]['lines'].append('B') if row >= 0",
"import print_table class GameState: def __init__(self, to_move, position, board, label=None):",
"1 and col != 0 and side == 'L': board[row][col",
"['T', 'L']}, {'winner': '', 'lines': ['R']}], [{'winner': '', 'lines': ['L',",
"is won or there are no empty squares.\" return len(self.actions(state))",
"newState.board = applyMove(newState.board, self.size, row, col, side, currMover) newState.scores =",
"{'winner': '', 'lines': ['R']}], [{'winner': '', 'lines': ['L', 'R']}, {'winner':",
"'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': '', 'lines': ['T',",
"row == len(board) - 1: for col in range(0, len(board[row])):",
"<= size - 1 and row != 0 and side",
"if state.to_move == 'V': moves = movesInCol(state.board, c) return moves",
"board=[[3, 8, 9, 5], [nan, 1, 3, 2], [8, 6,",
"to_move='H', position=(2, 0), board=[[nan, nan, nan, nan], [nan, nan, nan,",
"'lines': ['R']}], [{'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines':",
"return self.value > other.value def q2list(mq): list = [] while",
"board[row][col + 1]['lines'].append('L') sides = ['T', 'B', 'L', 'R'] complete",
"board self.label = label self.scores = {'H': 0, 'V': 0}",
"[{'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['L', 'R']},",
"state.scores[player] - state.scores[opponent] def terminal_test(self, state): \"A state is terminal",
"1 if board[row][col]['winner'] == 'B': scores['B'] += 1 return scores",
"position=(0, 0), board=[[nan, nan, nan], [3, 9, nan], [2, nan,",
"return super(DotLineState, self).__str__() return self.label class DotsAndLines(Game): \"\"\" An implementation",
"'A': scores['A'] += 1 if board[row][col]['winner'] == 'B': scores['B'] +=",
"result(self, state, move): r, c, v = move assert state.board[r][c]",
") lost.scores = {'H': 0, 'V': 9} winin1 = GameState(",
"[9, nan]], label='lost' ) lost.scores = {'H': 0, 'V': 9}",
"space == len(board[row]) - 1 and 'R' in board[row][space]['lines']: board_string",
"if '' != board[row][space]['winner']: board_string += board[row][space]['winner'] else: board_string +=",
"label self.scores = scores def __str__(self): if self.label is None:",
"mQueue.put(move) return q2list(mQueue) class ThinkAhead(Game): \"\"\" An implementation of ThinkAhead",
"implementation of Dots and Lines \"\"\" def __init__(self, state): self.initial",
"*** ''' def printDotsBoard(board): board_string = '' for row in",
"board_string += '---' else: board_string += ' ' board_string +=",
"empty squares.\" return len(self.actions(state)) == 0 def display(self, state): #",
"else: board_string += ' ' board_string += '\\n' if row",
"4, 4], [9, nan, 1, 5]], label='stolen' ) choose1 =",
"state.to_move == 'V': moves = movesInCol(state.board, c) return moves return",
") thinkA = ThinkAhead(stolen) def availableMoves(board): sides = ['T', 'B',",
"None: return super(DotLineState, self).__str__() return self.label class DotsAndLines(Game): \"\"\" An",
"def terminal_test(self, state): \"A state is terminal if it is",
"= '' for row in range(0, len(board)): for col in",
"return moves # defines the order of play def opponent(self,",
"label='Lost', scores={'A': 1, 'B': 3}) dotLineBoard = [[{'winner': 'A', 'lines':",
"'B', 'lines': ['T', 'B', 'L', 'R']}]] tied = DotLineState(board=dotLineBoard, to_move='A',",
"to_move, position, board, label=None): self.to_move = to_move self.position = position",
"= True for side in sides: if side in board[row][col]['lines']:",
"1: for col in range(0, len(board[row])): board_string += '*' if",
"= nextMover newState.position = r, c newState.board[r][c] = nan newState.scores[currMover]",
"row >= 0 and row != size - 1 and",
"board def countScore(board): scores = {'A': 0, 'B': 0} for",
"'R': board[row][col + 1]['lines'].append('L') sides = ['T', 'B', 'L', 'R']",
"== 'L': board[row][col - 1]['lines'].append('R') if col >= 0 and",
"'*\\n' for space in range(0, len(board[row])): if 'L' in board[row][space]['lines']:",
"def rcv(self): return self.row, self.col, self.value def __lt__(self, other): return",
"return 'H' return None def result(self, state, move): r, c,",
"{'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['L', 'R']}],",
"= movesInRow(state.board, r) return moves if state.to_move == 'V': moves",
"state is terminal if it is won or there are",
"are no empty squares.\" return len(self.actions(state)) == 0 def display(self,",
"'lines': []}, {'winner': '', 'lines': []}]], to_move='A', label='Start') #amended by",
"for row in range(0, len(board)): for col in range(0, len(board[row])):",
"= {'H': 9, 'V': 0} lost = GameState( to_move='V', position=(0,",
"row <= size - 1 and row != 0 and",
"== 'V': moves = movesInCol(state.board, c) return moves return []",
"[9, nan]], label='winin1' ) losein1 = GameState( to_move='V', position=(0, 0),",
"'B': 3}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L',",
"in range(0, len(board[row])): board_string += '*' if 'B' in board[row][col]['lines']:",
"scores = {'A': 0, 'B': 0} for row in range(0,",
"col == len(board[row]) - 1: board_string += '*\\n' for space",
"'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B',",
"row != 0 and side == 'T': board[row - 1][col]['lines'].append('B')",
"range(0, len(board)): if board[row][col]['winner'] == 'A': scores['A'] += 1 if",
"['T', 'B', 'L', 'R'] moves = PriorityQueue() for row in",
"applyMove(newState.board, self.size, row, col, side, currMover) newState.scores = countScore(newState.board) return",
"label=None): self.to_move = to_move self.position = position self.board = board",
"+= ' ' board_string += '*' print(board_string) class DotLineState: def",
"'lines': []}, {'winner': '', 'lines': []}], [{'winner': '', 'lines': []},",
"label self.scores = {'H': 0, 'V': 0} def __str__(self): if",
"move = Move(r, c, v) mQueue.put(move) return q2list(mQueue) class ThinkAhead(Game):",
"return list def movesInRow(board, r): mQueue = PriorityQueue() row =",
"countScore(board): scores = {'A': 0, 'B': 0} for row in",
"side in sides: if side not in board[row][col]['lines']: moves.put((row, col,",
"+= ' ' if col == len(board[row]) - 1: board_string",
"Move: def __init__(self, r, c, v): self.row = r self.col",
"range(0, len(board[row])): board_string += '*' if 'T' in board[row][col]['lines']: board_string",
"dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner':",
"[nan, nan, 1, 3]], label='winby10' ) thinkA = ThinkAhead(stolen) def",
"'R']}]] tied = DotLineState(board=dotLineBoard, to_move='A', label='Tied', scores={'A': 2, 'B': 2})",
"position=(1, 0), board=[[3, 8, 9, 5], [nan, 1, 3, 2],",
"= {'H': 0, 'V': 9} winin1 = GameState( to_move='H', position=(1,",
"0), board=[[nan, nan], [9, nan]], label='losein1' ) winin2 = GameState(",
"Dots and Lines \"\"\" def __init__(self, state): self.initial = state",
"'L', 'R'] moves = PriorityQueue() for row in range(0, len(board)):",
"def availableMoves(board): sides = ['T', 'B', 'L', 'R'] moves =",
"the order of play def opponent(self, player): if player ==",
"and side == 'T': board[row - 1][col]['lines'].append('B') if row >=",
"{'A': 0, 'B': 0} for row in range(0, len(board)): for",
"board[row][col]['lines']: board_string += '---' else: board_string += ' ' board_string",
"{'winner': '', 'lines': ['B', 'R']}], ] winIn5_3x3 = DotLineState(board=dotLineBoard, to_move='A',",
"1, 5]], label='choose1' ) winby10 = GameState( to_move='H', position=(2, 0),",
"import nan, isnan from queue import PriorityQueue from copy import",
") losein1 = GameState( to_move='V', position=(0, 0), board=[[nan, nan], [9,",
"'lines': ['T', 'L']}]] winin1Dots = DotLineState(board=dotLineBoard, to_move='A', label='Win in 1',",
"self.initial = state def actions(self, state): \"Legal moves are any",
"def countScore(board): scores = {'A': 0, 'B': 0} for row",
"- 1][col]['lines'].append('B') if row >= 0 and row != size",
"' board_string += '\\n' if row == len(board) - 1:",
"+= '---' else: board_string += ' ' board_string += '*'",
"'L', 'R']}], [{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}, {'winner':",
"' + str(state.scores)) won = GameState( to_move='H', position=(0, 1), board=[[nan,",
"self.label == None: return super(GameState, self).__str__() return self.label class Move:",
"0), board=[[nan, nan, nan], [3, 9, nan], [2, nan, 1]],",
"in sides: if side not in board[row][col]['lines']: moves.put((row, col, side))",
"= label self.scores = {'H': 0, 'V': 0} def __str__(self):",
"0 def display(self, state): print_table(state.board, njust='center', sep=',') print('Score: ' +",
"moves are any square not yet taken.\" r, c =",
"if player == 'H': return 'V' if player == 'V':",
"lost = GameState( to_move='V', position=(0, 1), board=[[nan, nan], [9, nan]],",
"and side == 'L': board[row][col - 1]['lines'].append('R') if col >=",
"board_string += board[row][space]['winner'] else: board_string += ' ' if space",
"\"Legal moves are any square not yet taken.\" r, c",
"moves return [] # defines the order of play def",
"nan, 1, 3]], label='winby10' ) thinkA = ThinkAhead(stolen) def availableMoves(board):",
"if board[row][col]['winner'] == 'B': scores['B'] += 1 return scores board",
"for col in range(0, len(board[row])): board_string += '*' if 'B'",
"'A': return 'B' if player == 'B': return 'A' return",
"def result(self, state, move): row, col, side = move currMover",
"'B', 'L', 'R']}], [{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']},",
"'L']}]] winin1Dots = DotLineState(board=dotLineBoard, to_move='A', label='Win in 1', scores={'A': 2,",
"'*' print(board_string) class DotLineState: def __init__(self, to_move, board, label=None, scores={'A':",
"'', 'lines': ['T', 'L']}]] winin1Dots = DotLineState(board=dotLineBoard, to_move='A', label='Win in",
"board=[[nan, nan], [9, nan]], label='winin1' ) losein1 = GameState( to_move='V',",
"size, row, col, side, currMover): board[row][col]['lines'].append(side) if row <= size",
"'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] won",
"in board[row][space]['lines']: board_string += ' |' else: board_string += '",
"GameState( to_move='H', position=(0, 1), board=[[nan, nan], [9, nan]], label='won' )",
"== 'B': scores['B'] += 1 return scores board = '''",
"!= 0 and side == 'L': board[row][col - 1]['lines'].append('R') if",
"= ThinkAhead(stolen) def availableMoves(board): sides = ['T', 'B', 'L', 'R']",
"side == 'R': board[row][col + 1]['lines'].append('L') sides = ['T', 'B',",
"== 'R': board[row][col + 1]['lines'].append('L') sides = ['T', 'B', 'L',",
"deepcopy(state) newState.to_move = nextMover newState.position = r, c newState.board[r][c] =",
"= c self.value = v def rcv(self): return self.row, self.col,",
"nan, nan, nan], [nan, 6, 4, 5], [nan, nan, 1,",
"[8, 6, 4, 4], [nan, nan, 1, 5]], label='choose1' )",
"nan, isnan from queue import PriorityQueue from copy import deepcopy",
"position=(0, 0), board=[[nan, nan], [9, nan]], label='losein1' ) winin2 =",
"[nan, nan, nan, nan], [nan, 6, 4, 5], [nan, nan,",
"return len(self.actions(state)) == 0 def display(self, state): print_table(state.board, njust='center', sep=',')",
"math import nan, isnan from queue import PriorityQueue from copy",
"nan, nan], [nan, 6, 4, 5], [nan, nan, 1, 3]],",
"return 'B' if player == 'B': return 'A' return None",
"self.value def __lt__(self, other): return self.value > other.value def q2list(mq):",
"Board represents the squares, whether the top, bottom, left, and",
"label='Win in 1', scores={'A': 2, 'B': 1}) dotLineBoard = [[{'winner':",
"'R']}], ] winIn5_3x3 = DotLineState(board=dotLineBoard, to_move='A', label='Win in 5', scores={'A':",
"= self.opponent(player) return state.scores[player] - state.scores[opponent] def terminal_test(self, state): \"A",
"board = ''' *** *** *** ''' def printDotsBoard(board): board_string",
"is None: return super(DotLineState, self).__str__() return self.label class DotsAndLines(Game): \"\"\"",
"board_string += '*' print(board_string) class DotLineState: def __init__(self, to_move, board,",
"isnan from queue import PriorityQueue from copy import deepcopy from",
"== 'H': moves = movesInRow(state.board, r) return moves if state.to_move",
"and side == 'B': board[row + 1][col]['lines'].append('T') if col <=",
"if state.to_move == 'H': moves = movesInRow(state.board, r) return moves",
"return q2list(mQueue) def movesInCol(board, c): mQueue = PriorityQueue() for r",
"1), board=[[nan, nan], [9, nan]], label='lost' ) lost.scores = {'H':",
"[nan, nan, 1]], label='winin2' ) losein2 = GameState( to_move='V', position=(0,",
"side in sides: if side in board[row][col]['lines']: continue complete =",
"col in range(0, len(board[row])): board_string += '*' if 'B' in",
"currMover) newState.scores = countScore(newState.board) return newState def utility(self, state, player):",
"countScore(newState.board) return newState def utility(self, state, player): \"Player relative score\"",
"in board[row][space]['lines']: board_string += '| ' else: board_string += '",
"right have been filled, and which player owns the square.",
"or there are no empty squares.\" return len(self.actions(state)) == 0",
"if board[row][col]['winner'] == '': for side in sides: if side",
"'lines': ['T', 'B', 'L', 'R']}]] tied = DotLineState(board=dotLineBoard, to_move='A', label='Tied',",
"return moves if state.to_move == 'V': moves = movesInCol(state.board, c)",
"9, 5], [nan, 1, 3, 2], [8, 6, 4, 4],",
"0}) play = DotLineState( board=[[{'winner': '', 'lines': []}, {'winner': '',",
"score\" opponent = self.opponent(player) return state.scores[player] - state.scores[opponent] def terminal_test(self,",
"row in range(0, len(board)): for col in range(0, len(board)): if",
"'T': board[row - 1][col]['lines'].append('B') if row >= 0 and row",
"[]}, {'winner': '', 'lines': []}]], to_move='A', label='Start') #amended by whh",
"board[row][col]['lines']: board_string += '---' else: board_string += ' ' if",
"movesInRow(board, r): mQueue = PriorityQueue() row = board[r] for c",
"c): mQueue = PriorityQueue() for r in range(len(board)): if isnan(board[r][c]):",
"state.position if state.to_move == 'H': moves = movesInRow(state.board, r) return",
"v = row[c] move = Move(r, c, v) mQueue.put(move) return",
"range(0, len(board[row])): if 'L' in board[row][space]['lines']: board_string += '| '",
"label='Win in 5', scores={'A': 0, 'B': 0}) play = DotLineState(",
"if player == 'B': return 'A' return None def result(self,",
"if col == len(board[row]) - 1: board_string += '*\\n' for",
"board[row][col - 1]['lines'].append('R') if col >= 0 and col !=",
"*** *** *** ''' def printDotsBoard(board): board_string = '' for",
"!= 0 and side == 'T': board[row - 1][col]['lines'].append('B') if",
"= DotLineState(board=dotLineBoard, to_move='A', label='Won', scores={'A': 3, 'B': 1}) dotLineBoard =",
"row = board[r] for c in range(len(row)): if isnan(row[c]): continue",
"nan]], label='lost' ) lost.scores = {'H': 0, 'V': 9} winin1",
"5], [nan, nan, 1, 3]], label='winby10' ) thinkA = ThinkAhead(stolen)",
"board[row + 1][col]['lines'].append('T') if col <= size - 1 and",
"player == 'B': return 'A' return None def result(self, state,",
"dotLine = DotsAndLines(play) #dotLine = DotsAndLines(winIn5_3x3) myGames = { dotLine:",
"state def actions(self, state): \"Legal moves are any square not",
"board=[[nan, nan, nan], [3, 9, nan], [2, nan, 1]], label='losein2'",
"continue complete = False if complete: board[row][col]['winner'] = currMover return",
"GameState( to_move='H', position=(2, 0), board=[[nan, nan, nan, nan], [nan, nan,",
"str(state.scores)) ''' Board represents the squares, whether the top, bottom,",
"position self.board = board self.label = label self.scores = {'H':",
"nextMover = self.opponent(currMover) newState = deepcopy(state) newState.to_move = nextMover newState.position",
"to_move='H', position=(1, 1), board=[[nan, nan], [9, nan]], label='winin1' ) losein1",
"else: board_string += ' ' if space == len(board[row]) -",
"- 1 and side == 'B': board[row + 1][col]['lines'].append('T') if",
"in range(len(row)): if isnan(row[c]): continue v = row[c] move =",
"def printDotsBoard(board): board_string = '' for row in range(0, len(board)):",
"r, c, v): self.row = r self.col = c self.value",
"label='won' ) won.scores = {'H': 9, 'V': 0} lost =",
"isnan(board[r][c]): continue v = board[r][c] move = Move(r, c, v)",
"'B': board[row + 1][col]['lines'].append('T') if col <= size - 1",
"1]], label='winin2' ) losein2 = GameState( to_move='V', position=(0, 0), board=[[nan,",
"board_string += '\\n' if row == len(board) - 1: for",
"'V': 9} winin1 = GameState( to_move='H', position=(1, 1), board=[[nan, nan],",
"#amended by whh dotLine = DotsAndLines(play) #dotLine = DotsAndLines(winIn5_3x3) myGames",
"[3, 9, nan], [2, nan, 1]], label='losein2' ) losein2.maxDepth =",
"side == 'L': board[row][col - 1]['lines'].append('R') if col >= 0",
"from grading.util import print_table class GameState: def __init__(self, to_move, position,",
"self.size = len(state.board) def actions(self, state): \"Legal moves are any",
"winin2 = GameState( to_move='H', position=(0, 0), board=[[nan, 3, 2], [nan,",
"str(state.scores)) won = GameState( to_move='H', position=(0, 1), board=[[nan, nan], [9,",
"- 1]['lines'].append('R') if col >= 0 and col != size",
"4], [9, nan, 1, 5]], label='stolen' ) choose1 = GameState(",
"c in range(len(row)): if isnan(row[c]): continue v = row[c] move",
"board[row][space]['lines']: board_string += '| ' else: board_string += ' '",
"newState = deepcopy(state) newState.to_move = nextMover newState.board = applyMove(newState.board, self.size,",
"def applyMove(board, size, row, col, side, currMover): board[row][col]['lines'].append(side) if row",
"assert state.board[r][c] == v currMover = state.to_move nextMover = self.opponent(currMover)",
"' if '' != board[row][space]['winner']: board_string += board[row][space]['winner'] else: board_string",
"[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines':",
"range(0, len(board)): if board[row][col]['winner'] == '': for side in sides:",
"__init__(self, to_move, board, label=None, scores={'A': 0, 'B': 0}): self.to_move =",
"= [] while not mq.empty(): list.append(mq.get(1).rcv()) return list def movesInRow(board,",
"len(board)): if board[row][col]['winner'] == 'A': scores['A'] += 1 if board[row][col]['winner']",
"state): print_table(state.board, njust='center', sep=',') print('Score: ' + str(state.scores)) won =",
"return [] # defines the order of play def opponent(self,",
"= GameState( to_move='H', position=(0, 0), board=[[nan, 3, 2], [nan, 9,",
"self.scores = scores def __str__(self): if self.label is None: return",
"6, 4, 5], [nan, nan, 1, 3]], label='winby10' ) thinkA",
"== 'T': board[row - 1][col]['lines'].append('B') if row >= 0 and",
"{'H': 0, 'V': 9} winin1 = GameState( to_move='H', position=(1, 1),",
"not yet taken.\" r, c = state.position if state.to_move ==",
"list def movesInRow(board, r): mQueue = PriorityQueue() row = board[r]",
"3, 2], [8, 6, 4, 4], [nan, nan, 1, 5]],",
"row, col, side, currMover): board[row][col]['lines'].append(side) if row <= size -",
"c self.value = v def rcv(self): return self.row, self.col, self.value",
"nan, 1, 5]], label='choose1' ) winby10 = GameState( to_move='H', position=(2,",
"tied = DotLineState(board=dotLineBoard, to_move='A', label='Tied', scores={'A': 2, 'B': 2}) dotLineBoard",
"[[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'A', 'lines':",
"self).__str__() return self.label class DotsAndLines(Game): \"\"\" An implementation of Dots",
"'', 'lines': ['B', 'R']}], ] winIn5_3x3 = DotLineState(board=dotLineBoard, to_move='A', label='Win",
"= [[{'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['T',",
"def movesInRow(board, r): mQueue = PriorityQueue() row = board[r] for",
"self.opponent(player) return state.scores[player] - state.scores[opponent] def terminal_test(self, state): \"A state",
"in range(0, len(board)): if board[row][col]['winner'] == '': for side in",
"board[row][col]['lines'].append(side) if row <= size - 1 and row !=",
"position=(0, 1), board=[[nan, nan], [9, nan]], label='won' ) won.scores =",
"'R']}, {'winner': '', 'lines': ['T', 'L']}]] winin1Dots = DotLineState(board=dotLineBoard, to_move='A',",
"size - 1 and row != 0 and side ==",
"opponent = self.opponent(player) return state.scores[player] - state.scores[opponent] def terminal_test(self, state):",
"+= '\\n' if row == len(board) - 1: for col",
"label=None, scores={'A': 0, 'B': 0}): self.to_move = to_move self.board =",
"'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'B', 'lines': ['T', 'B',",
"= GameState( to_move='H', position=(0, 1), board=[[nan, nan], [9, nan]], label='won'",
"9, 'V': 0} lost = GameState( to_move='V', position=(0, 1), board=[[nan,",
"q2list(mQueue) class ThinkAhead(Game): \"\"\" An implementation of ThinkAhead \"\"\" def",
"\"\"\" An implementation of ThinkAhead \"\"\" def __init__(self, state): self.initial",
"relative score\" opponent = self.opponent(player) return state.scores[player] - state.scores[opponent] def",
"losein2.maxDepth = 3 # http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen = GameState( to_move='H', position=(3,",
"sep=',') printDotsBoard(state.board) print('Score: ' + str(state.scores)) ''' Board represents the",
"1 and side == 'R': board[row][col + 1]['lines'].append('L') sides =",
"['T', 'B', 'L', 'R']}]] won = DotLineState(board=dotLineBoard, to_move='A', label='Won', scores={'A':",
"#dotLine = DotsAndLines(winIn5_3x3) myGames = { dotLine: [ won, lost,",
"play = DotLineState( board=[[{'winner': '', 'lines': []}, {'winner': '', 'lines':",
"mq.empty(): list.append(mq.get(1).rcv()) return list def movesInRow(board, r): mQueue = PriorityQueue()",
"'---' else: board_string += ' ' if col == len(board[row])",
"r in range(len(board)): if isnan(board[r][c]): continue v = board[r][c] move",
"\"\"\" def __init__(self, state): self.initial = state self.size = len(state.board)",
"[[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines':",
"deepcopy(state) newState.to_move = nextMover newState.board = applyMove(newState.board, self.size, row, col,",
"{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A', 'lines':",
"state): \"Legal moves are any square not yet taken.\" r,",
"if 'T' in board[row][col]['lines']: board_string += '---' else: board_string +=",
"'lines': []}], [{'winner': '', 'lines': []}, {'winner': '', 'lines': []}]],",
"label='winin2' ) losein2 = GameState( to_move='V', position=(0, 0), board=[[nan, nan,",
"9, 5], [9, 1, 3, 2], [8, 6, 4, 4],",
"{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] lost = DotLineState(board=dotLineBoard,",
"actions(self, state): \"Legal moves are any square not yet taken.\"",
"= self.opponent(currMover) newState = deepcopy(state) newState.to_move = nextMover newState.position =",
"in 1', scores={'A': 2, 'B': 1}) dotLineBoard = [[{'winner': '',",
"[2, nan, 1]], label='losein2' ) losein2.maxDepth = 3 # http://www.kongregate.com/games/zolli/thinkahead-brain-trainer",
"{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] won = DotLineState(board=dotLineBoard,",
"state, move): row, col, side = move currMover = state.to_move",
"opponent(self, player): if player == 'A': return 'B' if player",
"nan]], label='winin1' ) losein1 = GameState( to_move='V', position=(0, 0), board=[[nan,",
"class ThinkAhead(Game): \"\"\" An implementation of ThinkAhead \"\"\" def __init__(self,",
"'', 'lines': []}, {'winner': '', 'lines': []}], [{'winner': '', 'lines':",
"play def opponent(self, player): if player == 'A': return 'B'",
") winby10 = GameState( to_move='H', position=(2, 0), board=[[nan, nan, nan,",
"board_string += ' ' if col == len(board[row]) - 1:",
"''' dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']},",
"'R']}], [{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': '',",
"sep=',') print('Score: ' + str(state.scores)) won = GameState( to_move='H', position=(0,",
"= [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B',",
"any square not yet taken.\" moves = availableMoves(state.board) return moves",
"1', scores={'A': 2, 'B': 1}) dotLineBoard = [[{'winner': '', 'lines':",
"njust='center', sep=',') printDotsBoard(state.board) print('Score: ' + str(state.scores)) ''' Board represents",
"to_move self.position = position self.board = board self.label = label",
"print_table class GameState: def __init__(self, to_move, position, board, label=None): self.to_move",
"= state def actions(self, state): \"Legal moves are any square",
"return None def result(self, state, move): row, col, side =",
"__lt__(self, other): return self.value > other.value def q2list(mq): list =",
"result(self, state, move): row, col, side = move currMover =",
"def opponent(self, player): if player == 'H': return 'V' if",
"move): r, c, v = move assert state.board[r][c] == v",
"= [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'A',",
"to_move='V', position=(0, 0), board=[[nan, nan], [9, nan]], label='losein1' ) winin2",
"'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'A', 'lines': ['T',",
"for side in sides: if side in board[row][col]['lines']: continue complete",
"to_move='A', label='Tied', scores={'A': 2, 'B': 2}) dotLineBoard = [[{'winner': 'A',",
"2, 'B': 1}) dotLineBoard = [[{'winner': '', 'lines': ['L', 'R']},",
"return scores board = ''' *** *** *** ''' def",
"len(board)): for col in range(0, len(board[row])): board_string += '*' if",
"state): self.initial = state self.size = len(state.board) def actions(self, state):",
"= v def rcv(self): return self.row, self.col, self.value def __lt__(self,",
"play def opponent(self, player): if player == 'H': return 'V'",
"moves = PriorityQueue() for row in range(0, len(board)): for col",
"[nan, nan, 1, 5]], label='choose1' ) winby10 = GameState( to_move='H',",
"if self.label is None: return super(DotLineState, self).__str__() return self.label class",
"self.label class Move: def __init__(self, r, c, v): self.row =",
"if isnan(board[r][c]): continue v = board[r][c] move = Move(r, c,",
"None def result(self, state, move): r, c, v = move",
"0 and side == 'T': board[row - 1][col]['lines'].append('B') if row",
"board_string += ' ' board_string += '\\n' if row ==",
"== len(board) - 1: for col in range(0, len(board[row])): board_string",
") choose1 = GameState( to_move='H', position=(1, 0), board=[[3, 8, 9,",
"label='Won', scores={'A': 3, 'B': 1}) dotLineBoard = [[{'winner': 'A', 'lines':",
"by whh dotLine = DotsAndLines(play) #dotLine = DotsAndLines(winIn5_3x3) myGames =",
"'lines': ['L', 'R']}], [{'winner': '', 'lines': ['B', 'L', 'R']}, {'winner':",
"rcv(self): return self.row, self.col, self.value def __lt__(self, other): return self.value",
"['T', 'B', 'L', 'R']}]] lost = DotLineState(board=dotLineBoard, to_move='A', label='Lost', scores={'A':",
"def __lt__(self, other): return self.value > other.value def q2list(mq): list",
"board, label=None): self.to_move = to_move self.position = position self.board =",
"movesInCol(state.board, c) return moves return [] # defines the order",
"have been filled, and which player owns the square. '''",
"'*' if 'B' in board[row][col]['lines']: board_string += '---' else: board_string",
"board=[[nan, 3, 2], [nan, 9, nan], [nan, nan, 1]], label='winin2'",
"[[{'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['T', 'L']},",
"return self.label class DotsAndLines(Game): \"\"\" An implementation of Dots and",
"losein2 = GameState( to_move='V', position=(0, 0), board=[[nan, nan, nan], [3,",
"empty squares.\" return len(self.actions(state)) == 0 def display(self, state): print_table(state.board,",
"'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] lost =",
"[9, 1, 3, 2], [8, 6, 4, 4], [9, nan,",
"= PriorityQueue() for r in range(len(board)): if isnan(board[r][c]): continue v",
"'', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['L', 'R']}], [{'winner':",
"return newState def utility(self, state, player): \"Player relative score\" opponent",
"- state.scores[opponent] def terminal_test(self, state): \"A state is terminal if",
"nextMover = self.opponent(currMover) newState = deepcopy(state) newState.to_move = nextMover newState.board",
"scores def __str__(self): if self.label is None: return super(DotLineState, self).__str__()",
"row, col, side, currMover) newState.scores = countScore(newState.board) return newState def",
"['R']}], [{'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines': ['L',",
"['L', 'B']}, {'winner': '', 'lines': ['B', 'R']}], ] winIn5_3x3 =",
"r) return moves if state.to_move == 'V': moves = movesInCol(state.board,",
"0), board=[[nan, 3, 2], [nan, 9, nan], [nan, nan, 1]],",
"stolen = GameState( to_move='H', position=(3, 1), board=[[3, 8, 9, 5],",
"6, 4, 4], [nan, nan, 1, 5]], label='choose1' ) winby10",
"if side in board[row][col]['lines']: continue complete = False if complete:",
"'B': 0}): self.to_move = to_move self.board = board self.label =",
"'B', 'L', 'R']}, {'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}],",
"[{'winner': '', 'lines': ['B', 'L', 'R']}, {'winner': '', 'lines': ['L',",
"nan], [nan, nan, 1]], label='winin2' ) losein2 = GameState( to_move='V',",
"to_move='V', position=(0, 1), board=[[nan, nan], [9, nan]], label='lost' ) lost.scores",
"nan], [9, nan]], label='losein1' ) winin2 = GameState( to_move='H', position=(0,",
"v = board[r][c] move = Move(r, c, v) mQueue.put(move) return",
"self.label = label self.scores = {'H': 0, 'V': 0} def",
"else: board_string += ' ' if '' != board[row][space]['winner']: board_string",
"= board[r][c] move = Move(r, c, v) mQueue.put(move) return q2list(mQueue)",
"square not yet taken.\" r, c = state.position if state.to_move",
"opponent(self, player): if player == 'H': return 'V' if player",
"from utils import isnumber from grading.util import print_table class GameState:",
"= deepcopy(state) newState.to_move = nextMover newState.position = r, c newState.board[r][c]",
"1), board=[[nan, nan], [9, nan]], label='winin1' ) losein1 = GameState(",
"5]], label='stolen' ) choose1 = GameState( to_move='H', position=(1, 0), board=[[3,",
"any square not yet taken.\" r, c = state.position if",
"8, 9, 5], [nan, 1, 3, 2], [8, 6, 4,",
"board_string += ' ' if space == len(board[row]) - 1",
"DotLineState: def __init__(self, to_move, board, label=None, scores={'A': 0, 'B': 0}):",
"newState.to_move = nextMover newState.board = applyMove(newState.board, self.size, row, col, side,",
"[9, nan]], label='won' ) won.scores = {'H': 9, 'V': 0}",
"['B', 'L', 'R']}, {'winner': '', 'lines': ['L', 'B']}, {'winner': '',",
"0, 'B': 0}) play = DotLineState( board=[[{'winner': '', 'lines': []},",
"ThinkAhead(Game): \"\"\" An implementation of ThinkAhead \"\"\" def __init__(self, state):",
"4, 5], [nan, nan, 1, 3]], label='winby10' ) thinkA =",
"'V' if player == 'V': return 'H' return None def",
"len(board)): if board[row][col]['winner'] == '': for side in sides: if",
"'H': moves = movesInRow(state.board, r) return moves if state.to_move ==",
"== 'B': return 'A' return None def result(self, state, move):",
"'', 'lines': ['T', 'L']}, {'winner': '', 'lines': ['R']}], [{'winner': '',",
"order of play def opponent(self, player): if player == 'A':",
"[{'winner': '', 'lines': []}, {'winner': '', 'lines': []}]], to_move='A', label='Start')",
"PriorityQueue() for r in range(len(board)): if isnan(board[r][c]): continue v =",
"display(self, state): # print_table(state.board, njust='center', sep=',') printDotsBoard(state.board) print('Score: ' +",
"state, move): r, c, v = move assert state.board[r][c] ==",
"else: board_string += ' ' if col == len(board[row]) -",
"won or there are no empty squares.\" return len(self.actions(state)) ==",
"other): return self.value > other.value def q2list(mq): list = []",
"while not moves.empty(): moveList.append(moves.get(1)) return moveList def applyMove(board, size, row,",
"import deepcopy from utils import isnumber from grading.util import print_table",
"<= size - 1 and col != 0 and side",
"['T', 'B', 'L', 'R'] complete = True for side in",
"to_move self.board = board self.label = label self.scores = scores",
"move): row, col, side = move currMover = state.to_move nextMover",
"for space in range(0, len(board[row])): if 'L' in board[row][space]['lines']: board_string",
"'' for row in range(0, len(board)): for col in range(0,",
"board_string += '---' else: board_string += ' ' if col",
"1}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']},",
") won.scores = {'H': 9, 'V': 0} lost = GameState(",
"'L', 'R']}, {'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}], [{'winner':",
"if space == len(board[row]) - 1 and 'R' in board[row][space]['lines']:",
"sides = ['T', 'B', 'L', 'R'] complete = True for",
"self.scores = {'H': 0, 'V': 0} def __str__(self): if self.label",
"False if complete: board[row][col]['winner'] = currMover return board def countScore(board):",
"'R']}], [{'winner': '', 'lines': ['B', 'L', 'R']}, {'winner': '', 'lines':",
"'L', 'R']}], [{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner':",
"class Move: def __init__(self, r, c, v): self.row = r",
"True for side in sides: if side in board[row][col]['lines']: continue",
"__str__(self): if self.label is None: return super(DotLineState, self).__str__() return self.label",
"moves.put((row, col, side)) moveList = [] while not moves.empty(): moveList.append(moves.get(1))",
"'B': 2}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L',",
"'lines': ['B', 'R']}], ] winIn5_3x3 = DotLineState(board=dotLineBoard, to_move='A', label='Win in",
"[] while not moves.empty(): moveList.append(moves.get(1)) return moveList def applyMove(board, size,",
"0 and side == 'L': board[row][col - 1]['lines'].append('R') if col",
"for r in range(len(board)): if isnan(board[r][c]): continue v = board[r][c]",
"for col in range(0, len(board)): if board[row][col]['winner'] == 'A': scores['A']",
"state.scores[opponent] def terminal_test(self, state): \"A state is terminal if it",
"= GameState( to_move='H', position=(1, 1), board=[[nan, nan], [9, nan]], label='winin1'",
"if row >= 0 and row != size - 1",
"self.to_move = to_move self.board = board self.label = label self.scores",
"self.initial = state self.size = len(state.board) def actions(self, state): \"Legal",
"= len(state.board) def actions(self, state): \"Legal moves are any square",
"'lines': ['T', 'B', 'L', 'R']}, {'winner': '', 'lines': ['T', 'L']}]]",
"\"A state is terminal if it is won or there",
"in range(0, len(board[row])): board_string += '*' if 'T' in board[row][col]['lines']:",
"mQueue.put(move) return q2list(mQueue) def movesInCol(board, c): mQueue = PriorityQueue() for",
"r, c newState.board[r][c] = nan newState.scores[currMover] += v return newState",
"+= ' ' if '' != board[row][space]['winner']: board_string += board[row][space]['winner']",
"board, label=None, scores={'A': 0, 'B': 0}): self.to_move = to_move self.board",
"= DotLineState(board=dotLineBoard, to_move='A', label='Lost', scores={'A': 1, 'B': 3}) dotLineBoard =",
"== len(board[row]) - 1 and 'R' in board[row][space]['lines']: board_string +=",
"state): \"A state is terminal if it is won or",
"0, 'B': 0}): self.to_move = to_move self.board = board self.label",
"['L', 'R']}], [{'winner': '', 'lines': ['B', 'L', 'R']}, {'winner': '',",
"board_string += '| ' else: board_string += ' ' if",
"newState.scores = countScore(newState.board) return newState def utility(self, state, player): \"Player",
"to_move='H', position=(0, 1), board=[[nan, nan], [9, nan]], label='won' ) won.scores",
"in range(0, len(board)): for col in range(0, len(board)): if board[row][col]['winner']",
"print('Score: ' + str(state.scores)) ''' Board represents the squares, whether",
"__init__(self, state): self.initial = state self.size = len(state.board) def actions(self,",
"are any square not yet taken.\" moves = availableMoves(state.board) return",
"'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'B',",
"return board def countScore(board): scores = {'A': 0, 'B': 0}",
"side not in board[row][col]['lines']: moves.put((row, col, side)) moveList = []",
"'L', 'R']}]] tied = DotLineState(board=dotLineBoard, to_move='A', label='Tied', scores={'A': 2, 'B':",
"= self.opponent(currMover) newState = deepcopy(state) newState.to_move = nextMover newState.board =",
"to_move='A', label='Win in 5', scores={'A': 0, 'B': 0}) play =",
"board_string += '*\\n' for space in range(0, len(board[row])): if 'L'",
"3}) dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B', 'L', 'R']},",
"the square. ''' dotLineBoard = [[{'winner': 'A', 'lines': ['T', 'B',",
"col <= size - 1 and col != 0 and",
"to_move='H', position=(3, 1), board=[[3, 8, 9, 5], [9, 1, 3,",
"\"Legal moves are any square not yet taken.\" moves =",
"super(DotLineState, self).__str__() return self.label class DotsAndLines(Game): \"\"\" An implementation of",
"'B', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T',",
"def display(self, state): print_table(state.board, njust='center', sep=',') print('Score: ' + str(state.scores))",
"owns the square. ''' dotLineBoard = [[{'winner': 'A', 'lines': ['T',",
"+= board[row][space]['winner'] else: board_string += ' ' if space ==",
"'B', 'L', 'R']}]] won = DotLineState(board=dotLineBoard, to_move='A', label='Won', scores={'A': 3,",
"isnumber from grading.util import print_table class GameState: def __init__(self, to_move,",
"{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] tied = DotLineState(board=dotLineBoard,",
"r, c, v = move assert state.board[r][c] == v currMover",
"6, 4, 4], [9, nan, 1, 5]], label='stolen' ) choose1",
"def actions(self, state): \"Legal moves are any square not yet",
"[] # defines the order of play def opponent(self, player):",
"board[r][c] move = Move(r, c, v) mQueue.put(move) return q2list(mQueue) class",
"ThinkAhead \"\"\" def __init__(self, state): self.initial = state def actions(self,",
"['T', 'B', 'L', 'R']}], [{'winner': 'A', 'lines': ['T', 'B', 'L',",
"'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'A',",
"list.append(mq.get(1).rcv()) return list def movesInRow(board, r): mQueue = PriorityQueue() row",
"if player == 'V': return 'H' return None def result(self,",
"'L' in board[row][space]['lines']: board_string += '| ' else: board_string +=",
"1, 3, 2], [8, 6, 4, 4], [nan, nan, 1,",
"http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen = GameState( to_move='H', position=(3, 1), board=[[3, 8, 9,",
"len(board[row])): board_string += '*' if 'T' in board[row][col]['lines']: board_string +=",
"def __init__(self, r, c, v): self.row = r self.col =",
"movesInCol(board, c): mQueue = PriorityQueue() for r in range(len(board)): if",
"= move assert state.board[r][c] == v currMover = state.to_move nextMover",
"position=(3, 1), board=[[3, 8, 9, 5], [9, 1, 3, 2],",
"nan], [nan, nan, nan, nan], [nan, 6, 4, 5], [nan,",
"{'winner': '', 'lines': []}], [{'winner': '', 'lines': []}, {'winner': '',",
"not in board[row][col]['lines']: moves.put((row, col, side)) moveList = [] while",
"applyMove(board, size, row, col, side, currMover): board[row][col]['lines'].append(side) if row <=",
"c, v): self.row = r self.col = c self.value =",
"terminal_test(self, state): \"A state is terminal if it is won",
"'L']}, {'winner': '', 'lines': ['R']}], [{'winner': '', 'lines': ['L', 'R']},",
"def result(self, state, move): r, c, v = move assert",
"to_move='A', label='Lost', scores={'A': 1, 'B': 3}) dotLineBoard = [[{'winner': 'A',",
"currMover = state.to_move nextMover = self.opponent(currMover) newState = deepcopy(state) newState.to_move",
"'lines': ['L', 'R']}, {'winner': '', 'lines': ['L', 'R']}], [{'winner': '',",
"v): self.row = r self.col = c self.value = v",
"not mq.empty(): list.append(mq.get(1).rcv()) return list def movesInRow(board, r): mQueue =",
"nan], [2, nan, 1]], label='losein2' ) losein2.maxDepth = 3 #",
"+= '*' print(board_string) class DotLineState: def __init__(self, to_move, board, label=None,",
"move currMover = state.to_move nextMover = self.opponent(currMover) newState = deepcopy(state)",
"['B', 'R']}], ] winIn5_3x3 = DotLineState(board=dotLineBoard, to_move='A', label='Win in 5',",
"for side in sides: if side not in board[row][col]['lines']: moves.put((row,",
"side in board[row][col]['lines']: continue complete = False if complete: board[row][col]['winner']",
"winby10 = GameState( to_move='H', position=(2, 0), board=[[nan, nan, nan, nan],",
"'', 'lines': ['B', 'L', 'R']}, {'winner': '', 'lines': ['L', 'B']},",
"3]], label='winby10' ) thinkA = ThinkAhead(stolen) def availableMoves(board): sides =",
"of play def opponent(self, player): if player == 'H': return",
"label='winby10' ) thinkA = ThinkAhead(stolen) def availableMoves(board): sides = ['T',",
"= PriorityQueue() row = board[r] for c in range(len(row)): if",
"'V': moves = movesInCol(state.board, c) return moves return [] #",
"scores board = ''' *** *** *** ''' def printDotsBoard(board):",
"printDotsBoard(state.board) print('Score: ' + str(state.scores)) ''' Board represents the squares,",
"- 1 and row != 0 and side == 'T':",
"+ 1]['lines'].append('L') sides = ['T', 'B', 'L', 'R'] complete =",
"no empty squares.\" return len(self.actions(state)) == 0 def display(self, state):",
"if row <= size - 1 and row != 0",
"board[row][col]['winner'] = currMover return board def countScore(board): scores = {'A':",
"def __init__(self, to_move, position, board, label=None): self.to_move = to_move self.position",
"continue v = row[c] move = Move(r, c, v) mQueue.put(move)",
") winin2 = GameState( to_move='H', position=(0, 0), board=[[nan, 3, 2],",
"col in range(0, len(board)): if board[row][col]['winner'] == '': for side",
"def q2list(mq): list = [] while not mq.empty(): list.append(mq.get(1).rcv()) return",
"print(board_string) class DotLineState: def __init__(self, to_move, board, label=None, scores={'A': 0,",
"None def result(self, state, move): row, col, side = move",
"['T', 'B', 'L', 'R']}, {'winner': '', 'lines': ['T', 'L']}]] winin1Dots",
"v def rcv(self): return self.row, self.col, self.value def __lt__(self, other):",
"else: board_string += ' ' board_string += '*' print(board_string) class",
"if side not in board[row][col]['lines']: moves.put((row, col, side)) moveList =",
"1 and side == 'B': board[row + 1][col]['lines'].append('T') if col",
"= availableMoves(state.board) return moves # defines the order of play",
"{'winner': '', 'lines': ['T', 'L']}]] winin1Dots = DotLineState(board=dotLineBoard, to_move='A', label='Win",
"[] while not mq.empty(): list.append(mq.get(1).rcv()) return list def movesInRow(board, r):",
"'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] tied =",
"state.board[r][c] == v currMover = state.to_move nextMover = self.opponent(currMover) newState",
"and Lines \"\"\" def __init__(self, state): self.initial = state self.size",
"self.value = v def rcv(self): return self.row, self.col, self.value def",
"return q2list(mQueue) class ThinkAhead(Game): \"\"\" An implementation of ThinkAhead \"\"\"",
"implementation of ThinkAhead \"\"\" def __init__(self, state): self.initial = state",
"return None def result(self, state, move): r, c, v =",
"scores={'A': 2, 'B': 2}) dotLineBoard = [[{'winner': 'A', 'lines': ['T',",
"newState.to_move = nextMover newState.position = r, c newState.board[r][c] = nan",
"'lines': ['L', 'R']}, {'winner': '', 'lines': ['L', 'R']}, {'winner': '',",
"'', 'lines': ['R']}], [{'winner': '', 'lines': ['L', 'R']}, {'winner': '',",
"['L', 'R']}, {'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines':",
"= Move(r, c, v) mQueue.put(move) return q2list(mQueue) class ThinkAhead(Game): \"\"\"",
"'', 'lines': ['L', 'B']}, {'winner': '', 'lines': ['B', 'R']}], ]",
"sides: if side not in board[row][col]['lines']: moves.put((row, col, side)) moveList",
"to_move='A', label='Win in 1', scores={'A': 2, 'B': 1}) dotLineBoard =",
"newState def utility(self, state, player): \"Player relative score\" opponent =",
"[nan, 9, nan], [nan, nan, 1]], label='winin2' ) losein2 =",
"= GameState( to_move='H', position=(1, 0), board=[[3, 8, 9, 5], [nan,",
"board[r] for c in range(len(row)): if isnan(row[c]): continue v =",
"0), board=[[nan, nan, nan, nan], [nan, nan, nan, nan], [nan,",
"to_move='V', position=(0, 0), board=[[nan, nan, nan], [3, 9, nan], [2,",
"'L', 'R']}]] lost = DotLineState(board=dotLineBoard, to_move='A', label='Lost', scores={'A': 1, 'B':",
"0), board=[[3, 8, 9, 5], [nan, 1, 3, 2], [8,",
"'R']}]] won = DotLineState(board=dotLineBoard, to_move='A', label='Won', scores={'A': 3, 'B': 1})",
"GameState: def __init__(self, to_move, position, board, label=None): self.to_move = to_move",
"] winIn5_3x3 = DotLineState(board=dotLineBoard, to_move='A', label='Win in 5', scores={'A': 0,",
"dotLineBoard = [[{'winner': '', 'lines': ['L', 'R']}, {'winner': '', 'lines':",
"def movesInCol(board, c): mQueue = PriorityQueue() for r in range(len(board)):",
"from math import nan, isnan from queue import PriorityQueue from",
"*** *** ''' def printDotsBoard(board): board_string = '' for row",
"nan, nan], [3, 9, nan], [2, nan, 1]], label='losein2' )",
"!= size - 1 and side == 'R': board[row][col +",
"GameState( to_move='H', position=(1, 0), board=[[3, 8, 9, 5], [nan, 1,",
"'L', 'R']}]] won = DotLineState(board=dotLineBoard, to_move='A', label='Won', scores={'A': 3, 'B':",
"range(len(row)): if isnan(row[c]): continue v = row[c] move = Move(r,",
"moves.empty(): moveList.append(moves.get(1)) return moveList def applyMove(board, size, row, col, side,",
"board[row][col]['winner'] == 'A': scores['A'] += 1 if board[row][col]['winner'] == 'B':",
"'B', 'L', 'R']}]] lost = DotLineState(board=dotLineBoard, to_move='A', label='Lost', scores={'A': 1,",
"Move(r, c, v) mQueue.put(move) return q2list(mQueue) class ThinkAhead(Game): \"\"\" An",
"v currMover = state.to_move nextMover = self.opponent(currMover) newState = deepcopy(state)",
"'B': scores['B'] += 1 return scores board = ''' ***",
"position, board, label=None): self.to_move = to_move self.position = position self.board",
"'lines': ['T', 'L']}, {'winner': '', 'lines': ['R']}], [{'winner': '', 'lines':",
"+= ' ' if space == len(board[row]) - 1 and",
"+= '*' if 'B' in board[row][col]['lines']: board_string += '---' else:",
"{'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}], [{'winner': 'B', 'lines':",
"nan], [9, nan]], label='lost' ) lost.scores = {'H': 0, 'V':",
">= 0 and row != size - 1 and side",
"range(0, len(board)): for col in range(0, len(board[row])): board_string += '*'",
"'', 'lines': ['L', 'R']}], [{'winner': '', 'lines': ['B', 'L', 'R']},",
"''' *** *** *** ''' def printDotsBoard(board): board_string = ''",
"= applyMove(newState.board, self.size, row, col, side, currMover) newState.scores = countScore(newState.board)",
"space in range(0, len(board[row])): if 'L' in board[row][space]['lines']: board_string +=",
"DotLineState(board=dotLineBoard, to_move='A', label='Win in 5', scores={'A': 0, 'B': 0}) play",
"q2list(mQueue) def movesInCol(board, c): mQueue = PriorityQueue() for r in",
"= DotsAndLines(winIn5_3x3) myGames = { dotLine: [ won, lost, tied,",
"len(board[row]) - 1 and 'R' in board[row][space]['lines']: board_string += '",
"= state self.size = len(state.board) def actions(self, state): \"Legal moves",
"scores={'A': 0, 'B': 0}): self.to_move = to_move self.board = board",
"not yet taken.\" moves = availableMoves(state.board) return moves # defines",
"'V': 0} lost = GameState( to_move='V', position=(0, 1), board=[[nan, nan],",
"'R'] complete = True for side in sides: if side",
"= DotLineState(board=dotLineBoard, to_move='A', label='Win in 1', scores={'A': 2, 'B': 1})",
"'V': return 'H' return None def result(self, state, move): r,",
"+= v return newState def utility(self, state, player): \"Player relative",
"'H': return 'V' if player == 'V': return 'H' return",
"1: board_string += '*\\n' for space in range(0, len(board[row])): if",
"= scores def __str__(self): if self.label is None: return super(DotLineState,",
"DotLineState(board=dotLineBoard, to_move='A', label='Lost', scores={'A': 1, 'B': 3}) dotLineBoard = [[{'winner':",
"the squares, whether the top, bottom, left, and right have",
"c = state.position if state.to_move == 'H': moves = movesInRow(state.board,",
"self.label = label self.scores = scores def __str__(self): if self.label",
"None: return super(GameState, self).__str__() return self.label class Move: def __init__(self,",
"position=(0, 1), board=[[nan, nan], [9, nan]], label='lost' ) lost.scores =",
"9, nan], [nan, nan, 1]], label='winin2' ) losein2 = GameState(",
"nan, 1, 5]], label='stolen' ) choose1 = GameState( to_move='H', position=(1,",
"self.size, row, col, side, currMover) newState.scores = countScore(newState.board) return newState",
"'A' return None def result(self, state, move): row, col, side",
"print_table(state.board, njust='center', sep=',') printDotsBoard(state.board) print('Score: ' + str(state.scores)) ''' Board",
"'lines': ['T', 'B', 'L', 'R']}]] lost = DotLineState(board=dotLineBoard, to_move='A', label='Lost',",
"[nan, 1, 3, 2], [8, 6, 4, 4], [nan, nan,",
"nan, 1]], label='losein2' ) losein2.maxDepth = 3 # http://www.kongregate.com/games/zolli/thinkahead-brain-trainer stolen",
"3, 2], [8, 6, 4, 4], [9, nan, 1, 5]],",
"' board_string += '*' print(board_string) class DotLineState: def __init__(self, to_move,",
"__str__(self): if self.label == None: return super(GameState, self).__str__() return self.label",
"1 return scores board = ''' *** *** *** '''",
"return self.row, self.col, self.value def __lt__(self, other): return self.value >",
"2], [nan, 9, nan], [nan, nan, 1]], label='winin2' ) losein2",
"'B', 'L', 'R'] moves = PriorityQueue() for row in range(0,",
"+= '*' if 'T' in board[row][col]['lines']: board_string += '---' else:",
"len(board[row]) - 1: board_string += '*\\n' for space in range(0,",
"GameState( to_move='V', position=(0, 1), board=[[nan, nan], [9, nan]], label='lost' )",
"''' def printDotsBoard(board): board_string = '' for row in range(0,",
"[]}], [{'winner': '', 'lines': []}, {'winner': '', 'lines': []}]], to_move='A',",
"state): \"Legal moves are any square not yet taken.\" moves",
"{'winner': '', 'lines': ['T', 'L']}, {'winner': '', 'lines': ['R']}], [{'winner':",
"if self.label == None: return super(GameState, self).__str__() return self.label class",
"self.opponent(currMover) newState = deepcopy(state) newState.to_move = nextMover newState.position = r,",
"v) mQueue.put(move) return q2list(mQueue) def movesInCol(board, c): mQueue = PriorityQueue()",
"__init__(self, state): self.initial = state def actions(self, state): \"Legal moves",
"state): self.initial = state def actions(self, state): \"Legal moves are",
"to_move='H', position=(0, 0), board=[[nan, 3, 2], [nan, 9, nan], [nan,",
"> other.value def q2list(mq): list = [] while not mq.empty():",
"2], [8, 6, 4, 4], [9, nan, 1, 5]], label='stolen'",
"moves # defines the order of play def opponent(self, player):",
"# defines the order of play def opponent(self, player): if",
"position=(0, 0), board=[[nan, 3, 2], [nan, 9, nan], [nan, nan,",
"in range(0, len(board)): for col in range(0, len(board[row])): board_string +=",
"0, 'V': 9} winin1 = GameState( to_move='H', position=(1, 1), board=[[nan,",
"if row == len(board) - 1: for col in range(0,",
"squares.\" return len(self.actions(state)) == 0 def display(self, state): # print_table(state.board,",
"'B', 'lines': ['T', 'B', 'L', 'R']}]] won = DotLineState(board=dotLineBoard, to_move='A',",
"'L', 'R']}, {'winner': 'B', 'lines': ['T', 'B', 'L', 'R']}]] lost",
"' if space == len(board[row]) - 1 and 'R' in",
"won = DotLineState(board=dotLineBoard, to_move='A', label='Won', scores={'A': 3, 'B': 1}) dotLineBoard",
"board=[[nan, nan], [9, nan]], label='won' ) won.scores = {'H': 9,",
"2], [8, 6, 4, 4], [nan, nan, 1, 5]], label='choose1'",
"if board[row][col]['winner'] == 'A': scores['A'] += 1 if board[row][col]['winner'] ==",
"len(board[row])): board_string += '*' if 'B' in board[row][col]['lines']: board_string +=",
"in range(0, len(board)): if board[row][col]['winner'] == 'A': scores['A'] += 1",
"nan, 1]], label='winin2' ) losein2 = GameState( to_move='V', position=(0, 0),",
"'B': 0} for row in range(0, len(board)): for col in",
"import PriorityQueue from copy import deepcopy from utils import isnumber",
"games import Game from math import nan, isnan from queue",
"+= '*\\n' for space in range(0, len(board[row])): if 'L' in",
"r): mQueue = PriorityQueue() row = board[r] for c in",
"row != size - 1 and side == 'B': board[row",
"= state.position if state.to_move == 'H': moves = movesInRow(state.board, r)",
"'B': 1}) dotLineBoard = [[{'winner': '', 'lines': ['L', 'R']}, {'winner':",
"= r, c newState.board[r][c] = nan newState.scores[currMover] += v return",
"of play def opponent(self, player): if player == 'A': return",
"player): if player == 'H': return 'V' if player ==",
"GameState( to_move='H', position=(3, 1), board=[[3, 8, 9, 5], [9, 1,",
"1, 3, 2], [8, 6, 4, 4], [9, nan, 1,",
"defines the order of play def opponent(self, player): if player",
"'L', 'R']}, {'winner': '', 'lines': ['T', 'L']}]] winin1Dots = DotLineState(board=dotLineBoard,",
"1}) dotLineBoard = [[{'winner': '', 'lines': ['L', 'R']}, {'winner': '',",
"'A', 'lines': ['T', 'B', 'L', 'R']}, {'winner': 'B', 'lines': ['T',",
"and right have been filled, and which player owns the",
"5], [nan, 1, 3, 2], [8, 6, 4, 4], [nan,",
"['T', 'B', 'L', 'R']}], [{'winner': 'B', 'lines': ['T', 'B', 'L',",
"<gh_stars>0 from games import Game from math import nan, isnan"
] |
[
"for argument if not ticker: raise Exception(\"Stock ticker is required\")",
"image = Image.open(imagefile) image = autocrop_image(image, 0) image.save(imagefile, \"PNG\", quality=100)",
"text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) i = 0 for i in range(0,",
"df2img.plot_dataframe( df_pg, fig_size=(1000, (40 + (40 * 20))), col_width=[3, 3,",
"value=\"0\", emoji=\"🟢\"), ] await ctx.send(embed=embeds[0], view=Menu(embeds, options)) except Exception as",
"quality=100) uploaded_image = gst_imgur.upload_image(imagefile, title=\"something\") image_link = uploaded_image.link embeds_img.append( f\"{image_link}\",",
"\"impliedVolatility\", ] if opt_type == \"Calls\": df = calls_df[columns].rename(columns=column_map) if",
"required\") dates = yfinance_model.option_expirations(ticker) if not dates: raise Exception(\"Stock ticker",
"None, min_sp: float = None, max_sp: float = None, ):",
"icon_url=cfg.AUTHOR_ICON_URL, ) i = 0 for i in range(0, i2):",
"for col, f in formats.items(): df[col] = df[col].map(lambda x: f.format(x))",
"filename=imagefile) image = Image.open(imagefile) image = autocrop_image(image, 0) image.save(imagefile, \"PNG\",",
"np.percentile(df[\"strike\"], 1) max_strike = np.percentile(df[\"strike\"], 100) if min_sp: min_strike =",
"for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f\"Page",
"dates = yfinance_model.option_expirations(ticker) if not dates: raise Exception(\"Stock ticker is",
"ticker is invalid\") options = yfinance_model.get_option_chain(ticker, str(expiry)) calls_df = options.calls",
"discordbot.helpers import autocrop_image from gamestonk_terminal.stocks.options import yfinance_model async def chain_command(",
"1) max_strike = np.percentile(df[\"strike\"], 100) if min_sp: min_strike = min_sp",
"while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) figp =",
"\"\"\"Show calls/puts for given ticker and expiration\"\"\" try: # Debug",
"{expiry} [yfinance]\" embeds: list = [] # Weekly Calls Pages",
"0, 20 df_pg = [] embeds_img = [] dindex =",
"= 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i +=",
") embeds[i].set_footer( text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) i = 0 for i",
"pd from menus.menu import Menu from PIL import Image import",
"gst_imgur.upload_image(imagefile, title=\"something\") image_link = uploaded_image.link embeds_img.append( f\"{image_link}\", ) embeds.append( disnake.Embed(",
"uploaded_image = gst_imgur.upload_image(imagefile, title=\"something\") image_link = uploaded_image.link embeds_img.append( f\"{image_link}\", )",
"if max_sp: max_strike = max_sp if min_sp > max_sp: #",
"figp = df2img.plot_dataframe( df_pg, fig_size=(1000, (40 + (40 * 20))),",
"ticker: str = None, expiry: str = None, opt_type: str",
"= [] embeds_img = [] dindex = len(df.index) while i",
"i in range(0, i2): embeds[i].set_author( name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL, ) embeds[i].set_footer(",
"max_sp: max_strike = max_sp if min_sp > max_sp: # type:",
"= 0, 0, 20 df_pg = [] embeds_img = []",
"Exception(\"Stock ticker is invalid\") options = yfinance_model.get_option_chain(ticker, str(expiry)) calls_df =",
"min_sp > max_sp: # type: ignore min_sp, max_sp = max_strike,",
"= {\"iv\": \"{:.2f}\"} for col, f in formats.items(): df[col] =",
"import Menu from PIL import Image import discordbot.config_discordbot as cfg",
"f in formats.items(): df[col] = df[col].map(lambda x: f.format(x)) # pylint:",
"paper_bgcolor=\"rgba(0, 0, 0, 0)\", ) imagefile = f\"opt-chain{i}.png\" df2img.save_dataframe(fig=figp, filename=imagefile)",
"ticker is required\") dates = yfinance_model.option_expirations(ticker) if not dates: raise",
"as np import pandas as pd from menus.menu import Menu",
"import gst_imgur, logger from discordbot.helpers import autocrop_image from gamestonk_terminal.stocks.options import",
"= {\"openInterest\": \"oi\", \"volume\": \"vol\", \"impliedVolatility\": \"iv\"} columns = [",
"options = yfinance_model.get_option_chain(ticker, str(expiry)) calls_df = options.calls puts_df = options.puts",
"puts_df = options.puts column_map = {\"openInterest\": \"oi\", \"volume\": \"vol\", \"impliedVolatility\":",
"= autocrop_image(image, 0) image.save(imagefile, \"PNG\", quality=100) uploaded_image = gst_imgur.upload_image(imagefile, title=\"something\")",
"# type: ignore min_sp, max_sp = max_strike, min_strike df =",
"# Author/Footer for i in range(0, i2): embeds[i].set_author( name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL,",
"\"volume\", \"openInterest\", \"impliedVolatility\", ] if opt_type == \"Calls\": df =",
"if opt_type == \"Puts\": df = puts_df[columns].rename(columns=column_map) min_strike = np.percentile(df[\"strike\"],",
"formats.items(): df[col] = df[col].map(lambda x: f.format(x)) # pylint: disable=W0640 df.set_index(\"strike\",",
"= None, max_sp: float = None, ): \"\"\"Show calls/puts for",
"Check for argument if not ticker: raise Exception(\"Stock ticker is",
"np.percentile(df[\"strike\"], 100) if min_sp: min_strike = min_sp if max_sp: max_strike",
"import pandas as pd from menus.menu import Menu from PIL",
"gamestonk_terminal.stocks.options import yfinance_model async def chain_command( ctx, ticker: str =",
"and expiration\"\"\" try: # Debug if cfg.DEBUG: logger.debug( \"opt-chain %s",
"df_pg, fig_size=(1000, (40 + (40 * 20))), col_width=[3, 3, 3,",
"= gst_imgur.upload_image(imagefile, title=\"something\") image_link = uploaded_image.link embeds_img.append( f\"{image_link}\", ) embeds.append(",
") i2 += 1 i += 20 end += 20",
"= np.percentile(df[\"strike\"], 100) if min_sp: min_strike = min_sp if max_sp:",
"max_sp: # type: ignore min_sp, max_sp = max_strike, min_strike df",
"opt_type: str = None, min_sp: float = None, max_sp: float",
"len(df.index) while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) figp",
"df2img.save_dataframe(fig=figp, filename=imagefile) image = Image.open(imagefile) image = autocrop_image(image, 0) image.save(imagefile,",
"title=\"ERROR Stock-Options: Expirations\", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, )",
"= [] # Weekly Calls Pages i, i2, end =",
"import yfinance_model async def chain_command( ctx, ticker: str = None,",
"): \"\"\"Show calls/puts for given ticker and expiration\"\"\" try: #",
"name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) i =",
"# Debug if cfg.DEBUG: logger.debug( \"opt-chain %s %s %s %s",
"df = df[df[\"strike\"] >= min_strike] df = df[df[\"strike\"] <= max_strike]",
"dindex = len(df.index) while i < dindex: df_pg = df.iloc[i:end]",
"as cfg from discordbot.config_discordbot import gst_imgur, logger from discordbot.helpers import",
"import df2img import disnake import numpy as np import pandas",
"= None, ): \"\"\"Show calls/puts for given ticker and expiration\"\"\"",
"range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f\"Page 1 of {len(embeds)}\")",
"= puts_df[columns].rename(columns=column_map) min_strike = np.percentile(df[\"strike\"], 1) max_strike = np.percentile(df[\"strike\"], 100)",
") embeds.append( disnake.Embed( title=title, colour=cfg.COLOR, ), ) i2 += 1",
"%s %s %s %s\", ticker, expiry, opt_type, min_sp, max_sp )",
"col_width=[3, 3, 3, 3], tbl_cells=dict( height=35, ), font=dict( family=\"Consolas\", size=20,",
"embeds_img.append( f\"{image_link}\", ) embeds.append( disnake.Embed( title=title, colour=cfg.COLOR, ), ) i2",
"max_sp ) # Check for argument if not ticker: raise",
"Menu from PIL import Image import discordbot.config_discordbot as cfg from",
"[ \"strike\", \"bid\", \"ask\", \"volume\", \"openInterest\", \"impliedVolatility\", ] if opt_type",
"in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f\"Page 1 of",
"= df2img.plot_dataframe( df_pg, fig_size=(1000, (40 + (40 * 20))), col_width=[3,",
"%s %s %s\", ticker, expiry, opt_type, min_sp, max_sp ) #",
"= yfinance_model.option_expirations(ticker) if not dates: raise Exception(\"Stock ticker is invalid\")",
"disnake.Embed( title=\"ERROR Stock-Options: Expirations\", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL,",
"column_map = {\"openInterest\": \"oi\", \"volume\": \"vol\", \"impliedVolatility\": \"iv\"} columns =",
"col, f in formats.items(): df[col] = df[col].map(lambda x: f.format(x)) #",
"min_strike] df = df[df[\"strike\"] <= max_strike] df[\"iv\"] = pd.to_numeric(df[\"iv\"].astype(float)) formats",
"i2, end = 0, 0, 20 df_pg = [] embeds_img",
"min_strike = min_sp if max_sp: max_strike = max_sp if min_sp",
"max_strike = np.percentile(df[\"strike\"], 100) if min_sp: min_strike = min_sp if",
"= Image.open(imagefile) image = autocrop_image(image, 0) image.save(imagefile, \"PNG\", quality=100) uploaded_image",
"autocrop_image(image, 0) image.save(imagefile, \"PNG\", quality=100) uploaded_image = gst_imgur.upload_image(imagefile, title=\"something\") image_link",
"import disnake import numpy as np import pandas as pd",
"str = None, min_sp: float = None, max_sp: float =",
"%s %s\", ticker, expiry, opt_type, min_sp, max_sp ) # Check",
"yfinance_model.option_expirations(ticker) if not dates: raise Exception(\"Stock ticker is invalid\") options",
"20 df_pg = [] embeds_img = [] dindex = len(df.index)",
"as pd from menus.menu import Menu from PIL import Image",
"i, i2, end = 0, 0, 20 df_pg = []",
"None, ): \"\"\"Show calls/puts for given ticker and expiration\"\"\" try:",
"100) if min_sp: min_strike = min_sp if max_sp: max_strike =",
"title = f\"Stocks: {opt_type} Option Chain for {ticker.upper()} on {expiry}",
"Debug if cfg.DEBUG: logger.debug( \"opt-chain %s %s %s %s %s\",",
"emoji=\"🟢\"), ] await ctx.send(embed=embeds[0], view=Menu(embeds, options)) except Exception as e:",
"formats = {\"iv\": \"{:.2f}\"} for col, f in formats.items(): df[col]",
"colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed, delete_after=30.0)",
"min_sp, max_sp ) # Check for argument if not ticker:",
"\"openInterest\", \"impliedVolatility\", ] if opt_type == \"Calls\": df = calls_df[columns].rename(columns=column_map)",
"3, 3, 3], tbl_cells=dict( height=35, ), font=dict( family=\"Consolas\", size=20, ),",
"= len(df.index) while i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg)",
"), font=dict( family=\"Consolas\", size=20, ), template=\"plotly_dark\", paper_bgcolor=\"rgba(0, 0, 0, 0)\",",
"= [ disnake.SelectOption(label=\"Home\", value=\"0\", emoji=\"🟢\"), ] await ctx.send(embed=embeds[0], view=Menu(embeds, options))",
"colour=cfg.COLOR, ), ) i2 += 1 i += 20 end",
"Author/Footer for i in range(0, i2): embeds[i].set_author( name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL,",
"df_pg = [] embeds_img = [] dindex = len(df.index) while",
"embed = disnake.Embed( title=\"ERROR Stock-Options: Expirations\", colour=cfg.COLOR, description=e, ) embed.set_author(",
"%s %s %s %s %s\", ticker, expiry, opt_type, min_sp, max_sp",
"for i in range(0, i2): embeds[i].set_author( name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL, )",
"of {len(embeds)}\") options = [ disnake.SelectOption(label=\"Home\", value=\"0\", emoji=\"🟢\"), ] await",
"{len(embeds)}\") options = [ disnake.SelectOption(label=\"Home\", value=\"0\", emoji=\"🟢\"), ] await ctx.send(embed=embeds[0],",
"embeds[0].set_footer(text=f\"Page 1 of {len(embeds)}\") options = [ disnake.SelectOption(label=\"Home\", value=\"0\", emoji=\"🟢\"),",
"0) image.save(imagefile, \"PNG\", quality=100) uploaded_image = gst_imgur.upload_image(imagefile, title=\"something\") image_link =",
"+= 20 os.remove(imagefile) # Author/Footer for i in range(0, i2):",
"\"ask\", \"volume\", \"openInterest\", \"impliedVolatility\", ] if opt_type == \"Calls\": df",
"df[col] = df[col].map(lambda x: f.format(x)) # pylint: disable=W0640 df.set_index(\"strike\", inplace=True)",
"df = puts_df[columns].rename(columns=column_map) min_strike = np.percentile(df[\"strike\"], 1) max_strike = np.percentile(df[\"strike\"],",
"Option Chain for {ticker.upper()} on {expiry} [yfinance]\" embeds: list =",
"tbl_cells=dict( height=35, ), font=dict( family=\"Consolas\", size=20, ), template=\"plotly_dark\", paper_bgcolor=\"rgba(0, 0,",
"20 os.remove(imagefile) # Author/Footer for i in range(0, i2): embeds[i].set_author(",
"end += 20 os.remove(imagefile) # Author/Footer for i in range(0,",
"from discordbot.helpers import autocrop_image from gamestonk_terminal.stocks.options import yfinance_model async def",
"= None, expiry: str = None, opt_type: str = None,",
"title=\"something\") image_link = uploaded_image.link embeds_img.append( f\"{image_link}\", ) embeds.append( disnake.Embed( title=title,",
"os import df2img import disnake import numpy as np import",
"\"bid\", \"ask\", \"volume\", \"openInterest\", \"impliedVolatility\", ] if opt_type == \"Calls\":",
"= uploaded_image.link embeds_img.append( f\"{image_link}\", ) embeds.append( disnake.Embed( title=title, colour=cfg.COLOR, ),",
"autocrop_image from gamestonk_terminal.stocks.options import yfinance_model async def chain_command( ctx, ticker:",
"(40 + (40 * 20))), col_width=[3, 3, 3, 3], tbl_cells=dict(",
"= options.calls puts_df = options.puts column_map = {\"openInterest\": \"oi\", \"volume\":",
"+= 1 embeds[0].set_footer(text=f\"Page 1 of {len(embeds)}\") options = [ disnake.SelectOption(label=\"Home\",",
"disable=W0640 df.set_index(\"strike\", inplace=True) title = f\"Stocks: {opt_type} Option Chain for",
"cfg.DEBUG: logger.debug( \"opt-chain %s %s %s %s %s\", ticker, expiry,",
"height=35, ), font=dict( family=\"Consolas\", size=20, ), template=\"plotly_dark\", paper_bgcolor=\"rgba(0, 0, 0,",
"+ (40 * 20))), col_width=[3, 3, 3, 3], tbl_cells=dict( height=35,",
"pandas as pd from menus.menu import Menu from PIL import",
"> max_sp: # type: ignore min_sp, max_sp = max_strike, min_strike",
"df[\"iv\"] = pd.to_numeric(df[\"iv\"].astype(float)) formats = {\"iv\": \"{:.2f}\"} for col, f",
"yfinance_model.get_option_chain(ticker, str(expiry)) calls_df = options.calls puts_df = options.puts column_map =",
"image_link = uploaded_image.link embeds_img.append( f\"{image_link}\", ) embeds.append( disnake.Embed( title=title, colour=cfg.COLOR,",
"embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f\"Page 1 of {len(embeds)}\") options =",
"dates: raise Exception(\"Stock ticker is invalid\") options = yfinance_model.get_option_chain(ticker, str(expiry))",
"except Exception as e: embed = disnake.Embed( title=\"ERROR Stock-Options: Expirations\",",
"embeds.append( disnake.Embed( title=title, colour=cfg.COLOR, ), ) i2 += 1 i",
"i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f\"Page 1",
"), ) i2 += 1 i += 20 end +=",
"pylint: disable=W0640 df.set_index(\"strike\", inplace=True) title = f\"Stocks: {opt_type} Option Chain",
"= df[df[\"strike\"] >= min_strike] df = df[df[\"strike\"] <= max_strike] df[\"iv\"]",
"min_strike = np.percentile(df[\"strike\"], 1) max_strike = np.percentile(df[\"strike\"], 100) if min_sp:",
"import autocrop_image from gamestonk_terminal.stocks.options import yfinance_model async def chain_command( ctx,",
"gst_imgur, logger from discordbot.helpers import autocrop_image from gamestonk_terminal.stocks.options import yfinance_model",
"disnake.Embed( title=title, colour=cfg.COLOR, ), ) i2 += 1 i +=",
"max_sp = max_strike, min_strike df = df[df[\"strike\"] >= min_strike] df",
"str(expiry)) calls_df = options.calls puts_df = options.puts column_map = {\"openInterest\":",
") imagefile = f\"opt-chain{i}.png\" df2img.save_dataframe(fig=figp, filename=imagefile) image = Image.open(imagefile) image",
"PIL import Image import discordbot.config_discordbot as cfg from discordbot.config_discordbot import",
"i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i",
"puts_df[columns].rename(columns=column_map) min_strike = np.percentile(df[\"strike\"], 1) max_strike = np.percentile(df[\"strike\"], 100) if",
"list = [] # Weekly Calls Pages i, i2, end",
"df = calls_df[columns].rename(columns=column_map) if opt_type == \"Puts\": df = puts_df[columns].rename(columns=column_map)",
"calls/puts for given ticker and expiration\"\"\" try: # Debug if",
"opt_type == \"Puts\": df = puts_df[columns].rename(columns=column_map) min_strike = np.percentile(df[\"strike\"], 1)",
"in formats.items(): df[col] = df[col].map(lambda x: f.format(x)) # pylint: disable=W0640",
"0, 0)\", ) imagefile = f\"opt-chain{i}.png\" df2img.save_dataframe(fig=figp, filename=imagefile) image =",
"raise Exception(\"Stock ticker is required\") dates = yfinance_model.option_expirations(ticker) if not",
"not dates: raise Exception(\"Stock ticker is invalid\") options = yfinance_model.get_option_chain(ticker,",
"raise Exception(\"Stock ticker is invalid\") options = yfinance_model.get_option_chain(ticker, str(expiry)) calls_df",
"imagefile = f\"opt-chain{i}.png\" df2img.save_dataframe(fig=figp, filename=imagefile) image = Image.open(imagefile) image =",
"if not dates: raise Exception(\"Stock ticker is invalid\") options =",
"font=dict( family=\"Consolas\", size=20, ), template=\"plotly_dark\", paper_bgcolor=\"rgba(0, 0, 0, 0)\", )",
"df[df[\"strike\"] <= max_strike] df[\"iv\"] = pd.to_numeric(df[\"iv\"].astype(float)) formats = {\"iv\": \"{:.2f}\"}",
"from menus.menu import Menu from PIL import Image import discordbot.config_discordbot",
">= min_strike] df = df[df[\"strike\"] <= max_strike] df[\"iv\"] = pd.to_numeric(df[\"iv\"].astype(float))",
"title=title, colour=cfg.COLOR, ), ) i2 += 1 i += 20",
"import numpy as np import pandas as pd from menus.menu",
"= [ \"strike\", \"bid\", \"ask\", \"volume\", \"openInterest\", \"impliedVolatility\", ] if",
"f\"Stocks: {opt_type} Option Chain for {ticker.upper()} on {expiry} [yfinance]\" embeds:",
"i += 1 embeds[0].set_footer(text=f\"Page 1 of {len(embeds)}\") options = [",
"options = [ disnake.SelectOption(label=\"Home\", value=\"0\", emoji=\"🟢\"), ] await ctx.send(embed=embeds[0], view=Menu(embeds,",
"type: ignore min_sp, max_sp = max_strike, min_strike df = df[df[\"strike\"]",
"3, 3], tbl_cells=dict( height=35, ), font=dict( family=\"Consolas\", size=20, ), template=\"plotly_dark\",",
"pd.to_numeric(df[\"iv\"].astype(float)) formats = {\"iv\": \"{:.2f}\"} for col, f in formats.items():",
"== \"Calls\": df = calls_df[columns].rename(columns=column_map) if opt_type == \"Puts\": df",
"\"{:.2f}\"} for col, f in formats.items(): df[col] = df[col].map(lambda x:",
"opt_type, min_sp, max_sp ) # Check for argument if not",
"not ticker: raise Exception(\"Stock ticker is required\") dates = yfinance_model.option_expirations(ticker)",
"[] dindex = len(df.index) while i < dindex: df_pg =",
"None, max_sp: float = None, ): \"\"\"Show calls/puts for given",
"ctx.send(embed=embeds[0], view=Menu(embeds, options)) except Exception as e: embed = disnake.Embed(",
"\"Puts\": df = puts_df[columns].rename(columns=column_map) min_strike = np.percentile(df[\"strike\"], 1) max_strike =",
"ignore min_sp, max_sp = max_strike, min_strike df = df[df[\"strike\"] >=",
"ticker, expiry, opt_type, min_sp, max_sp ) # Check for argument",
"= None, min_sp: float = None, max_sp: float = None,",
"f.format(x)) # pylint: disable=W0640 df.set_index(\"strike\", inplace=True) title = f\"Stocks: {opt_type}",
"[yfinance]\" embeds: list = [] # Weekly Calls Pages i,",
"0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i]) i += 1",
"options.puts column_map = {\"openInterest\": \"oi\", \"volume\": \"vol\", \"impliedVolatility\": \"iv\"} columns",
"[] # Weekly Calls Pages i, i2, end = 0,",
"fig_size=(1000, (40 + (40 * 20))), col_width=[3, 3, 3, 3],",
"disnake import numpy as np import pandas as pd from",
"disnake.SelectOption(label=\"Home\", value=\"0\", emoji=\"🟢\"), ] await ctx.send(embed=embeds[0], view=Menu(embeds, options)) except Exception",
"\"vol\", \"impliedVolatility\": \"iv\"} columns = [ \"strike\", \"bid\", \"ask\", \"volume\",",
"opt_type == \"Calls\": df = calls_df[columns].rename(columns=column_map) if opt_type == \"Puts\":",
"discordbot.config_discordbot import gst_imgur, logger from discordbot.helpers import autocrop_image from gamestonk_terminal.stocks.options",
"ticker: raise Exception(\"Stock ticker is required\") dates = yfinance_model.option_expirations(ticker) if",
"min_sp: float = None, max_sp: float = None, ): \"\"\"Show",
"for given ticker and expiration\"\"\" try: # Debug if cfg.DEBUG:",
"expiration\"\"\" try: # Debug if cfg.DEBUG: logger.debug( \"opt-chain %s %s",
"# Check for argument if not ticker: raise Exception(\"Stock ticker",
"df[col].map(lambda x: f.format(x)) # pylint: disable=W0640 df.set_index(\"strike\", inplace=True) title =",
"i2): embeds[i].set_image(url=embeds_img[i]) i += 1 embeds[0].set_footer(text=f\"Page 1 of {len(embeds)}\") options",
"i2 += 1 i += 20 end += 20 os.remove(imagefile)",
"chain_command( ctx, ticker: str = None, expiry: str = None,",
"Chain for {ticker.upper()} on {expiry} [yfinance]\" embeds: list = []",
"= min_sp if max_sp: max_strike = max_sp if min_sp >",
"np import pandas as pd from menus.menu import Menu from",
"inplace=True) title = f\"Stocks: {opt_type} Option Chain for {ticker.upper()} on",
"] await ctx.send(embed=embeds[0], view=Menu(embeds, options)) except Exception as e: embed",
"df2img import disnake import numpy as np import pandas as",
"df.iloc[i:end] df_pg.append(df_pg) figp = df2img.plot_dataframe( df_pg, fig_size=(1000, (40 + (40",
"1 embeds[0].set_footer(text=f\"Page 1 of {len(embeds)}\") options = [ disnake.SelectOption(label=\"Home\", value=\"0\",",
"max_strike] df[\"iv\"] = pd.to_numeric(df[\"iv\"].astype(float)) formats = {\"iv\": \"{:.2f}\"} for col,",
"Stock-Options: Expirations\", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await",
"= f\"Stocks: {opt_type} Option Chain for {ticker.upper()} on {expiry} [yfinance]\"",
"str = None, opt_type: str = None, min_sp: float =",
"on {expiry} [yfinance]\" embeds: list = [] # Weekly Calls",
"is required\") dates = yfinance_model.option_expirations(ticker) if not dates: raise Exception(\"Stock",
"f\"opt-chain{i}.png\" df2img.save_dataframe(fig=figp, filename=imagefile) image = Image.open(imagefile) image = autocrop_image(image, 0)",
"1 of {len(embeds)}\") options = [ disnake.SelectOption(label=\"Home\", value=\"0\", emoji=\"🟢\"), ]",
"max_strike, min_strike df = df[df[\"strike\"] >= min_strike] df = df[df[\"strike\"]",
"family=\"Consolas\", size=20, ), template=\"plotly_dark\", paper_bgcolor=\"rgba(0, 0, 0, 0)\", ) imagefile",
"invalid\") options = yfinance_model.get_option_chain(ticker, str(expiry)) calls_df = options.calls puts_df =",
"None, expiry: str = None, opt_type: str = None, min_sp:",
"embeds_img = [] dindex = len(df.index) while i < dindex:",
"x: f.format(x)) # pylint: disable=W0640 df.set_index(\"strike\", inplace=True) title = f\"Stocks:",
"min_sp if max_sp: max_strike = max_sp if min_sp > max_sp:",
"dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) figp = df2img.plot_dataframe( df_pg, fig_size=(1000,",
") i = 0 for i in range(0, i2): embeds[i].set_image(url=embeds_img[i])",
"= max_sp if min_sp > max_sp: # type: ignore min_sp,",
"logger from discordbot.helpers import autocrop_image from gamestonk_terminal.stocks.options import yfinance_model async",
"argument if not ticker: raise Exception(\"Stock ticker is required\") dates",
"df[df[\"strike\"] >= min_strike] df = df[df[\"strike\"] <= max_strike] df[\"iv\"] =",
"df_pg = df.iloc[i:end] df_pg.append(df_pg) figp = df2img.plot_dataframe( df_pg, fig_size=(1000, (40",
"await ctx.send(embed=embeds[0], view=Menu(embeds, options)) except Exception as e: embed =",
"{opt_type} Option Chain for {ticker.upper()} on {expiry} [yfinance]\" embeds: list",
"[ disnake.SelectOption(label=\"Home\", value=\"0\", emoji=\"🟢\"), ] await ctx.send(embed=embeds[0], view=Menu(embeds, options)) except",
"calls_df[columns].rename(columns=column_map) if opt_type == \"Puts\": df = puts_df[columns].rename(columns=column_map) min_strike =",
"] if opt_type == \"Calls\": df = calls_df[columns].rename(columns=column_map) if opt_type",
"df_pg.append(df_pg) figp = df2img.plot_dataframe( df_pg, fig_size=(1000, (40 + (40 *",
"is invalid\") options = yfinance_model.get_option_chain(ticker, str(expiry)) calls_df = options.calls puts_df",
"= calls_df[columns].rename(columns=column_map) if opt_type == \"Puts\": df = puts_df[columns].rename(columns=column_map) min_strike",
"%s\", ticker, expiry, opt_type, min_sp, max_sp ) # Check for",
"import discordbot.config_discordbot as cfg from discordbot.config_discordbot import gst_imgur, logger from",
"df.set_index(\"strike\", inplace=True) title = f\"Stocks: {opt_type} Option Chain for {ticker.upper()}",
"def chain_command( ctx, ticker: str = None, expiry: str =",
"columns = [ \"strike\", \"bid\", \"ask\", \"volume\", \"openInterest\", \"impliedVolatility\", ]",
"= yfinance_model.get_option_chain(ticker, str(expiry)) calls_df = options.calls puts_df = options.puts column_map",
"template=\"plotly_dark\", paper_bgcolor=\"rgba(0, 0, 0, 0)\", ) imagefile = f\"opt-chain{i}.png\" df2img.save_dataframe(fig=figp,",
"max_sp if min_sp > max_sp: # type: ignore min_sp, max_sp",
"{ticker.upper()} on {expiry} [yfinance]\" embeds: list = [] # Weekly",
"3], tbl_cells=dict( height=35, ), font=dict( family=\"Consolas\", size=20, ), template=\"plotly_dark\", paper_bgcolor=\"rgba(0,",
"import Image import discordbot.config_discordbot as cfg from discordbot.config_discordbot import gst_imgur,",
"* 20))), col_width=[3, 3, 3, 3], tbl_cells=dict( height=35, ), font=dict(",
"min_sp: min_strike = min_sp if max_sp: max_strike = max_sp if",
"max_sp: float = None, ): \"\"\"Show calls/puts for given ticker",
"Image.open(imagefile) image = autocrop_image(image, 0) image.save(imagefile, \"PNG\", quality=100) uploaded_image =",
"end = 0, 0, 20 df_pg = [] embeds_img =",
"min_strike df = df[df[\"strike\"] >= min_strike] df = df[df[\"strike\"] <=",
"float = None, ): \"\"\"Show calls/puts for given ticker and",
"1 i += 20 end += 20 os.remove(imagefile) # Author/Footer",
"size=20, ), template=\"plotly_dark\", paper_bgcolor=\"rgba(0, 0, 0, 0)\", ) imagefile =",
"discordbot.config_discordbot as cfg from discordbot.config_discordbot import gst_imgur, logger from discordbot.helpers",
"os.remove(imagefile) # Author/Footer for i in range(0, i2): embeds[i].set_author( name=cfg.AUTHOR_NAME,",
"embeds[i].set_author( name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) i",
"== \"Puts\": df = puts_df[columns].rename(columns=column_map) min_strike = np.percentile(df[\"strike\"], 1) max_strike",
"i < dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) figp = df2img.plot_dataframe(",
"logger.debug( \"opt-chain %s %s %s %s %s\", ticker, expiry, opt_type,",
"\"oi\", \"volume\": \"vol\", \"impliedVolatility\": \"iv\"} columns = [ \"strike\", \"bid\",",
"0, 0, 0)\", ) imagefile = f\"opt-chain{i}.png\" df2img.save_dataframe(fig=figp, filename=imagefile) image",
"for {ticker.upper()} on {expiry} [yfinance]\" embeds: list = [] #",
"from gamestonk_terminal.stocks.options import yfinance_model async def chain_command( ctx, ticker: str",
"{\"iv\": \"{:.2f}\"} for col, f in formats.items(): df[col] = df[col].map(lambda",
"df = df[df[\"strike\"] <= max_strike] df[\"iv\"] = pd.to_numeric(df[\"iv\"].astype(float)) formats =",
"str = None, expiry: str = None, opt_type: str =",
"Calls Pages i, i2, end = 0, 0, 20 df_pg",
"embeds[i].set_footer( text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) i = 0 for i in",
"Exception as e: embed = disnake.Embed( title=\"ERROR Stock-Options: Expirations\", colour=cfg.COLOR,",
"ctx, ticker: str = None, expiry: str = None, opt_type:",
"image = autocrop_image(image, 0) image.save(imagefile, \"PNG\", quality=100) uploaded_image = gst_imgur.upload_image(imagefile,",
"numpy as np import pandas as pd from menus.menu import",
"in range(0, i2): embeds[i].set_author( name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=cfg.AUTHOR_NAME,",
"# pylint: disable=W0640 df.set_index(\"strike\", inplace=True) title = f\"Stocks: {opt_type} Option",
"= [] dindex = len(df.index) while i < dindex: df_pg",
"float = None, max_sp: float = None, ): \"\"\"Show calls/puts",
"(40 * 20))), col_width=[3, 3, 3, 3], tbl_cells=dict( height=35, ),",
"image.save(imagefile, \"PNG\", quality=100) uploaded_image = gst_imgur.upload_image(imagefile, title=\"something\") image_link = uploaded_image.link",
"20 end += 20 os.remove(imagefile) # Author/Footer for i in",
"min_sp, max_sp = max_strike, min_strike df = df[df[\"strike\"] >= min_strike]",
"Weekly Calls Pages i, i2, end = 0, 0, 20",
"None, opt_type: str = None, min_sp: float = None, max_sp:",
"options.calls puts_df = options.puts column_map = {\"openInterest\": \"oi\", \"volume\": \"vol\",",
"{\"openInterest\": \"oi\", \"volume\": \"vol\", \"impliedVolatility\": \"iv\"} columns = [ \"strike\",",
"i += 20 end += 20 os.remove(imagefile) # Author/Footer for",
"from discordbot.config_discordbot import gst_imgur, logger from discordbot.helpers import autocrop_image from",
"given ticker and expiration\"\"\" try: # Debug if cfg.DEBUG: logger.debug(",
"), template=\"plotly_dark\", paper_bgcolor=\"rgba(0, 0, 0, 0)\", ) imagefile = f\"opt-chain{i}.png\"",
"= disnake.Embed( title=\"ERROR Stock-Options: Expirations\", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME,",
"\"iv\"} columns = [ \"strike\", \"bid\", \"ask\", \"volume\", \"openInterest\", \"impliedVolatility\",",
"from PIL import Image import discordbot.config_discordbot as cfg from discordbot.config_discordbot",
"= np.percentile(df[\"strike\"], 1) max_strike = np.percentile(df[\"strike\"], 100) if min_sp: min_strike",
"max_strike = max_sp if min_sp > max_sp: # type: ignore",
"\"PNG\", quality=100) uploaded_image = gst_imgur.upload_image(imagefile, title=\"something\") image_link = uploaded_image.link embeds_img.append(",
"0, 0, 20 df_pg = [] embeds_img = [] dindex",
"cfg from discordbot.config_discordbot import gst_imgur, logger from discordbot.helpers import autocrop_image",
"\"Calls\": df = calls_df[columns].rename(columns=column_map) if opt_type == \"Puts\": df =",
"Exception(\"Stock ticker is required\") dates = yfinance_model.option_expirations(ticker) if not dates:",
"\"volume\": \"vol\", \"impliedVolatility\": \"iv\"} columns = [ \"strike\", \"bid\", \"ask\",",
"if not ticker: raise Exception(\"Stock ticker is required\") dates =",
"\"strike\", \"bid\", \"ask\", \"volume\", \"openInterest\", \"impliedVolatility\", ] if opt_type ==",
"expiry: str = None, opt_type: str = None, min_sp: float",
"= options.puts column_map = {\"openInterest\": \"oi\", \"volume\": \"vol\", \"impliedVolatility\": \"iv\"}",
"20))), col_width=[3, 3, 3, 3], tbl_cells=dict( height=35, ), font=dict( family=\"Consolas\",",
"\"opt-chain %s %s %s %s %s\", ticker, expiry, opt_type, min_sp,",
"Expirations\", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed,",
") # Check for argument if not ticker: raise Exception(\"Stock",
"url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) i = 0",
"menus.menu import Menu from PIL import Image import discordbot.config_discordbot as",
"options)) except Exception as e: embed = disnake.Embed( title=\"ERROR Stock-Options:",
"# Weekly Calls Pages i, i2, end = 0, 0,",
"f\"{image_link}\", ) embeds.append( disnake.Embed( title=title, colour=cfg.COLOR, ), ) i2 +=",
"= df.iloc[i:end] df_pg.append(df_pg) figp = df2img.plot_dataframe( df_pg, fig_size=(1000, (40 +",
"icon_url=cfg.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) i = 0 for",
"+= 20 end += 20 os.remove(imagefile) # Author/Footer for i",
"< dindex: df_pg = df.iloc[i:end] df_pg.append(df_pg) figp = df2img.plot_dataframe( df_pg,",
"<= max_strike] df[\"iv\"] = pd.to_numeric(df[\"iv\"].astype(float)) formats = {\"iv\": \"{:.2f}\"} for",
"yfinance_model async def chain_command( ctx, ticker: str = None, expiry:",
"expiry, opt_type, min_sp, max_sp ) # Check for argument if",
"+= 1 i += 20 end += 20 os.remove(imagefile) #",
"= None, opt_type: str = None, min_sp: float = None,",
"Pages i, i2, end = 0, 0, 20 df_pg =",
"ticker and expiration\"\"\" try: # Debug if cfg.DEBUG: logger.debug( \"opt-chain",
"view=Menu(embeds, options)) except Exception as e: embed = disnake.Embed( title=\"ERROR",
"embeds: list = [] # Weekly Calls Pages i, i2,",
"i2): embeds[i].set_author( name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, )",
"e: embed = disnake.Embed( title=\"ERROR Stock-Options: Expirations\", colour=cfg.COLOR, description=e, )",
"= max_strike, min_strike df = df[df[\"strike\"] >= min_strike] df =",
"if cfg.DEBUG: logger.debug( \"opt-chain %s %s %s %s %s\", ticker,",
"uploaded_image.link embeds_img.append( f\"{image_link}\", ) embeds.append( disnake.Embed( title=title, colour=cfg.COLOR, ), )",
"as e: embed = disnake.Embed( title=\"ERROR Stock-Options: Expirations\", colour=cfg.COLOR, description=e,",
"if min_sp: min_strike = min_sp if max_sp: max_strike = max_sp",
"0)\", ) imagefile = f\"opt-chain{i}.png\" df2img.save_dataframe(fig=figp, filename=imagefile) image = Image.open(imagefile)",
"range(0, i2): embeds[i].set_author( name=cfg.AUTHOR_NAME, url=cfg.AUTHOR_URL, icon_url=cfg.AUTHOR_ICON_URL, ) embeds[i].set_footer( text=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL,",
"Image import discordbot.config_discordbot as cfg from discordbot.config_discordbot import gst_imgur, logger",
"= df[col].map(lambda x: f.format(x)) # pylint: disable=W0640 df.set_index(\"strike\", inplace=True) title",
"[] embeds_img = [] dindex = len(df.index) while i <",
"= df[df[\"strike\"] <= max_strike] df[\"iv\"] = pd.to_numeric(df[\"iv\"].astype(float)) formats = {\"iv\":",
"async def chain_command( ctx, ticker: str = None, expiry: str",
"calls_df = options.calls puts_df = options.puts column_map = {\"openInterest\": \"oi\",",
"import os import df2img import disnake import numpy as np",
"= f\"opt-chain{i}.png\" df2img.save_dataframe(fig=figp, filename=imagefile) image = Image.open(imagefile) image = autocrop_image(image,",
"= pd.to_numeric(df[\"iv\"].astype(float)) formats = {\"iv\": \"{:.2f}\"} for col, f in",
"if min_sp > max_sp: # type: ignore min_sp, max_sp =",
"\"impliedVolatility\": \"iv\"} columns = [ \"strike\", \"bid\", \"ask\", \"volume\", \"openInterest\",",
"if opt_type == \"Calls\": df = calls_df[columns].rename(columns=column_map) if opt_type ==",
"try: # Debug if cfg.DEBUG: logger.debug( \"opt-chain %s %s %s"
] |
[
"rate\", \"Lender profit\"]] = profit_columns data_frame[\"Dollar profit\"] = ( data_frame[\"Lender",
"<filename>scripts/get_lenderprofit.py #%% import packages import numpy as np import pandas",
"result_type=\"expand\", ) data_frame[[\"Breakeven Loan rate\", \"Lender profit\"]] = profit_columns data_frame[\"Dollar",
"a, _ = get_average_profitability(lender_coc=x, lapse_assumption=False) return a lender_coc_value = np.arange(start=0.01,",
"#%% import packages import numpy as np import pandas as",
"as pd import multiprocessing from time import time import json",
"= get_average_profitability(lender_coc=x, lapse_assumption=True) return a def tempfunc_f(x): a, _ =",
"lapse_assumption=True, policyholder_rate=yield_curve, statutory_interest=0.035, premium_markup=0.0, cash_interest=0.001, lender_coc=0.01, data_frame=mortality_experience, ): profit_columns =",
"import multiprocessing from time import time import json from premiumFinance.constants",
"premiumFinance.financing import calculate_lender_profit, yield_curve mortality_experience = pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%% calculate profit",
"policyholder_rate=yield_curve, statutory_interest=0.035, premium_markup=0.0, cash_interest=0.001, lender_coc=0.01, data_frame=mortality_experience, ): profit_columns = data_frame.apply(",
"tbd if __name__ == \"__main__\": pool = multiprocessing.Pool() start_time =",
"Exposed\"].sum() ) return average_profitability, data_frame def tempfunc_t(x): a, _ =",
"average_profitability, data_frame def tempfunc_t(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=True) return",
"tempfunc in (tempfunc_t, tempfunc_f): foo.append( pool.map( tempfunc, lender_coc_value, ) )",
"= time() foo = [] for tempfunc in (tempfunc_t, tempfunc_f):",
"json from premiumFinance.constants import ( MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH, ) from premiumFinance.financing",
"return a lender_coc_value = np.arange(start=0.01, stop=0.2, step=0.01) #%% tbd if",
"( MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH, ) from premiumFinance.financing import calculate_lender_profit, yield_curve mortality_experience",
"packages import numpy as np import pandas as pd import",
"tempfunc_f): foo.append( pool.map( tempfunc, lender_coc_value, ) ) print(f\"it took {time()",
"yield_curve mortality_experience = pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%% calculate profit rate def get_average_profitability(",
"Loan rate\", \"Lender profit\"]] = profit_columns data_frame[\"Dollar profit\"] = (",
"mortality_experience = pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%% calculate profit rate def get_average_profitability( is_level_premium=True,",
"= multiprocessing.Pool() start_time = time() foo = [] for tempfunc",
"lambda row: calculate_lender_profit( row=row, is_level_premium=is_level_premium, lapse_assumption=lapse_assumption, policyholder_rate=policyholder_rate, statutory_interest=statutory_interest, premium_markup=premium_markup, cash_interest=cash_interest,",
"get_average_profitability(lender_coc=x, lapse_assumption=True) return a def tempfunc_f(x): a, _ = get_average_profitability(lender_coc=x,",
"as np import pandas as pd import multiprocessing from time",
"np.arange(start=0.01, stop=0.2, step=0.01) #%% tbd if __name__ == \"__main__\": pool",
"= ( data_frame[\"Lender profit\"] * data_frame[\"Amount Exposed\"] ) average_profitability =",
"import json from premiumFinance.constants import ( MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH, ) from",
"PROCESSED_PROFITABILITY_PATH, ) from premiumFinance.financing import calculate_lender_profit, yield_curve mortality_experience = pd.read_excel(MORTALITY_TABLE_CLEANED_PATH)",
"return average_profitability, data_frame def tempfunc_t(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=True)",
"import calculate_lender_profit, yield_curve mortality_experience = pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%% calculate profit rate",
"pandas as pd import multiprocessing from time import time import",
"data_frame[\"Dollar profit\"].sum() / data_frame[\"Amount Exposed\"].sum() ) return average_profitability, data_frame def",
"): profit_columns = data_frame.apply( lambda row: calculate_lender_profit( row=row, is_level_premium=is_level_premium, lapse_assumption=lapse_assumption,",
"profit\"] * data_frame[\"Amount Exposed\"] ) average_profitability = ( data_frame[\"Dollar profit\"].sum()",
"for tempfunc in (tempfunc_t, tempfunc_f): foo.append( pool.map( tempfunc, lender_coc_value, )",
"step=0.01) #%% tbd if __name__ == \"__main__\": pool = multiprocessing.Pool()",
"a def tempfunc_f(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=False) return a",
"premiumFinance.constants import ( MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH, ) from premiumFinance.financing import calculate_lender_profit,",
"lender_coc_value = np.arange(start=0.01, stop=0.2, step=0.01) #%% tbd if __name__ ==",
"= pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%% calculate profit rate def get_average_profitability( is_level_premium=True, lapse_assumption=True,",
") average_profitability = ( data_frame[\"Dollar profit\"].sum() / data_frame[\"Amount Exposed\"].sum() )",
"calculate profit rate def get_average_profitability( is_level_premium=True, lapse_assumption=True, policyholder_rate=yield_curve, statutory_interest=0.035, premium_markup=0.0,",
"calculate_lender_profit, yield_curve mortality_experience = pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%% calculate profit rate def",
"calculate_lender_profit( row=row, is_level_premium=is_level_premium, lapse_assumption=lapse_assumption, policyholder_rate=policyholder_rate, statutory_interest=statutory_interest, premium_markup=premium_markup, cash_interest=cash_interest, lender_coc=lender_coc, ),",
"pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%% calculate profit rate def get_average_profitability( is_level_premium=True, lapse_assumption=True, policyholder_rate=yield_curve,",
"time import json from premiumFinance.constants import ( MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH, )",
") from premiumFinance.financing import calculate_lender_profit, yield_curve mortality_experience = pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%%",
"pool.map( tempfunc, lender_coc_value, ) ) print(f\"it took {time() - start_time}\")",
"= { \"lender_coc\": lender_coc_value.tolist(), \"profitability\": foo, } with open(PROCESSED_PROFITABILITY_PATH, \"w\")",
"axis=1, result_type=\"expand\", ) data_frame[[\"Breakeven Loan rate\", \"Lender profit\"]] = profit_columns",
") return average_profitability, data_frame def tempfunc_t(x): a, _ = get_average_profitability(lender_coc=x,",
"rate def get_average_profitability( is_level_premium=True, lapse_assumption=True, policyholder_rate=yield_curve, statutory_interest=0.035, premium_markup=0.0, cash_interest=0.001, lender_coc=0.01,",
"/ data_frame[\"Amount Exposed\"].sum() ) return average_profitability, data_frame def tempfunc_t(x): a,",
"tempfunc, lender_coc_value, ) ) print(f\"it took {time() - start_time}\") lender_profitability",
"np import pandas as pd import multiprocessing from time import",
"= data_frame.apply( lambda row: calculate_lender_profit( row=row, is_level_premium=is_level_premium, lapse_assumption=lapse_assumption, policyholder_rate=policyholder_rate, statutory_interest=statutory_interest,",
"profit\"]] = profit_columns data_frame[\"Dollar profit\"] = ( data_frame[\"Lender profit\"] *",
"tempfunc_t(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=True) return a def tempfunc_f(x):",
"== \"__main__\": pool = multiprocessing.Pool() start_time = time() foo =",
"multiprocessing from time import time import json from premiumFinance.constants import",
"data_frame.apply( lambda row: calculate_lender_profit( row=row, is_level_premium=is_level_premium, lapse_assumption=lapse_assumption, policyholder_rate=policyholder_rate, statutory_interest=statutory_interest, premium_markup=premium_markup,",
"in (tempfunc_t, tempfunc_f): foo.append( pool.map( tempfunc, lender_coc_value, ) ) print(f\"it",
") print(f\"it took {time() - start_time}\") lender_profitability = { \"lender_coc\":",
"return a def tempfunc_f(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=False) return",
"tempfunc_f(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=False) return a lender_coc_value =",
"lender_profitability = { \"lender_coc\": lender_coc_value.tolist(), \"profitability\": foo, } with open(PROCESSED_PROFITABILITY_PATH,",
"statutory_interest=0.035, premium_markup=0.0, cash_interest=0.001, lender_coc=0.01, data_frame=mortality_experience, ): profit_columns = data_frame.apply( lambda",
"data_frame[\"Lender profit\"] * data_frame[\"Amount Exposed\"] ) average_profitability = ( data_frame[\"Dollar",
"( data_frame[\"Dollar profit\"].sum() / data_frame[\"Amount Exposed\"].sum() ) return average_profitability, data_frame",
"= get_average_profitability(lender_coc=x, lapse_assumption=False) return a lender_coc_value = np.arange(start=0.01, stop=0.2, step=0.01)",
"( data_frame[\"Lender profit\"] * data_frame[\"Amount Exposed\"] ) average_profitability = (",
"lapse_assumption=lapse_assumption, policyholder_rate=policyholder_rate, statutory_interest=statutory_interest, premium_markup=premium_markup, cash_interest=cash_interest, lender_coc=lender_coc, ), axis=1, result_type=\"expand\", )",
"from premiumFinance.constants import ( MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH, ) from premiumFinance.financing import",
"time() foo = [] for tempfunc in (tempfunc_t, tempfunc_f): foo.append(",
"start_time = time() foo = [] for tempfunc in (tempfunc_t,",
"data_frame=mortality_experience, ): profit_columns = data_frame.apply( lambda row: calculate_lender_profit( row=row, is_level_premium=is_level_premium,",
"data_frame def tempfunc_t(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=True) return a",
"numpy as np import pandas as pd import multiprocessing from",
"lender_coc_value, ) ) print(f\"it took {time() - start_time}\") lender_profitability =",
"if __name__ == \"__main__\": pool = multiprocessing.Pool() start_time = time()",
"def tempfunc_f(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=False) return a lender_coc_value",
"{time() - start_time}\") lender_profitability = { \"lender_coc\": lender_coc_value.tolist(), \"profitability\": foo,",
"_ = get_average_profitability(lender_coc=x, lapse_assumption=True) return a def tempfunc_f(x): a, _",
"stop=0.2, step=0.01) #%% tbd if __name__ == \"__main__\": pool =",
"import time import json from premiumFinance.constants import ( MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH,",
"def get_average_profitability( is_level_premium=True, lapse_assumption=True, policyholder_rate=yield_curve, statutory_interest=0.035, premium_markup=0.0, cash_interest=0.001, lender_coc=0.01, data_frame=mortality_experience,",
"from time import time import json from premiumFinance.constants import (",
"#%% calculate profit rate def get_average_profitability( is_level_premium=True, lapse_assumption=True, policyholder_rate=yield_curve, statutory_interest=0.035,",
"_ = get_average_profitability(lender_coc=x, lapse_assumption=False) return a lender_coc_value = np.arange(start=0.01, stop=0.2,",
"data_frame[[\"Breakeven Loan rate\", \"Lender profit\"]] = profit_columns data_frame[\"Dollar profit\"] =",
"lender_coc=lender_coc, ), axis=1, result_type=\"expand\", ) data_frame[[\"Breakeven Loan rate\", \"Lender profit\"]]",
"foo = [] for tempfunc in (tempfunc_t, tempfunc_f): foo.append( pool.map(",
"a lender_coc_value = np.arange(start=0.01, stop=0.2, step=0.01) #%% tbd if __name__",
"profit\"].sum() / data_frame[\"Amount Exposed\"].sum() ) return average_profitability, data_frame def tempfunc_t(x):",
"Exposed\"] ) average_profitability = ( data_frame[\"Dollar profit\"].sum() / data_frame[\"Amount Exposed\"].sum()",
"#%% tbd if __name__ == \"__main__\": pool = multiprocessing.Pool() start_time",
"time import time import json from premiumFinance.constants import ( MORTALITY_TABLE_CLEANED_PATH,",
"= np.arange(start=0.01, stop=0.2, step=0.01) #%% tbd if __name__ == \"__main__\":",
"lapse_assumption=False) return a lender_coc_value = np.arange(start=0.01, stop=0.2, step=0.01) #%% tbd",
"\"lender_coc\": lender_coc_value.tolist(), \"profitability\": foo, } with open(PROCESSED_PROFITABILITY_PATH, \"w\") as outfile:",
"= [] for tempfunc in (tempfunc_t, tempfunc_f): foo.append( pool.map( tempfunc,",
"row=row, is_level_premium=is_level_premium, lapse_assumption=lapse_assumption, policyholder_rate=policyholder_rate, statutory_interest=statutory_interest, premium_markup=premium_markup, cash_interest=cash_interest, lender_coc=lender_coc, ), axis=1,",
"is_level_premium=True, lapse_assumption=True, policyholder_rate=yield_curve, statutory_interest=0.035, premium_markup=0.0, cash_interest=0.001, lender_coc=0.01, data_frame=mortality_experience, ): profit_columns",
"is_level_premium=is_level_premium, lapse_assumption=lapse_assumption, policyholder_rate=policyholder_rate, statutory_interest=statutory_interest, premium_markup=premium_markup, cash_interest=cash_interest, lender_coc=lender_coc, ), axis=1, result_type=\"expand\",",
"profit_columns = data_frame.apply( lambda row: calculate_lender_profit( row=row, is_level_premium=is_level_premium, lapse_assumption=lapse_assumption, policyholder_rate=policyholder_rate,",
"import packages import numpy as np import pandas as pd",
"\"Lender profit\"]] = profit_columns data_frame[\"Dollar profit\"] = ( data_frame[\"Lender profit\"]",
"multiprocessing.Pool() start_time = time() foo = [] for tempfunc in",
") data_frame[[\"Breakeven Loan rate\", \"Lender profit\"]] = profit_columns data_frame[\"Dollar profit\"]",
"(tempfunc_t, tempfunc_f): foo.append( pool.map( tempfunc, lender_coc_value, ) ) print(f\"it took",
"data_frame[\"Dollar profit\"] = ( data_frame[\"Lender profit\"] * data_frame[\"Amount Exposed\"] )",
"__name__ == \"__main__\": pool = multiprocessing.Pool() start_time = time() foo",
"statutory_interest=statutory_interest, premium_markup=premium_markup, cash_interest=cash_interest, lender_coc=lender_coc, ), axis=1, result_type=\"expand\", ) data_frame[[\"Breakeven Loan",
"data_frame[\"Amount Exposed\"].sum() ) return average_profitability, data_frame def tempfunc_t(x): a, _",
"foo.append( pool.map( tempfunc, lender_coc_value, ) ) print(f\"it took {time() -",
"), axis=1, result_type=\"expand\", ) data_frame[[\"Breakeven Loan rate\", \"Lender profit\"]] =",
"start_time}\") lender_profitability = { \"lender_coc\": lender_coc_value.tolist(), \"profitability\": foo, } with",
"get_average_profitability(lender_coc=x, lapse_assumption=False) return a lender_coc_value = np.arange(start=0.01, stop=0.2, step=0.01) #%%",
"def tempfunc_t(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=True) return a def",
"\"__main__\": pool = multiprocessing.Pool() start_time = time() foo = []",
"took {time() - start_time}\") lender_profitability = { \"lender_coc\": lender_coc_value.tolist(), \"profitability\":",
"premium_markup=0.0, cash_interest=0.001, lender_coc=0.01, data_frame=mortality_experience, ): profit_columns = data_frame.apply( lambda row:",
"\"profitability\": foo, } with open(PROCESSED_PROFITABILITY_PATH, \"w\") as outfile: json.dump(lender_profitability, outfile)",
"lender_coc=0.01, data_frame=mortality_experience, ): profit_columns = data_frame.apply( lambda row: calculate_lender_profit( row=row,",
"- start_time}\") lender_profitability = { \"lender_coc\": lender_coc_value.tolist(), \"profitability\": foo, }",
"lapse_assumption=True) return a def tempfunc_f(x): a, _ = get_average_profitability(lender_coc=x, lapse_assumption=False)",
"a, _ = get_average_profitability(lender_coc=x, lapse_assumption=True) return a def tempfunc_f(x): a,",
"row: calculate_lender_profit( row=row, is_level_premium=is_level_premium, lapse_assumption=lapse_assumption, policyholder_rate=policyholder_rate, statutory_interest=statutory_interest, premium_markup=premium_markup, cash_interest=cash_interest, lender_coc=lender_coc,",
"cash_interest=cash_interest, lender_coc=lender_coc, ), axis=1, result_type=\"expand\", ) data_frame[[\"Breakeven Loan rate\", \"Lender",
"policyholder_rate=policyholder_rate, statutory_interest=statutory_interest, premium_markup=premium_markup, cash_interest=cash_interest, lender_coc=lender_coc, ), axis=1, result_type=\"expand\", ) data_frame[[\"Breakeven",
"profit_columns data_frame[\"Dollar profit\"] = ( data_frame[\"Lender profit\"] * data_frame[\"Amount Exposed\"]",
"premium_markup=premium_markup, cash_interest=cash_interest, lender_coc=lender_coc, ), axis=1, result_type=\"expand\", ) data_frame[[\"Breakeven Loan rate\",",
") ) print(f\"it took {time() - start_time}\") lender_profitability = {",
"from premiumFinance.financing import calculate_lender_profit, yield_curve mortality_experience = pd.read_excel(MORTALITY_TABLE_CLEANED_PATH) #%% calculate",
"import numpy as np import pandas as pd import multiprocessing",
"import pandas as pd import multiprocessing from time import time",
"= profit_columns data_frame[\"Dollar profit\"] = ( data_frame[\"Lender profit\"] * data_frame[\"Amount",
"= ( data_frame[\"Dollar profit\"].sum() / data_frame[\"Amount Exposed\"].sum() ) return average_profitability,",
"profit\"] = ( data_frame[\"Lender profit\"] * data_frame[\"Amount Exposed\"] ) average_profitability",
"data_frame[\"Amount Exposed\"] ) average_profitability = ( data_frame[\"Dollar profit\"].sum() / data_frame[\"Amount",
"[] for tempfunc in (tempfunc_t, tempfunc_f): foo.append( pool.map( tempfunc, lender_coc_value,",
"pd import multiprocessing from time import time import json from",
"cash_interest=0.001, lender_coc=0.01, data_frame=mortality_experience, ): profit_columns = data_frame.apply( lambda row: calculate_lender_profit(",
"pool = multiprocessing.Pool() start_time = time() foo = [] for",
"lender_coc_value.tolist(), \"profitability\": foo, } with open(PROCESSED_PROFITABILITY_PATH, \"w\") as outfile: json.dump(lender_profitability,",
"MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH, ) from premiumFinance.financing import calculate_lender_profit, yield_curve mortality_experience =",
"{ \"lender_coc\": lender_coc_value.tolist(), \"profitability\": foo, } with open(PROCESSED_PROFITABILITY_PATH, \"w\") as",
"profit rate def get_average_profitability( is_level_premium=True, lapse_assumption=True, policyholder_rate=yield_curve, statutory_interest=0.035, premium_markup=0.0, cash_interest=0.001,",
"print(f\"it took {time() - start_time}\") lender_profitability = { \"lender_coc\": lender_coc_value.tolist(),",
"average_profitability = ( data_frame[\"Dollar profit\"].sum() / data_frame[\"Amount Exposed\"].sum() ) return",
"import ( MORTALITY_TABLE_CLEANED_PATH, PROCESSED_PROFITABILITY_PATH, ) from premiumFinance.financing import calculate_lender_profit, yield_curve",
"* data_frame[\"Amount Exposed\"] ) average_profitability = ( data_frame[\"Dollar profit\"].sum() /",
"get_average_profitability( is_level_premium=True, lapse_assumption=True, policyholder_rate=yield_curve, statutory_interest=0.035, premium_markup=0.0, cash_interest=0.001, lender_coc=0.01, data_frame=mortality_experience, ):"
] |
[
"dashboard.common import datastore_hooks from dashboard.common import namespaced_stored_object from dashboard.common import",
"first, and if datastore is used it unpickles. When an",
"__future__ import absolute_import import six.moves.cPickle as cPickle import datetime import",
"0 or None. \"\"\" Set(key, value, days_to_keep, datastore_hooks.EXTERNAL) @ndb.synctasklet def",
"= [entity.key for entity in entities if entity] yield (unnamespaced_future,",
"return None namespaced_key = namespaced_stored_object.NamespaceKey(key) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if",
"removals are usually caused by large changes that affect both",
"in our data being evicted. To prevent this, we cache",
"to keep is given, calculate expiration time for # the",
"stored_object.Get(key) def GetExternal(key): \"\"\"Gets the value from the datastore for",
"the value from the datastore for the externally namespaced key.\"\"\"",
"entity: return cPickle.loads(entity.value) return stored_object.Get(key) def Set(key, value, days_to_keep=None, namespace=None):",
"usually caused by large changes that affect both caches. Although",
"not intended to be used directly by other modules. \"\"\"",
"unpickles. When an item is removed from the the cache,",
"import logging from google.appengine.api import datastore_errors from google.appengine.runtime import apiproxy_errors",
"is governed by a BSD-style license that can be #",
"DeleteAsync(key): unnamespaced_future = stored_object.DeleteAsync(key) # See the comment in stored_object.DeleteAsync()",
"The key name, which will be namespaced as externally_visible. value:",
"None namespaced_key = namespaced_stored_object.NamespaceKey( key, datastore_hooks.EXTERNAL) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY)",
"processed query results in the data store. Using NDB, the",
"the datastore.\"\"\" if key is None: return None namespaced_key =",
"datastore for the externally namespaced key. Needed for things like",
"if datastore is used it unpickles. When an item is",
"namespace): return ndb.Key(cls.__name__, namespaced_stored_object.NamespaceKey(key, namespace)) @classmethod def GetExpiredKeys(cls): \"\"\"Gets keys",
"the datastore.\"\"\" yield DeleteAsync(key) @ndb.tasklet def DeleteAsync(key): unnamespaced_future = stored_object.DeleteAsync(key)",
"results in memcache and datastore. Memcache is not very reliable",
"data store entity with the key and a BlobProperty with",
"datastore. Memcache is not very reliable for the perf dashboard.",
"datastore for the externally namespaced key.\"\"\" if key is None:",
"the value in the datastore for the externally namespaced key.",
"= namespaced_stored_object.NamespaceKey(key, namespace) try: CachedPickledString( id=namespaced_key, value=cPickle.dumps(value), expire_time=expire_time).put() except datastore_errors.BadRequestError",
"value in the datastore. Args: key: The key name, which",
"be namespaced. value: The value to set. days_to_keep: Number of",
"LRU and shared between multiple applications, so their activity may",
"has a single BlobProperty is much quicker than a complex",
"\"\"\"Gets the value from the datastore.\"\"\" if key is None:",
"and store it in datastore. # Once the entity expires,",
"cPickle import datetime import logging from google.appengine.api import datastore_errors from",
"ndb.BlobProperty() expire_time = ndb.DateTimeProperty() @classmethod def NamespacedKey(cls, key, namespace): return",
"None namespaced_key = namespaced_stored_object.NamespaceKey(key) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity:",
"code is governed by a BSD-style license that can be",
"When number of days to keep is given, calculate expiration",
"days_to_keep, datastore_hooks.EXTERNAL) @ndb.synctasklet def Delete(key): \"\"\"Clears the value from the",
"datastore.\"\"\" yield DeleteAsync(key) @ndb.tasklet def DeleteAsync(key): unnamespaced_future = stored_object.DeleteAsync(key) #",
"cached in memcache if possible. This improves performance because doing",
"external caches, since removals are usually caused by large changes",
"the datastore for the externally namespaced key.\"\"\" if key is",
"def DeleteAsync(key): unnamespaced_future = stored_object.DeleteAsync(key) # See the comment in",
"The key name, which will be namespaced. value: The value",
"= cls.query(cls.expire_time < current_time) query = query.filter(cls.expire_time != None) return",
"governed by a BSD-style license that can be # found",
"def Set(key, value, days_to_keep=None, namespace=None): \"\"\"Sets the value in the",
"Use of this source code is governed by a BSD-style",
"may result in our data being evicted. To prevent this,",
"a single BlobProperty is much quicker than a complex query",
"value) def SetExternal(key, value, days_to_keep=None): \"\"\"Sets the value in the",
"return cPickle.loads(entity.value) return stored_object.Get(key) def GetExternal(key): \"\"\"Gets the value from",
"affect both caches. Although this module contains ndb.Model classes, these",
"namespace, otherwise namespace will be retrieved using datastore_hooks.GetNamespace(). \"\"\" #",
"except apiproxy_errors.RequestTooLargeError as e: stored_object.Set(key, value) def SetExternal(key, value, days_to_keep=None):",
"module contains ndb.Model classes, these are not intended to be",
"0 or None. namespace: Optional namespace, otherwise namespace will be",
"perf dashboard. Prometheus team explained that memcache is LRU and",
"@classmethod def GetExpiredKeys(cls): \"\"\"Gets keys of expired entities. Returns: List",
"if possible. This improves performance because doing a get() for",
"= namespaced_stored_object.NamespaceKey(key) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value)",
"days_to_keep=None, namespace=None): \"\"\"Sets the value in the datastore. Args: key:",
"value: The value to set. days_to_keep: Number of days to",
"namespaced key. Needed for things like /add_point that update internal/external",
"which has a single BlobProperty is much quicker than a",
"and external caches, since removals are usually caused by large",
"query = cls.query(cls.expire_time < current_time) query = query.filter(cls.expire_time != None)",
"namespaced_stored_object.NamespaceKey(key, namespace) try: CachedPickledString( id=namespaced_key, value=cPickle.dumps(value), expire_time=expire_time).put() except datastore_errors.BadRequestError as",
"= datetime.datetime.now() query = cls.query(cls.expire_time < current_time) query = query.filter(cls.expire_time",
"Prometheus team explained that memcache is LRU and shared between",
"the externally namespaced key.\"\"\" if key is None: return None",
"namespaced_key = namespaced_stored_object.NamespaceKey( key, datastore_hooks.EXTERNAL) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if",
"performance because doing a get() for a key which has",
"other modules. \"\"\" from __future__ import print_function from __future__ import",
"be used directly by other modules. \"\"\" from __future__ import",
"import six.moves.cPickle as cPickle import datetime import logging from google.appengine.api",
"import ndb from dashboard.common import datastore_hooks from dashboard.common import namespaced_stored_object",
"calculate expiration time for # the entity and store it",
"based on whether datastore_hooks says the request is internal_only. 2)",
"is internal_only. 2) Pickles the value (memcache does this internally),",
"@classmethod def NamespacedKey(cls, key, namespace): return ndb.Key(cls.__name__, namespaced_stored_object.NamespaceKey(key, namespace)) @classmethod",
"same time. Args: key: The key name, which will be",
"# the entity and store it in datastore. # Once",
"team explained that memcache is LRU and shared between multiple",
"caches. Although this module contains ndb.Model classes, these are not",
"to set. days_to_keep: Number of days to keep entity in",
"datastore_hooks.INTERNAL), CachedPickledString.NamespacedKey(key, datastore_hooks.EXTERNAL), ]) keys = [entity.key for entity in",
"(memcache does this internally), and adds a data store entity",
"in the LICENSE file. \"\"\"Caches processed query results in memcache",
"the cache, it is removed from both internal and external",
"= namespaced_stored_object.NamespaceKey( key, datastore_hooks.EXTERNAL) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity:",
"datastore_errors.BadRequestError as e: logging.warning('BadRequestError for key %s: %s', key, e)",
"in datastore. # Once the entity expires, it will be",
"so their activity may result in our data being evicted.",
"will be retrieved using datastore_hooks.GetNamespace(). \"\"\" # When number of",
"to be used directly by other modules. \"\"\" from __future__",
"the comment in stored_object.DeleteAsync() about this get(). entities = yield",
"Args: key: The key name, which will be namespaced as",
"rights reserved. # Use of this source code is governed",
"internal/external data at the same time. Args: key: The key",
"activity may result in our data being evicted. To prevent",
"dataset. (Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When an item is cached, layered_cache does",
"and a BlobProperty with the pickled value. Retrieving values checks",
"checks memcache via NDB first, and if datastore is used",
"memcache and datastore. Memcache is not very reliable for the",
"directly by other modules. \"\"\" from __future__ import print_function from",
"internally), and adds a data store entity with the key",
"in the datastore. Args: key: The key name, which will",
"Args: key: The key name, which will be namespaced. value:",
"entities if entity] yield (unnamespaced_future, ndb.delete_multi_async(keys)) def DeleteAllExpiredEntities(): \"\"\"Deletes all",
"entity and store it in datastore. # Once the entity",
"\"\"\"Gets keys of expired entities. Returns: List of keys for",
"days_to_keep: Number of days to keep entity in datastore, default",
"expire when this value is 0 or None. namespace: Optional",
"store it in datastore. # Once the entity expires, it",
"be namespaced as externally_visible. value: The value to set. days_to_keep:",
"values checks memcache via NDB first, and if datastore is",
"if entity] yield (unnamespaced_future, ndb.delete_multi_async(keys)) def DeleteAllExpiredEntities(): \"\"\"Deletes all expired",
"%s', key, e) except apiproxy_errors.RequestTooLargeError as e: stored_object.Set(key, value) def",
"datetime.datetime.now() + datetime.timedelta( days=days_to_keep) namespaced_key = namespaced_stored_object.NamespaceKey(key, namespace) try: CachedPickledString(",
"value is 0 or None. \"\"\" Set(key, value, days_to_keep, datastore_hooks.EXTERNAL)",
"if key is None: return None namespaced_key = namespaced_stored_object.NamespaceKey( key,",
"namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return stored_object.Get(key) def GetExternal(key): \"\"\"Gets",
"in the data store. Using NDB, the values are also",
"data at the same time. Args: key: The key name,",
"return ndb.Key(cls.__name__, namespaced_stored_object.NamespaceKey(key, namespace)) @classmethod def GetExpiredKeys(cls): \"\"\"Gets keys of",
"the key and a BlobProperty with the pickled value. Retrieving",
"item is cached, layered_cache does the following: 1) Namespaces the",
"externally namespaced key. Needed for things like /add_point that update",
"can be # found in the LICENSE file. \"\"\"Caches processed",
"the following: 1) Namespaces the key based on whether datastore_hooks",
"for key %s: %s', key, e) except apiproxy_errors.RequestTooLargeError as e:",
"a data store entity with the key and a BlobProperty",
"import datastore_errors from google.appengine.runtime import apiproxy_errors from google.appengine.ext import ndb",
"import absolute_import import six.moves.cPickle as cPickle import datetime import logging",
"from the datastore. expire_time = None if days_to_keep: expire_time =",
"Copyright 2018 The Chromium Authors. All rights reserved. # Use",
"Returns: List of keys for items which are expired. \"\"\"",
"\"\"\" current_time = datetime.datetime.now() query = cls.query(cls.expire_time < current_time) query",
"expire_time = datetime.datetime.now() + datetime.timedelta( days=days_to_keep) namespaced_key = namespaced_stored_object.NamespaceKey(key, namespace)",
"\"\"\"Clears the value from the datastore.\"\"\" yield DeleteAsync(key) @ndb.tasklet def",
"entity: return cPickle.loads(entity.value) return stored_object.Get(key) def GetExternal(key): \"\"\"Gets the value",
"ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return stored_object.Get(key) def Set(key,",
"from google.appengine.runtime import apiproxy_errors from google.appengine.ext import ndb from dashboard.common",
"namespaced as externally_visible. value: The value to set. days_to_keep: Number",
"from __future__ import print_function from __future__ import division from __future__",
"= None if days_to_keep: expire_time = datetime.datetime.now() + datetime.timedelta( days=days_to_keep)",
"license that can be # found in the LICENSE file.",
"comment in stored_object.DeleteAsync() about this get(). entities = yield ndb.get_multi_async([",
"print_function from __future__ import division from __future__ import absolute_import import",
"@ndb.tasklet def DeleteAsync(key): unnamespaced_future = stored_object.DeleteAsync(key) # See the comment",
"2) Pickles the value (memcache does this internally), and adds",
"namespaced_stored_object from dashboard.common import stored_object class CachedPickledString(ndb.Model): value = ndb.BlobProperty()",
"Entity will not expire when this value is 0 or",
"except datastore_errors.BadRequestError as e: logging.warning('BadRequestError for key %s: %s', key,",
"removed from both internal and external caches, since removals are",
"be retrieved using datastore_hooks.GetNamespace(). \"\"\" # When number of days",
"this internally), and adds a data store entity with the",
"doing a get() for a key which has a single",
"(unnamespaced_future, ndb.delete_multi_async(keys)) def DeleteAllExpiredEntities(): \"\"\"Deletes all expired entities from the",
"NDB first, and if datastore is used it unpickles. When",
"name, which will be namespaced as externally_visible. value: The value",
"the value from the datastore.\"\"\" yield DeleteAsync(key) @ndb.tasklet def DeleteAsync(key):",
"very reliable for the perf dashboard. Prometheus team explained that",
"the request is internal_only. 2) Pickles the value (memcache does",
"key is None: return None namespaced_key = namespaced_stored_object.NamespaceKey( key, datastore_hooks.EXTERNAL)",
"BSD-style license that can be # found in the LICENSE",
"# Use of this source code is governed by a",
"for items which are expired. \"\"\" current_time = datetime.datetime.now() query",
"# found in the LICENSE file. \"\"\"Caches processed query results",
"for things like /add_point that update internal/external data at the",
"datastore. expire_time = None if days_to_keep: expire_time = datetime.datetime.now() +",
"that update internal/external data at the same time. Args: key:",
"dashboard. Prometheus team explained that memcache is LRU and shared",
"Optional namespace, otherwise namespace will be retrieved using datastore_hooks.GetNamespace(). \"\"\"",
"BlobProperty is much quicker than a complex query over a",
"from __future__ import division from __future__ import absolute_import import six.moves.cPickle",
"= yield ndb.get_multi_async([ CachedPickledString.NamespacedKey(key, datastore_hooks.INTERNAL), CachedPickledString.NamespacedKey(key, datastore_hooks.EXTERNAL), ]) keys =",
"is 0 or None. \"\"\" Set(key, value, days_to_keep, datastore_hooks.EXTERNAL) @ndb.synctasklet",
"says the request is internal_only. 2) Pickles the value (memcache",
"key, datastore_hooks.EXTERNAL) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value)",
"e: stored_object.Set(key, value) def SetExternal(key, value, days_to_keep=None): \"\"\"Sets the value",
"entities. Returns: List of keys for items which are expired.",
"value=cPickle.dumps(value), expire_time=expire_time).put() except datastore_errors.BadRequestError as e: logging.warning('BadRequestError for key %s:",
"BlobProperty with the pickled value. Retrieving values checks memcache via",
"from the datastore.\"\"\" yield DeleteAsync(key) @ndb.tasklet def DeleteAsync(key): unnamespaced_future =",
"over a large dataset. (Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When an item is",
"ndb.delete_multi_async(keys)) def DeleteAllExpiredEntities(): \"\"\"Deletes all expired entities from the datastore.\"\"\"",
"cls.query(cls.expire_time < current_time) query = query.filter(cls.expire_time != None) return query.fetch(keys_only=True)",
"between multiple applications, so their activity may result in our",
"a BSD-style license that can be # found in the",
"when this value is 0 or None. namespace: Optional namespace,",
"days=days_to_keep) namespaced_key = namespaced_stored_object.NamespaceKey(key, namespace) try: CachedPickledString( id=namespaced_key, value=cPickle.dumps(value), expire_time=expire_time).put()",
"namespace: Optional namespace, otherwise namespace will be retrieved using datastore_hooks.GetNamespace().",
"the datastore for the externally namespaced key. Needed for things",
"datastore_hooks from dashboard.common import namespaced_stored_object from dashboard.common import stored_object class",
"a large dataset. (Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When an item is cached,",
"Retrieving values checks memcache via NDB first, and if datastore",
"keep entity in datastore, default is None. Entity will not",
"value. Retrieving values checks memcache via NDB first, and if",
"the pickled value. Retrieving values checks memcache via NDB first,",
"we cache processed query results in the data store. Using",
"by other modules. \"\"\" from __future__ import print_function from __future__",
"it unpickles. When an item is removed from the the",
"is LRU and shared between multiple applications, so their activity",
"namespaced_key = namespaced_stored_object.NamespaceKey(key) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return",
"return cPickle.loads(entity.value) return stored_object.Get(key) def Set(key, value, days_to_keep=None, namespace=None): \"\"\"Sets",
"item is removed from the the cache, it is removed",
"%s: %s', key, e) except apiproxy_errors.RequestTooLargeError as e: stored_object.Set(key, value)",
"datastore. # Once the entity expires, it will be deleted",
"import apiproxy_errors from google.appengine.ext import ndb from dashboard.common import datastore_hooks",
"return None namespaced_key = namespaced_stored_object.NamespaceKey( key, datastore_hooks.EXTERNAL) entity = ndb.Key('CachedPickledString',",
"import stored_object class CachedPickledString(ndb.Model): value = ndb.BlobProperty() expire_time = ndb.DateTimeProperty()",
"the externally namespaced key. Needed for things like /add_point that",
"deleted from the datastore. expire_time = None if days_to_keep: expire_time",
"at the same time. Args: key: The key name, which",
"from google.appengine.api import datastore_errors from google.appengine.runtime import apiproxy_errors from google.appengine.ext",
"applications, so their activity may result in our data being",
"@ndb.synctasklet def Delete(key): \"\"\"Clears the value from the datastore.\"\"\" yield",
"which will be namespaced as externally_visible. value: The value to",
"query = query.filter(cls.expire_time != None) return query.fetch(keys_only=True) def Get(key): \"\"\"Gets",
"explained that memcache is LRU and shared between multiple applications,",
"CachedPickledString( id=namespaced_key, value=cPickle.dumps(value), expire_time=expire_time).put() except datastore_errors.BadRequestError as e: logging.warning('BadRequestError for",
"NDB, the values are also cached in memcache if possible.",
"prevent this, we cache processed query results in the data",
"is removed from both internal and external caches, since removals",
"ndb.Key(cls.__name__, namespaced_stored_object.NamespaceKey(key, namespace)) @classmethod def GetExpiredKeys(cls): \"\"\"Gets keys of expired",
"__future__ import print_function from __future__ import division from __future__ import",
"store entity with the key and a BlobProperty with the",
"stored_object.DeleteAsync() about this get(). entities = yield ndb.get_multi_async([ CachedPickledString.NamespacedKey(key, datastore_hooks.INTERNAL),",
"cache, it is removed from both internal and external caches,",
"the perf dashboard. Prometheus team explained that memcache is LRU",
"GetExternal(key): \"\"\"Gets the value from the datastore for the externally",
"value, days_to_keep=None, namespace=None): \"\"\"Sets the value in the datastore. Args:",
"namespaced_stored_object.NamespaceKey( key, datastore_hooks.EXTERNAL) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return",
"an item is cached, layered_cache does the following: 1) Namespaces",
"key and a BlobProperty with the pickled value. Retrieving values",
"given, calculate expiration time for # the entity and store",
"dashboard.common import namespaced_stored_object from dashboard.common import stored_object class CachedPickledString(ndb.Model): value",
"caused by large changes that affect both caches. Although this",
"memcache via NDB first, and if datastore is used it",
"this value is 0 or None. namespace: Optional namespace, otherwise",
"used it unpickles. When an item is removed from the",
"dashboard.common import stored_object class CachedPickledString(ndb.Model): value = ndb.BlobProperty() expire_time =",
"CachedPickledString(ndb.Model): value = ndb.BlobProperty() expire_time = ndb.DateTimeProperty() @classmethod def NamespacedKey(cls,",
"than a complex query over a large dataset. (Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ)",
"= ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return stored_object.Get(key) def",
"namespaced_stored_object.NamespaceKey(key) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return",
"datetime.datetime.now() query = cls.query(cls.expire_time < current_time) query = query.filter(cls.expire_time !=",
"our data being evicted. To prevent this, we cache processed",
"externally namespaced key.\"\"\" if key is None: return None namespaced_key",
"both caches. Although this module contains ndb.Model classes, these are",
"datastore_hooks.EXTERNAL), ]) keys = [entity.key for entity in entities if",
"value = ndb.BlobProperty() expire_time = ndb.DateTimeProperty() @classmethod def NamespacedKey(cls, key,",
"unnamespaced_future = stored_object.DeleteAsync(key) # See the comment in stored_object.DeleteAsync() about",
"Although this module contains ndb.Model classes, these are not intended",
"entity] yield (unnamespaced_future, ndb.delete_multi_async(keys)) def DeleteAllExpiredEntities(): \"\"\"Deletes all expired entities",
"\"\"\" Set(key, value, days_to_keep, datastore_hooks.EXTERNAL) @ndb.synctasklet def Delete(key): \"\"\"Clears the",
"results in the data store. Using NDB, the values are",
"key, namespace): return ndb.Key(cls.__name__, namespaced_stored_object.NamespaceKey(key, namespace)) @classmethod def GetExpiredKeys(cls): \"\"\"Gets",
"absolute_import import six.moves.cPickle as cPickle import datetime import logging from",
"id=namespaced_key, value=cPickle.dumps(value), expire_time=expire_time).put() except datastore_errors.BadRequestError as e: logging.warning('BadRequestError for key",
"in memcache and datastore. Memcache is not very reliable for",
"being evicted. To prevent this, we cache processed query results",
"query.filter(cls.expire_time != None) return query.fetch(keys_only=True) def Get(key): \"\"\"Gets the value",
"def GetExpiredKeys(cls): \"\"\"Gets keys of expired entities. Returns: List of",
"datetime.timedelta( days=days_to_keep) namespaced_key = namespaced_stored_object.NamespaceKey(key, namespace) try: CachedPickledString( id=namespaced_key, value=cPickle.dumps(value),",
"def Delete(key): \"\"\"Clears the value from the datastore.\"\"\" yield DeleteAsync(key)",
"possible. This improves performance because doing a get() for a",
"namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return stored_object.Get(key) def Set(key, value,",
"the data store. Using NDB, the values are also cached",
"this source code is governed by a BSD-style license that",
"return stored_object.Get(key) def GetExternal(key): \"\"\"Gets the value from the datastore",
"externally_visible. value: The value to set. days_to_keep: Number of days",
"= stored_object.DeleteAsync(key) # See the comment in stored_object.DeleteAsync() about this",
"much quicker than a complex query over a large dataset.",
"from google.appengine.ext import ndb from dashboard.common import datastore_hooks from dashboard.common",
"\"\"\"Gets the value from the datastore for the externally namespaced",
"in entities if entity] yield (unnamespaced_future, ndb.delete_multi_async(keys)) def DeleteAllExpiredEntities(): \"\"\"Deletes",
"caches, since removals are usually caused by large changes that",
"of keys for items which are expired. \"\"\" current_time =",
"like /add_point that update internal/external data at the same time.",
"get(). entities = yield ndb.get_multi_async([ CachedPickledString.NamespacedKey(key, datastore_hooks.INTERNAL), CachedPickledString.NamespacedKey(key, datastore_hooks.EXTERNAL), ])",
"and adds a data store entity with the key and",
"expired entities. Returns: List of keys for items which are",
"datastore_hooks.EXTERNAL) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return",
"ndb.get_multi_async([ CachedPickledString.NamespacedKey(key, datastore_hooks.INTERNAL), CachedPickledString.NamespacedKey(key, datastore_hooks.EXTERNAL), ]) keys = [entity.key for",
"google.appengine.ext import ndb from dashboard.common import datastore_hooks from dashboard.common import",
"SetExternal(key, value, days_to_keep=None): \"\"\"Sets the value in the datastore for",
"source code is governed by a BSD-style license that can",
"days to keep is given, calculate expiration time for #",
"Authors. All rights reserved. # Use of this source code",
"query over a large dataset. (Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When an item",
"and shared between multiple applications, so their activity may result",
"= query.filter(cls.expire_time != None) return query.fetch(keys_only=True) def Get(key): \"\"\"Gets the",
"key based on whether datastore_hooks says the request is internal_only.",
"import print_function from __future__ import division from __future__ import absolute_import",
"days to keep entity in datastore, default is None. Entity",
"be deleted from the datastore. expire_time = None if days_to_keep:",
"with the pickled value. Retrieving values checks memcache via NDB",
"the LICENSE file. \"\"\"Caches processed query results in memcache and",
"logging from google.appengine.api import datastore_errors from google.appengine.runtime import apiproxy_errors from",
"namespaced key.\"\"\" if key is None: return None namespaced_key =",
"None. Entity will not expire when this value is 0",
"def NamespacedKey(cls, key, namespace): return ndb.Key(cls.__name__, namespaced_stored_object.NamespaceKey(key, namespace)) @classmethod def",
"of days to keep entity in datastore, default is None.",
"key, e) except apiproxy_errors.RequestTooLargeError as e: stored_object.Set(key, value) def SetExternal(key,",
"To prevent this, we cache processed query results in the",
"is given, calculate expiration time for # the entity and",
"update internal/external data at the same time. Args: key: The",
"entity with the key and a BlobProperty with the pickled",
"an item is removed from the the cache, it is",
"= datetime.datetime.now() + datetime.timedelta( days=days_to_keep) namespaced_key = namespaced_stored_object.NamespaceKey(key, namespace) try:",
"quicker than a complex query over a large dataset. (Background:",
"are usually caused by large changes that affect both caches.",
"value, days_to_keep=None): \"\"\"Sets the value in the datastore for the",
"set. days_to_keep: Number of days to keep entity in datastore,",
"CachedPickledString.NamespacedKey(key, datastore_hooks.EXTERNAL), ]) keys = [entity.key for entity in entities",
"yield (unnamespaced_future, ndb.delete_multi_async(keys)) def DeleteAllExpiredEntities(): \"\"\"Deletes all expired entities from",
"CachedPickledString.NamespacedKey(key, datastore_hooks.INTERNAL), CachedPickledString.NamespacedKey(key, datastore_hooks.EXTERNAL), ]) keys = [entity.key for entity",
"will not expire when this value is 0 or None.",
"the value (memcache does this internally), and adds a data",
"in stored_object.DeleteAsync() about this get(). entities = yield ndb.get_multi_async([ CachedPickledString.NamespacedKey(key,",
"that affect both caches. Although this module contains ndb.Model classes,",
"a get() for a key which has a single BlobProperty",
"Delete(key): \"\"\"Clears the value from the datastore.\"\"\" yield DeleteAsync(key) @ndb.tasklet",
"of this source code is governed by a BSD-style license",
"/add_point that update internal/external data at the same time. Args:",
"import namespaced_stored_object from dashboard.common import stored_object class CachedPickledString(ndb.Model): value =",
"which will be namespaced. value: The value to set. days_to_keep:",
"these are not intended to be used directly by other",
"datastore.\"\"\" if key is None: return None namespaced_key = namespaced_stored_object.NamespaceKey(key)",
"None: return None namespaced_key = namespaced_stored_object.NamespaceKey(key) entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY)",
"result in our data being evicted. To prevent this, we",
"will be namespaced. value: The value to set. days_to_keep: Number",
"reserved. # Use of this source code is governed by",
"are also cached in memcache if possible. This improves performance",
"stored_object.DeleteAsync(key) # See the comment in stored_object.DeleteAsync() about this get().",
"key.\"\"\" if key is None: return None namespaced_key = namespaced_stored_object.NamespaceKey(",
"Needed for things like /add_point that update internal/external data at",
"using datastore_hooks.GetNamespace(). \"\"\" # When number of days to keep",
"apiproxy_errors.RequestTooLargeError as e: stored_object.Set(key, value) def SetExternal(key, value, days_to_keep=None): \"\"\"Sets",
"is None: return None namespaced_key = namespaced_stored_object.NamespaceKey(key) entity = ndb.Key('CachedPickledString',",
"with the key and a BlobProperty with the pickled value.",
"yield DeleteAsync(key) @ndb.tasklet def DeleteAsync(key): unnamespaced_future = stored_object.DeleteAsync(key) # See",
"http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When an item is cached, layered_cache does the following:",
"value, days_to_keep, datastore_hooks.EXTERNAL) @ndb.synctasklet def Delete(key): \"\"\"Clears the value from",
"None) return query.fetch(keys_only=True) def Get(key): \"\"\"Gets the value from the",
"logging.warning('BadRequestError for key %s: %s', key, e) except apiproxy_errors.RequestTooLargeError as",
"is removed from the the cache, it is removed from",
"ndb from dashboard.common import datastore_hooks from dashboard.common import namespaced_stored_object from",
"stored_object class CachedPickledString(ndb.Model): value = ndb.BlobProperty() expire_time = ndb.DateTimeProperty() @classmethod",
"namespace will be retrieved using datastore_hooks.GetNamespace(). \"\"\" # When number",
"be # found in the LICENSE file. \"\"\"Caches processed query",
"are not intended to be used directly by other modules.",
"or None. namespace: Optional namespace, otherwise namespace will be retrieved",
"class CachedPickledString(ndb.Model): value = ndb.BlobProperty() expire_time = ndb.DateTimeProperty() @classmethod def",
"return query.fetch(keys_only=True) def Get(key): \"\"\"Gets the value from the datastore.\"\"\"",
"entity = ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return stored_object.Get(key)",
"cPickle.loads(entity.value) return stored_object.Get(key) def Set(key, value, days_to_keep=None, namespace=None): \"\"\"Sets the",
"GetExpiredKeys(cls): \"\"\"Gets keys of expired entities. Returns: List of keys",
"<reponame>BearerPipelineTest/catapult<gh_stars>0 # Copyright 2018 The Chromium Authors. All rights reserved.",
"is 0 or None. namespace: Optional namespace, otherwise namespace will",
"NamespacedKey(cls, key, namespace): return ndb.Key(cls.__name__, namespaced_stored_object.NamespaceKey(key, namespace)) @classmethod def GetExpiredKeys(cls):",
"if entity: return cPickle.loads(entity.value) return stored_object.Get(key) def GetExternal(key): \"\"\"Gets the",
"evicted. To prevent this, we cache processed query results in",
"cached, layered_cache does the following: 1) Namespaces the key based",
"name, which will be namespaced. value: The value to set.",
"not very reliable for the perf dashboard. Prometheus team explained",
"reliable for the perf dashboard. Prometheus team explained that memcache",
"datastore_errors from google.appengine.runtime import apiproxy_errors from google.appengine.ext import ndb from",
"for the perf dashboard. Prometheus team explained that memcache is",
"!= None) return query.fetch(keys_only=True) def Get(key): \"\"\"Gets the value from",
"DeleteAsync(key) @ndb.tasklet def DeleteAsync(key): unnamespaced_future = stored_object.DeleteAsync(key) # See the",
"expire_time = ndb.DateTimeProperty() @classmethod def NamespacedKey(cls, key, namespace): return ndb.Key(cls.__name__,",
"from __future__ import absolute_import import six.moves.cPickle as cPickle import datetime",
"a BlobProperty with the pickled value. Retrieving values checks memcache",
"default is None. Entity will not expire when this value",
"the key based on whether datastore_hooks says the request is",
"processed query results in memcache and datastore. Memcache is not",
"pickled value. Retrieving values checks memcache via NDB first, and",
"None if days_to_keep: expire_time = datetime.datetime.now() + datetime.timedelta( days=days_to_keep) namespaced_key",
"google.appengine.api import datastore_errors from google.appengine.runtime import apiproxy_errors from google.appengine.ext import",
"in datastore, default is None. Entity will not expire when",
"value from the datastore for the externally namespaced key.\"\"\" if",
"the datastore. expire_time = None if days_to_keep: expire_time = datetime.datetime.now()",
"namespaced_key = namespaced_stored_object.NamespaceKey(key, namespace) try: CachedPickledString( id=namespaced_key, value=cPickle.dumps(value), expire_time=expire_time).put() except",
"number of days to keep is given, calculate expiration time",
"a key which has a single BlobProperty is much quicker",
"LICENSE file. \"\"\"Caches processed query results in memcache and datastore.",
"query results in memcache and datastore. Memcache is not very",
"the values are also cached in memcache if possible. This",
"from both internal and external caches, since removals are usually",
"namespace) try: CachedPickledString( id=namespaced_key, value=cPickle.dumps(value), expire_time=expire_time).put() except datastore_errors.BadRequestError as e:",
"from the datastore for the externally namespaced key.\"\"\" if key",
"None: return None namespaced_key = namespaced_stored_object.NamespaceKey( key, datastore_hooks.EXTERNAL) entity =",
"values are also cached in memcache if possible. This improves",
"from the the cache, it is removed from both internal",
"large dataset. (Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When an item is cached, layered_cache",
"yield ndb.get_multi_async([ CachedPickledString.NamespacedKey(key, datastore_hooks.INTERNAL), CachedPickledString.NamespacedKey(key, datastore_hooks.EXTERNAL), ]) keys = [entity.key",
"expire_time = None if days_to_keep: expire_time = datetime.datetime.now() + datetime.timedelta(",
"is much quicker than a complex query over a large",
"< current_time) query = query.filter(cls.expire_time != None) return query.fetch(keys_only=True) def",
"\"\"\" # When number of days to keep is given,",
"def GetExternal(key): \"\"\"Gets the value from the datastore for the",
"# Once the entity expires, it will be deleted from",
"for entity in entities if entity] yield (unnamespaced_future, ndb.delete_multi_async(keys)) def",
"stored_object.Get(key) def Set(key, value, days_to_keep=None, namespace=None): \"\"\"Sets the value in",
"internal_only. 2) Pickles the value (memcache does this internally), and",
"retrieved using datastore_hooks.GetNamespace(). \"\"\" # When number of days to",
"used directly by other modules. \"\"\" from __future__ import print_function",
"that memcache is LRU and shared between multiple applications, so",
"List of keys for items which are expired. \"\"\" current_time",
"Set(key, value, days_to_keep=None, namespace=None): \"\"\"Sets the value in the datastore.",
"as externally_visible. value: The value to set. days_to_keep: Number of",
"layered_cache does the following: 1) Namespaces the key based on",
"days_to_keep: expire_time = datetime.datetime.now() + datetime.timedelta( days=days_to_keep) namespaced_key = namespaced_stored_object.NamespaceKey(key,",
"See the comment in stored_object.DeleteAsync() about this get(). entities =",
"key is None: return None namespaced_key = namespaced_stored_object.NamespaceKey(key) entity =",
"division from __future__ import absolute_import import six.moves.cPickle as cPickle import",
"the value in the datastore. Args: key: The key name,",
"= ndb.BlobProperty() expire_time = ndb.DateTimeProperty() @classmethod def NamespacedKey(cls, key, namespace):",
"namespace=None): \"\"\"Sets the value in the datastore. Args: key: The",
"key which has a single BlobProperty is much quicker than",
"the the cache, it is removed from both internal and",
"days_to_keep=None): \"\"\"Sets the value in the datastore for the externally",
"keys for items which are expired. \"\"\" current_time = datetime.datetime.now()",
"expired. \"\"\" current_time = datetime.datetime.now() query = cls.query(cls.expire_time < current_time)",
"(Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When an item is cached, layered_cache does the",
"in memcache if possible. This improves performance because doing a",
"for # the entity and store it in datastore. #",
"Set(key, value, days_to_keep, datastore_hooks.EXTERNAL) @ndb.synctasklet def Delete(key): \"\"\"Clears the value",
"value from the datastore.\"\"\" if key is None: return None",
"None. namespace: Optional namespace, otherwise namespace will be retrieved using",
"for the externally namespaced key. Needed for things like /add_point",
"# Copyright 2018 The Chromium Authors. All rights reserved. #",
"This improves performance because doing a get() for a key",
"datastore_hooks.EXTERNAL) @ndb.synctasklet def Delete(key): \"\"\"Clears the value from the datastore.\"\"\"",
"internal and external caches, since removals are usually caused by",
"this, we cache processed query results in the data store.",
"not expire when this value is 0 or None. \"\"\"",
"value is 0 or None. namespace: Optional namespace, otherwise namespace",
"classes, these are not intended to be used directly by",
"stored_object.Set(key, value) def SetExternal(key, value, days_to_keep=None): \"\"\"Sets the value in",
"will be namespaced as externally_visible. value: The value to set.",
"\"\"\"Sets the value in the datastore. Args: key: The key",
"and datastore. Memcache is not very reliable for the perf",
"the same time. Args: key: The key name, which will",
"value to set. days_to_keep: Number of days to keep entity",
"e) except apiproxy_errors.RequestTooLargeError as e: stored_object.Set(key, value) def SetExternal(key, value,",
"single BlobProperty is much quicker than a complex query over",
"data being evicted. To prevent this, we cache processed query",
"namespace)) @classmethod def GetExpiredKeys(cls): \"\"\"Gets keys of expired entities. Returns:",
"cache processed query results in the data store. Using NDB,",
"return stored_object.Get(key) def Set(key, value, days_to_keep=None, namespace=None): \"\"\"Sets the value",
"def DeleteAllExpiredEntities(): \"\"\"Deletes all expired entities from the datastore.\"\"\" ndb.delete_multi(CachedPickledString.GetExpiredKeys())",
"is cached, layered_cache does the following: 1) Namespaces the key",
"datastore is used it unpickles. When an item is removed",
"the value from the datastore.\"\"\" if key is None: return",
"the entity and store it in datastore. # Once the",
"# See the comment in stored_object.DeleteAsync() about this get(). entities",
"contains ndb.Model classes, these are not intended to be used",
"six.moves.cPickle as cPickle import datetime import logging from google.appengine.api import",
"will be deleted from the datastore. expire_time = None if",
"multiple applications, so their activity may result in our data",
"request is internal_only. 2) Pickles the value (memcache does this",
"value in the datastore for the externally namespaced key. Needed",
"complex query over a large dataset. (Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When an",
"by large changes that affect both caches. Although this module",
"by a BSD-style license that can be # found in",
"import datastore_hooks from dashboard.common import namespaced_stored_object from dashboard.common import stored_object",
"whether datastore_hooks says the request is internal_only. 2) Pickles the",
"items which are expired. \"\"\" current_time = datetime.datetime.now() query =",
"datastore_hooks says the request is internal_only. 2) Pickles the value",
"expires, it will be deleted from the datastore. expire_time =",
"their activity may result in our data being evicted. To",
"shared between multiple applications, so their activity may result in",
"modules. \"\"\" from __future__ import print_function from __future__ import division",
"datastore. Args: key: The key name, which will be namespaced.",
"def SetExternal(key, value, days_to_keep=None): \"\"\"Sets the value in the datastore",
"2018 The Chromium Authors. All rights reserved. # Use of",
"The Chromium Authors. All rights reserved. # Use of this",
"things like /add_point that update internal/external data at the same",
"does this internally), and adds a data store entity with",
"in the datastore for the externally namespaced key. Needed for",
"is used it unpickles. When an item is removed from",
"time for # the entity and store it in datastore.",
"large changes that affect both caches. Although this module contains",
"\"\"\"Sets the value in the datastore for the externally namespaced",
"Using NDB, the values are also cached in memcache if",
"Pickles the value (memcache does this internally), and adds a",
"otherwise namespace will be retrieved using datastore_hooks.GetNamespace(). \"\"\" # When",
"try: CachedPickledString( id=namespaced_key, value=cPickle.dumps(value), expire_time=expire_time).put() except datastore_errors.BadRequestError as e: logging.warning('BadRequestError",
"keys = [entity.key for entity in entities if entity] yield",
"When an item is cached, layered_cache does the following: 1)",
"current_time) query = query.filter(cls.expire_time != None) return query.fetch(keys_only=True) def Get(key):",
"of days to keep is given, calculate expiration time for",
"current_time = datetime.datetime.now() query = cls.query(cls.expire_time < current_time) query =",
"found in the LICENSE file. \"\"\"Caches processed query results in",
"on whether datastore_hooks says the request is internal_only. 2) Pickles",
"does the following: 1) Namespaces the key based on whether",
"that can be # found in the LICENSE file. \"\"\"Caches",
"because doing a get() for a key which has a",
"keep is given, calculate expiration time for # the entity",
"since removals are usually caused by large changes that affect",
"Once the entity expires, it will be deleted from the",
"expiration time for # the entity and store it in",
"not expire when this value is 0 or None. namespace:",
"datastore, default is None. Entity will not expire when this",
"value from the datastore.\"\"\" yield DeleteAsync(key) @ndb.tasklet def DeleteAsync(key): unnamespaced_future",
"key: The key name, which will be namespaced as externally_visible.",
"All rights reserved. # Use of this source code is",
"get() for a key which has a single BlobProperty is",
"the datastore. Args: key: The key name, which will be",
"[entity.key for entity in entities if entity] yield (unnamespaced_future, ndb.delete_multi_async(keys))",
"import datetime import logging from google.appengine.api import datastore_errors from google.appengine.runtime",
"changes that affect both caches. Although this module contains ndb.Model",
"expire_time=expire_time).put() except datastore_errors.BadRequestError as e: logging.warning('BadRequestError for key %s: %s',",
"also cached in memcache if possible. This improves performance because",
"The value to set. days_to_keep: Number of days to keep",
"as cPickle import datetime import logging from google.appengine.api import datastore_errors",
"namespaced. value: The value to set. days_to_keep: Number of days",
"for the externally namespaced key.\"\"\" if key is None: return",
"= ndb.DateTimeProperty() @classmethod def NamespacedKey(cls, key, namespace): return ndb.Key(cls.__name__, namespaced_stored_object.NamespaceKey(key,",
"adds a data store entity with the key and a",
"entity in datastore, default is None. Entity will not expire",
"keys of expired entities. Returns: List of keys for items",
"Number of days to keep entity in datastore, default is",
"memcache is LRU and shared between multiple applications, so their",
"following: 1) Namespaces the key based on whether datastore_hooks says",
"entity expires, it will be deleted from the datastore. expire_time",
"key name, which will be namespaced as externally_visible. value: The",
"query.fetch(keys_only=True) def Get(key): \"\"\"Gets the value from the datastore.\"\"\" if",
"is not very reliable for the perf dashboard. Prometheus team",
"query results in the data store. Using NDB, the values",
"for a key which has a single BlobProperty is much",
"When an item is removed from the the cache, it",
"from the datastore.\"\"\" if key is None: return None namespaced_key",
"namespaced_stored_object.NamespaceKey(key, namespace)) @classmethod def GetExpiredKeys(cls): \"\"\"Gets keys of expired entities.",
"when this value is 0 or None. \"\"\" Set(key, value,",
"from dashboard.common import namespaced_stored_object from dashboard.common import stored_object class CachedPickledString(ndb.Model):",
"key. Needed for things like /add_point that update internal/external data",
"this value is 0 or None. \"\"\" Set(key, value, days_to_keep,",
"improves performance because doing a get() for a key which",
"it is removed from both internal and external caches, since",
"is None. Entity will not expire when this value is",
"both internal and external caches, since removals are usually caused",
"and if datastore is used it unpickles. When an item",
"+ datetime.timedelta( days=days_to_keep) namespaced_key = namespaced_stored_object.NamespaceKey(key, namespace) try: CachedPickledString( id=namespaced_key,",
"removed from the the cache, it is removed from both",
"or None. \"\"\" Set(key, value, days_to_keep, datastore_hooks.EXTERNAL) @ndb.synctasklet def Delete(key):",
"data store. Using NDB, the values are also cached in",
"if days_to_keep: expire_time = datetime.datetime.now() + datetime.timedelta( days=days_to_keep) namespaced_key =",
"e: logging.warning('BadRequestError for key %s: %s', key, e) except apiproxy_errors.RequestTooLargeError",
"if entity: return cPickle.loads(entity.value) return stored_object.Get(key) def Set(key, value, days_to_keep=None,",
"it in datastore. # Once the entity expires, it will",
"datetime import logging from google.appengine.api import datastore_errors from google.appengine.runtime import",
"intended to be used directly by other modules. \"\"\" from",
"from dashboard.common import datastore_hooks from dashboard.common import namespaced_stored_object from dashboard.common",
"entities = yield ndb.get_multi_async([ CachedPickledString.NamespacedKey(key, datastore_hooks.INTERNAL), CachedPickledString.NamespacedKey(key, datastore_hooks.EXTERNAL), ]) keys",
"from dashboard.common import stored_object class CachedPickledString(ndb.Model): value = ndb.BlobProperty() expire_time",
"via NDB first, and if datastore is used it unpickles.",
"ndb.DateTimeProperty() @classmethod def NamespacedKey(cls, key, namespace): return ndb.Key(cls.__name__, namespaced_stored_object.NamespaceKey(key, namespace))",
"key name, which will be namespaced. value: The value to",
"as e: logging.warning('BadRequestError for key %s: %s', key, e) except",
"Chromium Authors. All rights reserved. # Use of this source",
"cPickle.loads(entity.value) return stored_object.Get(key) def GetExternal(key): \"\"\"Gets the value from the",
"value (memcache does this internally), and adds a data store",
"entity in entities if entity] yield (unnamespaced_future, ndb.delete_multi_async(keys)) def DeleteAllExpiredEntities():",
"this module contains ndb.Model classes, these are not intended to",
"def Get(key): \"\"\"Gets the value from the datastore.\"\"\" if key",
"as e: stored_object.Set(key, value) def SetExternal(key, value, days_to_keep=None): \"\"\"Sets the",
"Get(key): \"\"\"Gets the value from the datastore.\"\"\" if key is",
"Namespaces the key based on whether datastore_hooks says the request",
"expire when this value is 0 or None. \"\"\" Set(key,",
"to keep entity in datastore, default is None. Entity will",
"import division from __future__ import absolute_import import six.moves.cPickle as cPickle",
"it will be deleted from the datastore. expire_time = None",
"]) keys = [entity.key for entity in entities if entity]",
"Memcache is not very reliable for the perf dashboard. Prometheus",
"ndb.Model classes, these are not intended to be used directly",
"1) Namespaces the key based on whether datastore_hooks says the",
"which are expired. \"\"\" current_time = datetime.datetime.now() query = cls.query(cls.expire_time",
"key: The key name, which will be namespaced. value: The",
"apiproxy_errors from google.appengine.ext import ndb from dashboard.common import datastore_hooks from",
"if key is None: return None namespaced_key = namespaced_stored_object.NamespaceKey(key) entity",
"__future__ import division from __future__ import absolute_import import six.moves.cPickle as",
"ndb.Key('CachedPickledString', namespaced_key).get(read_policy=ndb.EVENTUAL_CONSISTENCY) if entity: return cPickle.loads(entity.value) return stored_object.Get(key) def GetExternal(key):",
"this get(). entities = yield ndb.get_multi_async([ CachedPickledString.NamespacedKey(key, datastore_hooks.INTERNAL), CachedPickledString.NamespacedKey(key, datastore_hooks.EXTERNAL),",
"\"\"\"Caches processed query results in memcache and datastore. Memcache is",
"google.appengine.runtime import apiproxy_errors from google.appengine.ext import ndb from dashboard.common import",
"\"\"\" from __future__ import print_function from __future__ import division from",
"of expired entities. Returns: List of keys for items which",
"memcache if possible. This improves performance because doing a get()",
"the entity expires, it will be deleted from the datastore.",
"is None: return None namespaced_key = namespaced_stored_object.NamespaceKey( key, datastore_hooks.EXTERNAL) entity",
"datastore_hooks.GetNamespace(). \"\"\" # When number of days to keep is",
"store. Using NDB, the values are also cached in memcache",
"key %s: %s', key, e) except apiproxy_errors.RequestTooLargeError as e: stored_object.Set(key,",
"time. Args: key: The key name, which will be namespaced",
"are expired. \"\"\" current_time = datetime.datetime.now() query = cls.query(cls.expire_time <",
"about this get(). entities = yield ndb.get_multi_async([ CachedPickledString.NamespacedKey(key, datastore_hooks.INTERNAL), CachedPickledString.NamespacedKey(key,",
"# When number of days to keep is given, calculate",
"a complex query over a large dataset. (Background: http://g/prometheus-discuss/othVtufGIyM/wjAS5djyG8kJ) When",
"file. \"\"\"Caches processed query results in memcache and datastore. Memcache",
"None. \"\"\" Set(key, value, days_to_keep, datastore_hooks.EXTERNAL) @ndb.synctasklet def Delete(key): \"\"\"Clears"
] |
[
"isinstance(df, cudf.DataFrame) df_train, df_test = tb.train_test_split(df, test_size=0.5, random_state=123) X_test =",
"for s in estimator.steps]}') print(\"scoring...\") y_pred = estimator.predict(X_test) y_proba =",
"== 'CumlToolBox' print(\"preparing...\") df = dsutils.load_bank() if dtype is not",
"= tb.train_test_split(df, test_size=0.5, random_state=123) X_test = df_test y_test = X_test.pop(target)",
"tb.from_local(df) assert isinstance(df, cudf.DataFrame) df_train, df_test = tb.train_test_split(df, test_size=0.5, random_state=123)",
"assert isinstance(tb, type) and tb.__name__ == 'CumlToolBox' print(\"preparing...\") df =",
"and tb.__name__ == 'CumlToolBox' print(\"preparing...\") df = dsutils.load_bank() if dtype",
"= get_tool_box(cudf.DataFrame) assert isinstance(tb, type) and tb.__name__ == 'CumlToolBox' print(\"preparing...\")",
"= exp.task if task == 'regression': metrics = ['mse', 'mae',",
"in estimator.steps]}') print(\"scoring...\") y_pred = estimator.predict(X_test) y_proba = estimator.predict_proba(X_test) task",
"get_tool_box from hypernets.tabular.datasets import dsutils def main(target='y', dtype=None, max_trials=3, drift_detection=False,",
"max_trials=max_trials, drift_detection=drift_detection, clear_cache=clear_cache, **kwargs) print('experiment:', f'{[s.name for s in exp.steps]}',",
"pipeline:', f'{[s[0] for s in estimator.steps]}') print(\"scoring...\") y_pred = estimator.predict(X_test)",
"= tb.metrics.calc_score(y_test, y_pred, y_proba, task=task, metrics=metrics, pos_label=kwargs.get('pos_label', None)) print(result) return",
"assert isinstance(df, cudf.DataFrame) df_train, df_test = tb.train_test_split(df, test_size=0.5, random_state=123) X_test",
"# main(target='day', reward_metric='f1', ensemble_size=10, log_level='info', max_trials=5) # main(target='day', dtype='str', reward_metric='f1',",
"max_trials=10) # main(target='y', max_trials=10, cv=False, ensemble_size=0, verbose=0, pos_label='yes', ) #",
"from hypernets.tabular import get_tool_box from hypernets.tabular.datasets import dsutils def main(target='y',",
"dtype is not None: df[target] = df[target].astype(dtype) df, = tb.from_local(df)",
"pos_label='yes', ) # main(target='day', reward_metric='f1', ensemble_size=10, log_level='info', max_trials=5) # main(target='day',",
"= tb.from_local(df) assert isinstance(df, cudf.DataFrame) df_train, df_test = tb.train_test_split(df, test_size=0.5,",
"from hypernets.tabular.datasets import dsutils def main(target='y', dtype=None, max_trials=3, drift_detection=False, clear_cache=True,",
"for s in exp.steps]}', 'random_state', exp.random_state) print(\"training...\") estimator = exp.run()",
"print('experiment:', f'{[s.name for s in exp.steps]}', 'random_state', exp.random_state) print(\"training...\") estimator",
"tb.__name__ == 'CumlToolBox' print(\"preparing...\") df = dsutils.load_bank() if dtype is",
"-*- coding:utf-8 -*- \"\"\" \"\"\" import cudf from hypergbm import",
"task == 'regression': metrics = ['mse', 'mae', 'msle', 'rmse', 'r2']",
"'random_state', exp.random_state) print(\"training...\") estimator = exp.run() print('estimator pipeline:', f'{[s[0] for",
"f'{[s[0] for s in estimator.steps]}') print(\"scoring...\") y_pred = estimator.predict(X_test) y_proba",
"y_pred, y_proba, task=task, metrics=metrics, pos_label=kwargs.get('pos_label', None)) print(result) return exp, estimator",
"= df[target].astype(dtype) df, = tb.from_local(df) assert isinstance(df, cudf.DataFrame) df_train, df_test",
"drift_detection=drift_detection, clear_cache=clear_cache, **kwargs) print('experiment:', f'{[s.name for s in exp.steps]}', 'random_state',",
"# -*- coding:utf-8 -*- \"\"\" \"\"\" import cudf from hypergbm",
"exp.task if task == 'regression': metrics = ['mse', 'mae', 'msle',",
"task=task, metrics=metrics, pos_label=kwargs.get('pos_label', None)) print(result) return exp, estimator if __name__",
"if task == 'regression': metrics = ['mse', 'mae', 'msle', 'rmse',",
") # main(target='day', reward_metric='f1', ensemble_size=10, log_level='info', max_trials=5) # main(target='day', dtype='str',",
"verbose=0, pos_label='yes', ) # main(target='day', reward_metric='f1', ensemble_size=10, log_level='info', max_trials=5) #",
"if dtype is not None: df[target] = df[target].astype(dtype) df, =",
"y_pred = estimator.predict(X_test) y_proba = estimator.predict_proba(X_test) task = exp.task if",
"main(target='day', dtype='str', reward_metric='f1', ensemble_size=0, log_level='info', max_trials=6) # main(target='age', dtype='float', ensemble_size=10,",
"reward_metric='f1', ensemble_size=0, log_level='info', max_trials=6) # main(target='age', dtype='float', ensemble_size=10, log_level='info', max_trials=8)",
"from hypergbm import make_experiment from hypernets.tabular import get_tool_box from hypernets.tabular.datasets",
"X_test.pop(target) exp = make_experiment(df_train, target=target, test_data=X_test.copy(), max_trials=max_trials, drift_detection=drift_detection, clear_cache=clear_cache, **kwargs)",
"['mse', 'mae', 'msle', 'rmse', 'r2'] else: metrics = ['auc', 'accuracy',",
"cudf.DataFrame) df_train, df_test = tb.train_test_split(df, test_size=0.5, random_state=123) X_test = df_test",
"log_level='info', max_trials=10) # main(target='y', max_trials=10, cv=False, ensemble_size=0, verbose=0, pos_label='yes', )",
"print(\"training...\") estimator = exp.run() print('estimator pipeline:', f'{[s[0] for s in",
"reward_metric='auc', ensemble_size=10, pos_label='yes', log_level='info', max_trials=10) # main(target='y', max_trials=10, cv=False, ensemble_size=0,",
"return exp, estimator if __name__ == '__main__': main(target='y', reward_metric='auc', ensemble_size=10,",
"-*- \"\"\" \"\"\" import cudf from hypergbm import make_experiment from",
"pos_label=kwargs.get('pos_label', None)) print(result) return exp, estimator if __name__ == '__main__':",
"random_state=123) X_test = df_test y_test = X_test.pop(target) exp = make_experiment(df_train,",
"df[target].astype(dtype) df, = tb.from_local(df) assert isinstance(df, cudf.DataFrame) df_train, df_test =",
"= df_test y_test = X_test.pop(target) exp = make_experiment(df_train, target=target, test_data=X_test.copy(),",
"task = exp.task if task == 'regression': metrics = ['mse',",
"dtype=None, max_trials=3, drift_detection=False, clear_cache=True, **kwargs): tb = get_tool_box(cudf.DataFrame) assert isinstance(tb,",
"reward_metric='f1', ensemble_size=10, log_level='info', max_trials=5) # main(target='day', dtype='str', reward_metric='f1', ensemble_size=0, log_level='info',",
"estimator if __name__ == '__main__': main(target='y', reward_metric='auc', ensemble_size=10, pos_label='yes', log_level='info',",
"# main(target='day', dtype='str', reward_metric='f1', ensemble_size=0, log_level='info', max_trials=6) # main(target='age', dtype='float',",
"exp = make_experiment(df_train, target=target, test_data=X_test.copy(), max_trials=max_trials, drift_detection=drift_detection, clear_cache=clear_cache, **kwargs) print('experiment:',",
"hypernets.tabular import get_tool_box from hypernets.tabular.datasets import dsutils def main(target='y', dtype=None,",
"__name__ == '__main__': main(target='y', reward_metric='auc', ensemble_size=10, pos_label='yes', log_level='info', max_trials=10) #",
"exp, estimator if __name__ == '__main__': main(target='y', reward_metric='auc', ensemble_size=10, pos_label='yes',",
"max_trials=10, cv=False, ensemble_size=0, verbose=0, pos_label='yes', ) # main(target='day', reward_metric='f1', ensemble_size=10,",
"cv=False, ensemble_size=0, verbose=0, pos_label='yes', ) # main(target='day', reward_metric='f1', ensemble_size=10, log_level='info',",
"df, = tb.from_local(df) assert isinstance(df, cudf.DataFrame) df_train, df_test = tb.train_test_split(df,",
"df = dsutils.load_bank() if dtype is not None: df[target] =",
"estimator.predict(X_test) y_proba = estimator.predict_proba(X_test) task = exp.task if task ==",
"= estimator.predict_proba(X_test) task = exp.task if task == 'regression': metrics",
"= dsutils.load_bank() if dtype is not None: df[target] = df[target].astype(dtype)",
"metrics=metrics, pos_label=kwargs.get('pos_label', None)) print(result) return exp, estimator if __name__ ==",
"exp.random_state) print(\"training...\") estimator = exp.run() print('estimator pipeline:', f'{[s[0] for s",
"make_experiment from hypernets.tabular import get_tool_box from hypernets.tabular.datasets import dsutils def",
"None)) print(result) return exp, estimator if __name__ == '__main__': main(target='y',",
"test_data=X_test.copy(), max_trials=max_trials, drift_detection=drift_detection, clear_cache=clear_cache, **kwargs) print('experiment:', f'{[s.name for s in",
"= make_experiment(df_train, target=target, test_data=X_test.copy(), max_trials=max_trials, drift_detection=drift_detection, clear_cache=clear_cache, **kwargs) print('experiment:', f'{[s.name",
"'r2'] else: metrics = ['auc', 'accuracy', 'f1', 'recall'] result =",
"pos_label='yes', log_level='info', max_trials=10) # main(target='y', max_trials=10, cv=False, ensemble_size=0, verbose=0, pos_label='yes',",
"target=target, test_data=X_test.copy(), max_trials=max_trials, drift_detection=drift_detection, clear_cache=clear_cache, **kwargs) print('experiment:', f'{[s.name for s",
"= ['mse', 'mae', 'msle', 'rmse', 'r2'] else: metrics = ['auc',",
"isinstance(tb, type) and tb.__name__ == 'CumlToolBox' print(\"preparing...\") df = dsutils.load_bank()",
"ensemble_size=0, verbose=0, pos_label='yes', ) # main(target='day', reward_metric='f1', ensemble_size=10, log_level='info', max_trials=5)",
"def main(target='y', dtype=None, max_trials=3, drift_detection=False, clear_cache=True, **kwargs): tb = get_tool_box(cudf.DataFrame)",
"== '__main__': main(target='y', reward_metric='auc', ensemble_size=10, pos_label='yes', log_level='info', max_trials=10) # main(target='y',",
"y_proba, task=task, metrics=metrics, pos_label=kwargs.get('pos_label', None)) print(result) return exp, estimator if",
"cudf from hypergbm import make_experiment from hypernets.tabular import get_tool_box from",
"'msle', 'rmse', 'r2'] else: metrics = ['auc', 'accuracy', 'f1', 'recall']",
"result = tb.metrics.calc_score(y_test, y_pred, y_proba, task=task, metrics=metrics, pos_label=kwargs.get('pos_label', None)) print(result)",
"clear_cache=clear_cache, **kwargs) print('experiment:', f'{[s.name for s in exp.steps]}', 'random_state', exp.random_state)",
"dsutils def main(target='y', dtype=None, max_trials=3, drift_detection=False, clear_cache=True, **kwargs): tb =",
"in exp.steps]}', 'random_state', exp.random_state) print(\"training...\") estimator = exp.run() print('estimator pipeline:',",
"main(target='day', reward_metric='f1', ensemble_size=10, log_level='info', max_trials=5) # main(target='day', dtype='str', reward_metric='f1', ensemble_size=0,",
"df_test = tb.train_test_split(df, test_size=0.5, random_state=123) X_test = df_test y_test =",
"'regression': metrics = ['mse', 'mae', 'msle', 'rmse', 'r2'] else: metrics",
"estimator.predict_proba(X_test) task = exp.task if task == 'regression': metrics =",
"'accuracy', 'f1', 'recall'] result = tb.metrics.calc_score(y_test, y_pred, y_proba, task=task, metrics=metrics,",
"None: df[target] = df[target].astype(dtype) df, = tb.from_local(df) assert isinstance(df, cudf.DataFrame)",
"= exp.run() print('estimator pipeline:', f'{[s[0] for s in estimator.steps]}') print(\"scoring...\")",
"'rmse', 'r2'] else: metrics = ['auc', 'accuracy', 'f1', 'recall'] result",
"['auc', 'accuracy', 'f1', 'recall'] result = tb.metrics.calc_score(y_test, y_pred, y_proba, task=task,",
"test_size=0.5, random_state=123) X_test = df_test y_test = X_test.pop(target) exp =",
"metrics = ['auc', 'accuracy', 'f1', 'recall'] result = tb.metrics.calc_score(y_test, y_pred,",
"print(result) return exp, estimator if __name__ == '__main__': main(target='y', reward_metric='auc',",
"main(target='y', reward_metric='auc', ensemble_size=10, pos_label='yes', log_level='info', max_trials=10) # main(target='y', max_trials=10, cv=False,",
"s in exp.steps]}', 'random_state', exp.random_state) print(\"training...\") estimator = exp.run() print('estimator",
"**kwargs): tb = get_tool_box(cudf.DataFrame) assert isinstance(tb, type) and tb.__name__ ==",
"max_trials=3, drift_detection=False, clear_cache=True, **kwargs): tb = get_tool_box(cudf.DataFrame) assert isinstance(tb, type)",
"import get_tool_box from hypernets.tabular.datasets import dsutils def main(target='y', dtype=None, max_trials=3,",
"import make_experiment from hypernets.tabular import get_tool_box from hypernets.tabular.datasets import dsutils",
"print('estimator pipeline:', f'{[s[0] for s in estimator.steps]}') print(\"scoring...\") y_pred =",
"exp.steps]}', 'random_state', exp.random_state) print(\"training...\") estimator = exp.run() print('estimator pipeline:', f'{[s[0]",
"if __name__ == '__main__': main(target='y', reward_metric='auc', ensemble_size=10, pos_label='yes', log_level='info', max_trials=10)",
"X_test = df_test y_test = X_test.pop(target) exp = make_experiment(df_train, target=target,",
"'__main__': main(target='y', reward_metric='auc', ensemble_size=10, pos_label='yes', log_level='info', max_trials=10) # main(target='y', max_trials=10,",
"import dsutils def main(target='y', dtype=None, max_trials=3, drift_detection=False, clear_cache=True, **kwargs): tb",
"estimator = exp.run() print('estimator pipeline:', f'{[s[0] for s in estimator.steps]}')",
"is not None: df[target] = df[target].astype(dtype) df, = tb.from_local(df) assert",
"# main(target='y', max_trials=10, cv=False, ensemble_size=0, verbose=0, pos_label='yes', ) # main(target='day',",
"df_train, df_test = tb.train_test_split(df, test_size=0.5, random_state=123) X_test = df_test y_test",
"**kwargs) print('experiment:', f'{[s.name for s in exp.steps]}', 'random_state', exp.random_state) print(\"training...\")",
"= estimator.predict(X_test) y_proba = estimator.predict_proba(X_test) task = exp.task if task",
"get_tool_box(cudf.DataFrame) assert isinstance(tb, type) and tb.__name__ == 'CumlToolBox' print(\"preparing...\") df",
"'recall'] result = tb.metrics.calc_score(y_test, y_pred, y_proba, task=task, metrics=metrics, pos_label=kwargs.get('pos_label', None))",
"df_test y_test = X_test.pop(target) exp = make_experiment(df_train, target=target, test_data=X_test.copy(), max_trials=max_trials,",
"tb.metrics.calc_score(y_test, y_pred, y_proba, task=task, metrics=metrics, pos_label=kwargs.get('pos_label', None)) print(result) return exp,",
"ensemble_size=10, log_level='info', max_trials=5) # main(target='day', dtype='str', reward_metric='f1', ensemble_size=0, log_level='info', max_trials=6)",
"else: metrics = ['auc', 'accuracy', 'f1', 'recall'] result = tb.metrics.calc_score(y_test,",
"\"\"\" \"\"\" import cudf from hypergbm import make_experiment from hypernets.tabular",
"coding:utf-8 -*- \"\"\" \"\"\" import cudf from hypergbm import make_experiment",
"s in estimator.steps]}') print(\"scoring...\") y_pred = estimator.predict(X_test) y_proba = estimator.predict_proba(X_test)",
"dsutils.load_bank() if dtype is not None: df[target] = df[target].astype(dtype) df,",
"'f1', 'recall'] result = tb.metrics.calc_score(y_test, y_pred, y_proba, task=task, metrics=metrics, pos_label=kwargs.get('pos_label',",
"import cudf from hypergbm import make_experiment from hypernets.tabular import get_tool_box",
"== 'regression': metrics = ['mse', 'mae', 'msle', 'rmse', 'r2'] else:",
"tb = get_tool_box(cudf.DataFrame) assert isinstance(tb, type) and tb.__name__ == 'CumlToolBox'",
"metrics = ['mse', 'mae', 'msle', 'rmse', 'r2'] else: metrics =",
"= X_test.pop(target) exp = make_experiment(df_train, target=target, test_data=X_test.copy(), max_trials=max_trials, drift_detection=drift_detection, clear_cache=clear_cache,",
"main(target='y', max_trials=10, cv=False, ensemble_size=0, verbose=0, pos_label='yes', ) # main(target='day', reward_metric='f1',",
"y_test = X_test.pop(target) exp = make_experiment(df_train, target=target, test_data=X_test.copy(), max_trials=max_trials, drift_detection=drift_detection,",
"hypergbm import make_experiment from hypernets.tabular import get_tool_box from hypernets.tabular.datasets import",
"hypernets.tabular.datasets import dsutils def main(target='y', dtype=None, max_trials=3, drift_detection=False, clear_cache=True, **kwargs):",
"type) and tb.__name__ == 'CumlToolBox' print(\"preparing...\") df = dsutils.load_bank() if",
"print(\"preparing...\") df = dsutils.load_bank() if dtype is not None: df[target]",
"y_proba = estimator.predict_proba(X_test) task = exp.task if task == 'regression':",
"= ['auc', 'accuracy', 'f1', 'recall'] result = tb.metrics.calc_score(y_test, y_pred, y_proba,",
"\"\"\" import cudf from hypergbm import make_experiment from hypernets.tabular import",
"not None: df[target] = df[target].astype(dtype) df, = tb.from_local(df) assert isinstance(df,",
"df[target] = df[target].astype(dtype) df, = tb.from_local(df) assert isinstance(df, cudf.DataFrame) df_train,",
"tb.train_test_split(df, test_size=0.5, random_state=123) X_test = df_test y_test = X_test.pop(target) exp",
"ensemble_size=10, pos_label='yes', log_level='info', max_trials=10) # main(target='y', max_trials=10, cv=False, ensemble_size=0, verbose=0,",
"'mae', 'msle', 'rmse', 'r2'] else: metrics = ['auc', 'accuracy', 'f1',",
"f'{[s.name for s in exp.steps]}', 'random_state', exp.random_state) print(\"training...\") estimator =",
"dtype='str', reward_metric='f1', ensemble_size=0, log_level='info', max_trials=6) # main(target='age', dtype='float', ensemble_size=10, log_level='info',",
"'CumlToolBox' print(\"preparing...\") df = dsutils.load_bank() if dtype is not None:",
"main(target='y', dtype=None, max_trials=3, drift_detection=False, clear_cache=True, **kwargs): tb = get_tool_box(cudf.DataFrame) assert",
"exp.run() print('estimator pipeline:', f'{[s[0] for s in estimator.steps]}') print(\"scoring...\") y_pred",
"clear_cache=True, **kwargs): tb = get_tool_box(cudf.DataFrame) assert isinstance(tb, type) and tb.__name__",
"estimator.steps]}') print(\"scoring...\") y_pred = estimator.predict(X_test) y_proba = estimator.predict_proba(X_test) task =",
"print(\"scoring...\") y_pred = estimator.predict(X_test) y_proba = estimator.predict_proba(X_test) task = exp.task",
"make_experiment(df_train, target=target, test_data=X_test.copy(), max_trials=max_trials, drift_detection=drift_detection, clear_cache=clear_cache, **kwargs) print('experiment:', f'{[s.name for",
"log_level='info', max_trials=5) # main(target='day', dtype='str', reward_metric='f1', ensemble_size=0, log_level='info', max_trials=6) #",
"drift_detection=False, clear_cache=True, **kwargs): tb = get_tool_box(cudf.DataFrame) assert isinstance(tb, type) and",
"max_trials=5) # main(target='day', dtype='str', reward_metric='f1', ensemble_size=0, log_level='info', max_trials=6) # main(target='age',"
] |
[
"for i in og: file1 = open(address+'/'+i, \"a\") x=\"\\ncover::https://image.tmdb.org/t/p/original/\"+list[j] file1.writelines(x)",
"def pictureInserter(og,address,list): j=0 for i in og: file1 = open(address+'/'+i,",
"i in og: file1 = open(address+'/'+i, \"a\") x=\"\\ncover::https://image.tmdb.org/t/p/original/\"+list[j] file1.writelines(x) file1.close()",
"pictureInserter(og,address,list): j=0 for i in og: file1 = open(address+'/'+i, \"a\")",
"j=0 for i in og: file1 = open(address+'/'+i, \"a\") x=\"\\ncover::https://image.tmdb.org/t/p/original/\"+list[j]",
"<gh_stars>0 def pictureInserter(og,address,list): j=0 for i in og: file1 =",
"in og: file1 = open(address+'/'+i, \"a\") x=\"\\ncover::https://image.tmdb.org/t/p/original/\"+list[j] file1.writelines(x) file1.close() j=j+1"
] |
[
"executor = concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers) futures = [executor.submit(_get_samples, loc, y_name, y_num) for",
"return 1281167 @staticmethod def num_test_examples(): return 50000 @staticmethod def num_classes():",
"output = [(os.path.join(y_dir, f), y_num) for f in get_platform().listdir(y_dir) if",
"base from platforms.platform import get_platform def _get_samples(root, y_name, y_num): y_dir",
"loc, y_name, y_num) for y_num, y_name in enumerate(classes)] for d",
"1.25)), torchvision.transforms.RandomHorizontalFlip() ] @staticmethod def _transforms(): return [torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224)] @staticmethod",
"# Copyright (c) Facebook, Inc. and its affiliates. # This",
"Copyright (c) Facebook, Inc. and its affiliates. # This source",
"in the # LICENSE file in the root directory of",
"as np import os from PIL import Image import torchvision",
"0.456, 0.406], [0.229, 0.224, 0.225])]) @staticmethod def num_train_examples(): return 1281167",
"under the MIT license found in the # LICENSE file",
"@staticmethod def num_classes(): return 1000 @staticmethod def _augment_transforms(): return [",
"get_test_set(resize): return Dataset(os.path.join(get_platform().imagenet_root, 'val'), Dataset._transforms()) @staticmethod def example_to_image(example): with get_platform().open(example,",
"in get_platform().listdir(y_dir) if f.lower().endswith('jpeg')] return output class Dataset(base.ImageDataset): \"\"\"ImageNet\"\"\" def",
"num_test_examples(): return 50000 @staticmethod def num_classes(): return 1000 @staticmethod def",
"transforms = Dataset._augment_transforms() if use_augmentation else Dataset._transforms() return Dataset(os.path.join(get_platform().imagenet_root, 'train'),",
"def _transforms(): return [torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224)] @staticmethod def get_train_set(use_augmentation, resize): transforms",
"in enumerate(classes): samples += _get_samples(loc, y_name, y_num) examples, labels =",
"Load the data. classes = sorted(get_platform().listdir(loc)) samples = [] if",
"@staticmethod def num_train_examples(): return 1281167 @staticmethod def num_test_examples(): return 50000",
"np import os from PIL import Image import torchvision from",
"classes = sorted(get_platform().listdir(loc)) samples = [] if get_platform().num_workers > 0:",
"examples, labels = zip(*samples) super(Dataset, self).__init__( np.array(examples), np.array(labels), image_transforms, [torchvision.transforms.Normalize([0.485,",
"in enumerate(classes)] for d in concurrent.futures.wait(futures)[0]: samples += d.result() else:",
"1281167 @staticmethod def num_test_examples(): return 50000 @staticmethod def num_classes(): return",
"zip(*samples) super(Dataset, self).__init__( np.array(examples), np.array(labels), image_transforms, [torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229,",
"[0.229, 0.224, 0.225])]) @staticmethod def num_train_examples(): return 1281167 @staticmethod def",
"return Dataset(os.path.join(get_platform().imagenet_root, 'train'), transforms) @staticmethod def get_test_set(resize): return Dataset(os.path.join(get_platform().imagenet_root, 'val'),",
"torchvision.transforms.CenterCrop(224)] @staticmethod def get_train_set(use_augmentation, resize): transforms = Dataset._augment_transforms() if use_augmentation",
"LICENSE file in the root directory of this source tree.",
"[(os.path.join(y_dir, f), y_num) for f in get_platform().listdir(y_dir) if f.lower().endswith('jpeg')] return",
"= concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers) futures = [executor.submit(_get_samples, loc, y_name, y_num) for y_num,",
"os.path.join(root, y_name) if not get_platform().isdir(y_dir): return [] output = [(os.path.join(y_dir,",
"str, image_transforms): # Load the data. classes = sorted(get_platform().listdir(loc)) samples",
"return [torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224)] @staticmethod def get_train_set(use_augmentation, resize): transforms = Dataset._augment_transforms()",
"= [(os.path.join(y_dir, f), y_num) for f in get_platform().listdir(y_dir) if f.lower().endswith('jpeg')]",
"num_train_examples(): return 1281167 @staticmethod def num_test_examples(): return 50000 @staticmethod def",
"0.406], [0.229, 0.224, 0.225])]) @staticmethod def num_train_examples(): return 1281167 @staticmethod",
"0.224, 0.225])]) @staticmethod def num_train_examples(): return 1281167 @staticmethod def num_test_examples():",
"if f.lower().endswith('jpeg')] return output class Dataset(base.ImageDataset): \"\"\"ImageNet\"\"\" def __init__(self, loc:",
"torchvision from datasets import base from platforms.platform import get_platform def",
"= zip(*samples) super(Dataset, self).__init__( np.array(examples), np.array(labels), image_transforms, [torchvision.transforms.Normalize([0.485, 0.456, 0.406],",
"numpy as np import os from PIL import Image import",
"@staticmethod def example_to_image(example): with get_platform().open(example, 'rb') as fp: return Image.open(fp).convert('RGB')",
"y_num, y_name in enumerate(classes)] for d in concurrent.futures.wait(futures)[0]: samples +=",
"import numpy as np import os from PIL import Image",
"(c) Facebook, Inc. and its affiliates. # This source code",
"def num_test_examples(): return 50000 @staticmethod def num_classes(): return 1000 @staticmethod",
"[torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224)] @staticmethod def get_train_set(use_augmentation, resize): transforms = Dataset._augment_transforms() if",
"if use_augmentation else Dataset._transforms() return Dataset(os.path.join(get_platform().imagenet_root, 'train'), transforms) @staticmethod def",
"d in concurrent.futures.wait(futures)[0]: samples += d.result() else: for y_num, y_name",
"root directory of this source tree. import concurrent.futures import numpy",
"this source tree. import concurrent.futures import numpy as np import",
"# LICENSE file in the root directory of this source",
"return output class Dataset(base.ImageDataset): \"\"\"ImageNet\"\"\" def __init__(self, loc: str, image_transforms):",
"example_to_image(example): with get_platform().open(example, 'rb') as fp: return Image.open(fp).convert('RGB') DataLoader =",
"affiliates. # This source code is licensed under the MIT",
"the MIT license found in the # LICENSE file in",
"concurrent.futures.wait(futures)[0]: samples += d.result() else: for y_num, y_name in enumerate(classes):",
"samples += d.result() else: for y_num, y_name in enumerate(classes): samples",
"resize): transforms = Dataset._augment_transforms() if use_augmentation else Dataset._transforms() return Dataset(os.path.join(get_platform().imagenet_root,",
"found in the # LICENSE file in the root directory",
"else: for y_num, y_name in enumerate(classes): samples += _get_samples(loc, y_name,",
"for f in get_platform().listdir(y_dir) if f.lower().endswith('jpeg')] return output class Dataset(base.ImageDataset):",
"y_num): y_dir = os.path.join(root, y_name) if not get_platform().isdir(y_dir): return []",
"[executor.submit(_get_samples, loc, y_name, y_num) for y_num, y_name in enumerate(classes)] for",
"samples += _get_samples(loc, y_name, y_num) examples, labels = zip(*samples) super(Dataset,",
"of this source tree. import concurrent.futures import numpy as np",
"license found in the # LICENSE file in the root",
"f.lower().endswith('jpeg')] return output class Dataset(base.ImageDataset): \"\"\"ImageNet\"\"\" def __init__(self, loc: str,",
"y_name, y_num): y_dir = os.path.join(root, y_name) if not get_platform().isdir(y_dir): return",
"[ torchvision.transforms.RandomResizedCrop(224, scale=(0.1, 1.0), ratio=(0.8, 1.25)), torchvision.transforms.RandomHorizontalFlip() ] @staticmethod def",
"0: executor = concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers) futures = [executor.submit(_get_samples, loc, y_name, y_num)",
"y_dir = os.path.join(root, y_name) if not get_platform().isdir(y_dir): return [] output",
"y_name, y_num) for y_num, y_name in enumerate(classes)] for d in",
"return [] output = [(os.path.join(y_dir, f), y_num) for f in",
"_get_samples(root, y_name, y_num): y_dir = os.path.join(root, y_name) if not get_platform().isdir(y_dir):",
"torchvision.transforms.RandomResizedCrop(224, scale=(0.1, 1.0), ratio=(0.8, 1.25)), torchvision.transforms.RandomHorizontalFlip() ] @staticmethod def _transforms():",
"Inc. and its affiliates. # This source code is licensed",
"@staticmethod def num_test_examples(): return 50000 @staticmethod def num_classes(): return 1000",
"enumerate(classes): samples += _get_samples(loc, y_name, y_num) examples, labels = zip(*samples)",
"datasets import base from platforms.platform import get_platform def _get_samples(root, y_name,",
"y_name) if not get_platform().isdir(y_dir): return [] output = [(os.path.join(y_dir, f),",
"self).__init__( np.array(examples), np.array(labels), image_transforms, [torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])",
"not get_platform().isdir(y_dir): return [] output = [(os.path.join(y_dir, f), y_num) for",
"= os.path.join(root, y_name) if not get_platform().isdir(y_dir): return [] output =",
"image_transforms, [torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) @staticmethod def num_train_examples():",
"the data. classes = sorted(get_platform().listdir(loc)) samples = [] if get_platform().num_workers",
"image_transforms): # Load the data. classes = sorted(get_platform().listdir(loc)) samples =",
"_augment_transforms(): return [ torchvision.transforms.RandomResizedCrop(224, scale=(0.1, 1.0), ratio=(0.8, 1.25)), torchvision.transforms.RandomHorizontalFlip() ]",
"y_name in enumerate(classes)] for d in concurrent.futures.wait(futures)[0]: samples += d.result()",
"concurrent.futures import numpy as np import os from PIL import",
"] @staticmethod def _transforms(): return [torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224)] @staticmethod def get_train_set(use_augmentation,",
"import os from PIL import Image import torchvision from datasets",
"from PIL import Image import torchvision from datasets import base",
"[] output = [(os.path.join(y_dir, f), y_num) for f in get_platform().listdir(y_dir)",
"def num_classes(): return 1000 @staticmethod def _augment_transforms(): return [ torchvision.transforms.RandomResizedCrop(224,",
"data. classes = sorted(get_platform().listdir(loc)) samples = [] if get_platform().num_workers >",
"for y_num, y_name in enumerate(classes): samples += _get_samples(loc, y_name, y_num)",
"y_num) examples, labels = zip(*samples) super(Dataset, self).__init__( np.array(examples), np.array(labels), image_transforms,",
"def _augment_transforms(): return [ torchvision.transforms.RandomResizedCrop(224, scale=(0.1, 1.0), ratio=(0.8, 1.25)), torchvision.transforms.RandomHorizontalFlip()",
"Dataset(base.ImageDataset): \"\"\"ImageNet\"\"\" def __init__(self, loc: str, image_transforms): # Load the",
"get_platform().num_workers > 0: executor = concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers) futures = [executor.submit(_get_samples, loc,",
"if get_platform().num_workers > 0: executor = concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers) futures = [executor.submit(_get_samples,",
"Dataset(os.path.join(get_platform().imagenet_root, 'train'), transforms) @staticmethod def get_test_set(resize): return Dataset(os.path.join(get_platform().imagenet_root, 'val'), Dataset._transforms())",
"from platforms.platform import get_platform def _get_samples(root, y_name, y_num): y_dir =",
"'train'), transforms) @staticmethod def get_test_set(resize): return Dataset(os.path.join(get_platform().imagenet_root, 'val'), Dataset._transforms()) @staticmethod",
"get_platform def _get_samples(root, y_name, y_num): y_dir = os.path.join(root, y_name) if",
"np.array(labels), image_transforms, [torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) @staticmethod def",
"is licensed under the MIT license found in the #",
"in the root directory of this source tree. import concurrent.futures",
"labels = zip(*samples) super(Dataset, self).__init__( np.array(examples), np.array(labels), image_transforms, [torchvision.transforms.Normalize([0.485, 0.456,",
"1000 @staticmethod def _augment_transforms(): return [ torchvision.transforms.RandomResizedCrop(224, scale=(0.1, 1.0), ratio=(0.8,",
"50000 @staticmethod def num_classes(): return 1000 @staticmethod def _augment_transforms(): return",
"the # LICENSE file in the root directory of this",
"Image import torchvision from datasets import base from platforms.platform import",
"from datasets import base from platforms.platform import get_platform def _get_samples(root,",
"_transforms(): return [torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224)] @staticmethod def get_train_set(use_augmentation, resize): transforms =",
"@staticmethod def get_train_set(use_augmentation, resize): transforms = Dataset._augment_transforms() if use_augmentation else",
"output class Dataset(base.ImageDataset): \"\"\"ImageNet\"\"\" def __init__(self, loc: str, image_transforms): #",
"[] if get_platform().num_workers > 0: executor = concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers) futures =",
"import torchvision from datasets import base from platforms.platform import get_platform",
"for y_num, y_name in enumerate(classes)] for d in concurrent.futures.wait(futures)[0]: samples",
"= Dataset._augment_transforms() if use_augmentation else Dataset._transforms() return Dataset(os.path.join(get_platform().imagenet_root, 'train'), transforms)",
"d.result() else: for y_num, y_name in enumerate(classes): samples += _get_samples(loc,",
"def num_train_examples(): return 1281167 @staticmethod def num_test_examples(): return 50000 @staticmethod",
"with get_platform().open(example, 'rb') as fp: return Image.open(fp).convert('RGB') DataLoader = base.DataLoader",
"> 0: executor = concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers) futures = [executor.submit(_get_samples, loc, y_name,",
"file in the root directory of this source tree. import",
"import Image import torchvision from datasets import base from platforms.platform",
"import base from platforms.platform import get_platform def _get_samples(root, y_name, y_num):",
"Dataset._transforms()) @staticmethod def example_to_image(example): with get_platform().open(example, 'rb') as fp: return",
"tree. import concurrent.futures import numpy as np import os from",
"torchvision.transforms.RandomHorizontalFlip() ] @staticmethod def _transforms(): return [torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224)] @staticmethod def",
"Dataset._augment_transforms() if use_augmentation else Dataset._transforms() return Dataset(os.path.join(get_platform().imagenet_root, 'train'), transforms) @staticmethod",
"_get_samples(loc, y_name, y_num) examples, labels = zip(*samples) super(Dataset, self).__init__( np.array(examples),",
"This source code is licensed under the MIT license found",
"samples = [] if get_platform().num_workers > 0: executor = concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers)",
"futures = [executor.submit(_get_samples, loc, y_name, y_num) for y_num, y_name in",
"__init__(self, loc: str, image_transforms): # Load the data. classes =",
"@staticmethod def get_test_set(resize): return Dataset(os.path.join(get_platform().imagenet_root, 'val'), Dataset._transforms()) @staticmethod def example_to_image(example):",
"get_platform().isdir(y_dir): return [] output = [(os.path.join(y_dir, f), y_num) for f",
"ratio=(0.8, 1.25)), torchvision.transforms.RandomHorizontalFlip() ] @staticmethod def _transforms(): return [torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224)]",
"get_platform().listdir(y_dir) if f.lower().endswith('jpeg')] return output class Dataset(base.ImageDataset): \"\"\"ImageNet\"\"\" def __init__(self,",
"import concurrent.futures import numpy as np import os from PIL",
"import get_platform def _get_samples(root, y_name, y_num): y_dir = os.path.join(root, y_name)",
"transforms) @staticmethod def get_test_set(resize): return Dataset(os.path.join(get_platform().imagenet_root, 'val'), Dataset._transforms()) @staticmethod def",
"y_name, y_num) examples, labels = zip(*samples) super(Dataset, self).__init__( np.array(examples), np.array(labels),",
"# Load the data. classes = sorted(get_platform().listdir(loc)) samples = []",
"def get_train_set(use_augmentation, resize): transforms = Dataset._augment_transforms() if use_augmentation else Dataset._transforms()",
"else Dataset._transforms() return Dataset(os.path.join(get_platform().imagenet_root, 'train'), transforms) @staticmethod def get_test_set(resize): return",
"source tree. import concurrent.futures import numpy as np import os",
"code is licensed under the MIT license found in the",
"y_num, y_name in enumerate(classes): samples += _get_samples(loc, y_name, y_num) examples,",
"= sorted(get_platform().listdir(loc)) samples = [] if get_platform().num_workers > 0: executor",
"the root directory of this source tree. import concurrent.futures import",
"@staticmethod def _transforms(): return [torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224)] @staticmethod def get_train_set(use_augmentation, resize):",
"source code is licensed under the MIT license found in",
"'val'), Dataset._transforms()) @staticmethod def example_to_image(example): with get_platform().open(example, 'rb') as fp:",
"licensed under the MIT license found in the # LICENSE",
"\"\"\"ImageNet\"\"\" def __init__(self, loc: str, image_transforms): # Load the data.",
"enumerate(classes)] for d in concurrent.futures.wait(futures)[0]: samples += d.result() else: for",
"for d in concurrent.futures.wait(futures)[0]: samples += d.result() else: for y_num,",
"sorted(get_platform().listdir(loc)) samples = [] if get_platform().num_workers > 0: executor =",
"if not get_platform().isdir(y_dir): return [] output = [(os.path.join(y_dir, f), y_num)",
"return 50000 @staticmethod def num_classes(): return 1000 @staticmethod def _augment_transforms():",
"and its affiliates. # This source code is licensed under",
"return [ torchvision.transforms.RandomResizedCrop(224, scale=(0.1, 1.0), ratio=(0.8, 1.25)), torchvision.transforms.RandomHorizontalFlip() ] @staticmethod",
"num_classes(): return 1000 @staticmethod def _augment_transforms(): return [ torchvision.transforms.RandomResizedCrop(224, scale=(0.1,",
"= [] if get_platform().num_workers > 0: executor = concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers) futures",
"get_train_set(use_augmentation, resize): transforms = Dataset._augment_transforms() if use_augmentation else Dataset._transforms() return",
"def example_to_image(example): with get_platform().open(example, 'rb') as fp: return Image.open(fp).convert('RGB') DataLoader",
"MIT license found in the # LICENSE file in the",
"in concurrent.futures.wait(futures)[0]: samples += d.result() else: for y_num, y_name in",
"1.0), ratio=(0.8, 1.25)), torchvision.transforms.RandomHorizontalFlip() ] @staticmethod def _transforms(): return [torchvision.transforms.Resize(256),",
"f), y_num) for f in get_platform().listdir(y_dir) if f.lower().endswith('jpeg')] return output",
"= [executor.submit(_get_samples, loc, y_name, y_num) for y_num, y_name in enumerate(classes)]",
"np.array(examples), np.array(labels), image_transforms, [torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) @staticmethod",
"super(Dataset, self).__init__( np.array(examples), np.array(labels), image_transforms, [torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224,",
"Dataset(os.path.join(get_platform().imagenet_root, 'val'), Dataset._transforms()) @staticmethod def example_to_image(example): with get_platform().open(example, 'rb') as",
"def __init__(self, loc: str, image_transforms): # Load the data. classes",
"platforms.platform import get_platform def _get_samples(root, y_name, y_num): y_dir = os.path.join(root,",
"[torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) @staticmethod def num_train_examples(): return",
"def get_test_set(resize): return Dataset(os.path.join(get_platform().imagenet_root, 'val'), Dataset._transforms()) @staticmethod def example_to_image(example): with",
"# This source code is licensed under the MIT license",
"return 1000 @staticmethod def _augment_transforms(): return [ torchvision.transforms.RandomResizedCrop(224, scale=(0.1, 1.0),",
"concurrent.futures.ThreadPoolExecutor(max_workers=get_platform().num_workers) futures = [executor.submit(_get_samples, loc, y_name, y_num) for y_num, y_name",
"<gh_stars>1-10 # Copyright (c) Facebook, Inc. and its affiliates. #",
"directory of this source tree. import concurrent.futures import numpy as",
"+= _get_samples(loc, y_name, y_num) examples, labels = zip(*samples) super(Dataset, self).__init__(",
"Dataset._transforms() return Dataset(os.path.join(get_platform().imagenet_root, 'train'), transforms) @staticmethod def get_test_set(resize): return Dataset(os.path.join(get_platform().imagenet_root,",
"its affiliates. # This source code is licensed under the",
"+= d.result() else: for y_num, y_name in enumerate(classes): samples +=",
"scale=(0.1, 1.0), ratio=(0.8, 1.25)), torchvision.transforms.RandomHorizontalFlip() ] @staticmethod def _transforms(): return",
"y_num) for f in get_platform().listdir(y_dir) if f.lower().endswith('jpeg')] return output class",
"f in get_platform().listdir(y_dir) if f.lower().endswith('jpeg')] return output class Dataset(base.ImageDataset): \"\"\"ImageNet\"\"\"",
"use_augmentation else Dataset._transforms() return Dataset(os.path.join(get_platform().imagenet_root, 'train'), transforms) @staticmethod def get_test_set(resize):",
"y_name in enumerate(classes): samples += _get_samples(loc, y_name, y_num) examples, labels",
"loc: str, image_transforms): # Load the data. classes = sorted(get_platform().listdir(loc))",
"Facebook, Inc. and its affiliates. # This source code is",
"0.225])]) @staticmethod def num_train_examples(): return 1281167 @staticmethod def num_test_examples(): return",
"os from PIL import Image import torchvision from datasets import",
"return Dataset(os.path.join(get_platform().imagenet_root, 'val'), Dataset._transforms()) @staticmethod def example_to_image(example): with get_platform().open(example, 'rb')",
"@staticmethod def _augment_transforms(): return [ torchvision.transforms.RandomResizedCrop(224, scale=(0.1, 1.0), ratio=(0.8, 1.25)),",
"y_num) for y_num, y_name in enumerate(classes)] for d in concurrent.futures.wait(futures)[0]:",
"def _get_samples(root, y_name, y_num): y_dir = os.path.join(root, y_name) if not",
"class Dataset(base.ImageDataset): \"\"\"ImageNet\"\"\" def __init__(self, loc: str, image_transforms): # Load",
"PIL import Image import torchvision from datasets import base from"
] |
[
"help='加密目标类型', default='input') parser.add_argument('--output', help='输出文件名,如不指定则输出至标准输出流') args = parser.parse_args() c = CryptSM4()",
"in output_list ] # 转成字节流 return list_to_bytes(output_list) # 合并 def",
"= [S_BOX[(A >> i) & (0x000000ff)] for i in range(0,",
"= B ^ (B <<< 13) ^ (B <<< 23)",
"rotl(input, 24) def L_prime(self, input): \"\"\"线性变换L',用于密钥扩展算法 L'(B) = B ^",
"parser.add_argument('--source_type', choices=['input', 'bin_file', 'image'], help='加密目标类型', default='input') parser.add_argument('--output', help='输出文件名,如不指定则输出至标准输出流') args =",
"Image.open(args.source) img = np.array(source.convert('RGBA')) shape = img.shape size = img.size",
"output = hexlify(output).decode() output = output[:size * 2] output =",
"import Image import numpy as np source = Image.open(args.source) img",
"FK[i] for i in range(4)] # 存储轮密钥 for i in",
"= [B[i] << (i * 8) for i in range(4)]",
"X (list): 输入 i (int): 轮密钥的下标 Returns: int: 输出 \"\"\"",
"# 反序变换 return sum(output) def encrypt(self, x): \"\"\"加密函数 Args: x",
"x in input_list] # 分别加解密 output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX))",
"import ArgumentParser, ArgumentError from binascii import hexlify, unhexlify from utils",
"密钥或初始化向量长度过长 Returns: bytes: key或iv \"\"\" if isinstance(key_iv, str): key_iv =",
"args.output: with open(args.output, \"wb\") as f: f.write(output) else: try: print(output.decode())",
"ENCRYPT = 0 # 加密 DECRYPT = 1 # 解密",
"(BLOCK_BYTE - len(key_iv)) + key_iv def set_key(self, key): \"\"\"设置key Args:",
"输出数据 \"\"\" B = [S_BOX[(A >> i) & (0x000000ff)] for",
"<< (i * 32) for i in range(4)] # 反序变换",
"sum(output) def encrypt(self, x): \"\"\"加密函数 Args: x (int): 需加密的数据 Returns:",
"输出 \"\"\" return self._crypt_ECB(padding(plain_text), ENCRYPT) def decrypt_ECB(self, cipher_text): \"\"\"ECB解密函数 Args:",
"raise TypeError(\"密钥或初始化向量类型错误\") if len(key_iv) > BLOCK_BYTE: raise ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE)) return unhexlify('00')",
"# 加解密时使用的轮密钥顺序不同 for i in range(32) if mode == ENCRYPT",
"(int): 需解密的数据 Returns: int: 输出 \"\"\" try: cipher_text = unhexlify(cipher_text)",
"== 'ecb' else c.decrypt_CBC( input, args.iv) if args.source_type == 'image':",
"bytes: key或iv \"\"\" if isinstance(key_iv, str): key_iv = key_iv.encode(encoding='UTF8') elif",
"TypeError(\"密钥或初始化向量类型错误\") if len(key_iv) > BLOCK_BYTE: raise ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE)) return unhexlify('00') *",
"ZelKnow @Github : https://github.com/ZelKnow \"\"\" __author__ = \"ZelKnow\" from argparse",
"input = f.read() else: from PIL import Image import numpy",
"K.append(K[i] ^ self.T(K[i + 1] ^ K[i + 2] ^",
"with open(args.source, 'rb') as f: input = f.read() else: from",
"python # -*- encoding: utf-8 -*- \"\"\" @File : sm4.py",
"input_list = bytes_to_list(input, BLOCK_BYTE) # 拆分成block input_list = [int(hexlify(i), 16)",
"加密或解密. Defaults to ENCRYPT. Returns: int: 输出 \"\"\" iv =",
"= self.check_key_iv(key) input = bytes_to_list(hexlify(key), BLOCK_HEX / 4) input =",
"help='加密/解密目标') parser.add_argument('key', help='密钥') parser.add_argument('--iv', help='初始化向量,cbc模式使用') parser.add_argument('--source_type', choices=['input', 'bin_file', 'image'], help='加密目标类型',",
"else reversed(range(32)): input.append(self.F(input[-4:], i)) # 32次迭代运算 output = input[-4:] output",
"j + 2], 16) for j in range(0, 8, 2)]",
"\"\"\" return input ^ rotl(input, 13) ^ rotl(input, 23) def",
"import rotl, num2hex, bytes_to_list, list_to_bytes, padding, unpadding ENCRYPT = 0",
"23) Args: input (int): 输入数据 Returns: int: 输出数据 \"\"\" return",
"int): print(len(num2hex(key_iv, width=32))) key_iv = unhexlify(num2hex(key_iv, width=32)) elif not isinstance(key_iv,",
"in range(0, len(output), 8)] output = np.array(output) output = Image.fromarray(output.reshape(shape).astype('uint8'))",
"def L_prime(self, input): \"\"\"线性变换L',用于密钥扩展算法 L'(B) = B ^ (B <<<",
"= 0 # 加密 DECRYPT = 1 # 解密 class",
"Args: A (int): 输入数据 L_func (function): 线性变换L Returns: int: 输出数据",
"= img.size input = unhexlify(''.join([num2hex(i, width=2) for i in img.flatten()]))",
"= [] def T(self, A, L_func): \"\"\"合成置换函数T T(.) = L(\\tau(.))",
"= input[-4:] output = [output[i] << (i * 32) for",
"2) ^ (B <<< 10) ^ (B <<< 18) ^",
"\"\"\"设置key Args: key (int, str or bytes): 密钥 \"\"\" key",
"for i in range(0, 32, 8)] B = [B[i] <<",
"unhexlify('00') * (BLOCK_BYTE - len(key_iv)) + key_iv def set_key(self, key):",
"parser.parse_args() c = CryptSM4() c.set_key(args.key) if args.mode == 'cbc' and",
"+ j:i + j + 2], 16) for j in",
"\"\"\"加密函数 Args: x (int): 需加密的数据 Returns: int: 输出 \"\"\" return",
"self.T(X[1] ^ X[2] ^ X[3] ^ self.rk[i], self.L) def _crypt(self,",
"j in range(0, 8, 2)] for i in range(0, len(output),",
"Returns: int: 输出数据 \"\"\" return input ^ rotl(input, 2) ^",
"[(x >> i) & (0xffffffff) for i in reversed(range(0, 128,",
"or bytes): key或iv Raises: TypeError: 密钥或初始化向量类型错误 ValueError: 密钥或初始化向量长度过长 Returns: bytes:",
"16) # 初始化向量 input_list = bytes_to_list(input, BLOCK_BYTE) # 拆分成block input_list",
"@Author : ZelKnow @Github : https://github.com/ZelKnow \"\"\" __author__ = \"ZelKnow\"",
"8) for i in range(4)] C = L_func(sum(B)) return C",
"in range(4)] C = L_func(sum(B)) return C def L(self, input):",
"Returns: int: 输出 \"\"\" return X[0] ^ self.T(X[1] ^ X[2]",
"解密 class CryptSM4(object): def __init__(self): self.rk = [] def T(self,",
"return sum(output) def encrypt(self, x): \"\"\"加密函数 Args: x (int): 需加密的数据",
"output_list = [] for x in input_list: if mode ==",
"help='初始化向量,cbc模式使用') parser.add_argument('--source_type', choices=['input', 'bin_file', 'image'], help='加密目标类型', default='input') parser.add_argument('--output', help='输出文件名,如不指定则输出至标准输出流') args",
"utf-8 -*- \"\"\" @File : sm4.py @Description : sm4加密算法的实现 @Date",
"PIL import Image import numpy as np source = Image.open(args.source)",
"= 1 # 解密 class CryptSM4(object): def __init__(self): self.rk =",
"for j in range(0, 8, 2)] for i in range(0,",
"key_iv.encode(encoding='UTF8') elif isinstance(key_iv, int): print(len(num2hex(key_iv, width=32))) key_iv = unhexlify(num2hex(key_iv, width=32))",
"if len(key_iv) > BLOCK_BYTE: raise ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE)) return unhexlify('00') * (BLOCK_BYTE",
"@File : sm4.py @Description : sm4加密算法的实现 @Date : 2021/10/28 15:59:51",
"input, args.iv) if args.source_type == 'image': output = hexlify(output).decode() output",
"16) for i in input] K = [input[i] ^ FK[i]",
"= [[int(output[i + j:i + j + 2], 16) for",
"[self._crypt(x, mode) for x in input_list] # 分别加解密 output_list =",
"= [int(hexlify(i), 16) for i in input_list] output_list = []",
"2], 16) for j in range(0, 8, 2)] for i",
"DECRYPT)) if __name__ == '__main__': parser = ArgumentParser(description=\"SM4加解密\") parser.add_argument('crypt', choices=['encrypt',",
"= [int(hexlify(i), 16) for i in input_list] output_list = [self._crypt(x,",
"L_prime(self, input): \"\"\"线性变换L',用于密钥扩展算法 L'(B) = B ^ (B <<< 13)",
"= x output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX)) for o in",
"from utils import S_BOX, BLOCK_BYTE, FK, CK, BLOCK_HEX from utils",
"range(0, 32, 8)] B = [B[i] << (i * 8)",
"= unhexlify(cipher_text) except: pass return unpadding(self._crypt_CBC(cipher_text, iv, DECRYPT)) if __name__",
"args = parser.parse_args() c = CryptSM4() c.set_key(args.key) if args.mode ==",
"1 # 解密 class CryptSM4(object): def __init__(self): self.rk = []",
"ArgumentParser, ArgumentError from binascii import hexlify, unhexlify from utils import",
"open(args.source, 'rb') as f: input = f.read() else: from PIL",
"mode (int, optional): 加密或解密. Defaults to ENCRYPT. Returns: int: 输出",
"rotl, num2hex, bytes_to_list, list_to_bytes, padding, unpadding ENCRYPT = 0 #",
"int(input[2:], 16) elif args.source_type == 'bin_file': with open(args.source, 'rb') as",
"as np source = Image.open(args.source) img = np.array(source.convert('RGBA')) shape =",
"^ (B <<< 18) ^ (B <<< 24) Args: input",
"\"ZelKnow\" from argparse import ArgumentParser, ArgumentError from binascii import hexlify,",
"输出 \"\"\" input = [(x >> i) & (0xffffffff) for",
"* 8) for i in range(4)] C = L_func(sum(B)) return",
"输出 \"\"\" try: cipher_text = unhexlify(cipher_text) except: pass return unpadding(self._crypt_CBC(cipher_text,",
"(0xffffffff) for i in reversed(range(0, 128, 32))] # 加解密时使用的轮密钥顺序不同 for",
"isinstance(key_iv, int): print(len(num2hex(key_iv, width=32))) key_iv = unhexlify(num2hex(key_iv, width=32)) elif not",
"utils import S_BOX, BLOCK_BYTE, FK, CK, BLOCK_HEX from utils import",
"= bytes_to_list(input, BLOCK_BYTE) # 拆分成block input_list = [int(hexlify(i), 16) for",
"is None: raise ArgumentError(\"请输入初始化向量的值\") if args.source_type == 'input': input =",
"numpy as np source = Image.open(args.source) img = np.array(source.convert('RGBA')) shape",
"elif args.output: with open(args.output, \"wb\") as f: f.write(output) else: try:",
"unpadding ENCRYPT = 0 # 加密 DECRYPT = 1 #",
"ENCRYPT. Returns: int: 输出 \"\"\" iv = int(hexlify(self.check_key_iv(iv)), 16) #",
"input): \"\"\"线性变换L',用于密钥扩展算法 L'(B) = B ^ (B <<< 13) ^",
"unhexlify(cipher_text) except: pass return unpadding(self._crypt_ECB(cipher_text, DECRYPT)) def _crypt_CBC(self, input, iv,",
"unhexlify(num2hex(o, width=BLOCK_HEX)) for o in output_list ] return list_to_bytes(output_list) def",
"help='密钥') parser.add_argument('--iv', help='初始化向量,cbc模式使用') parser.add_argument('--source_type', choices=['input', 'bin_file', 'image'], help='加密目标类型', default='input') parser.add_argument('--output',",
"<<< 13) ^ (B <<< 23) Args: input (int): 输入数据",
"\"\"\" @File : sm4.py @Description : sm4加密算法的实现 @Date : 2021/10/28",
"ENCRYPT else reversed(range(32)): input.append(self.F(input[-4:], i)) # 32次迭代运算 output = input[-4:]",
"Returns: bytes: key或iv \"\"\" if isinstance(key_iv, str): key_iv = key_iv.encode(encoding='UTF8')",
"-*- \"\"\" @File : sm4.py @Description : sm4加密算法的实现 @Date :",
"= \"ZelKnow\" from argparse import ArgumentParser, ArgumentError from binascii import",
"not isinstance(key_iv, bytes): raise TypeError(\"密钥或初始化向量类型错误\") if len(key_iv) > BLOCK_BYTE: raise",
"mode=ENCRYPT): \"\"\"ECB加解密函数 Args: x (int): 需加解密的数据 mode (int, optional): 加密或解密.",
"CK[i], self.L_prime)) self.rk = K[4:] def F(self, X, i): \"\"\"轮函数F",
"== ENCRYPT else reversed(range(32)): input.append(self.F(input[-4:], i)) # 32次迭代运算 output =",
"return C def L(self, input): \"\"\"线性变换L,用于轮函数中 L(B) = B ^",
"key = self.check_key_iv(key) input = bytes_to_list(hexlify(key), BLOCK_HEX / 4) input",
"for i in range(0, len(output), 8)] output = np.array(output) output",
"o in output_list ] return list_to_bytes(output_list) def encrypt_CBC(self, plain_text, iv):",
"[S_BOX[(A >> i) & (0x000000ff)] for i in range(0, 32,",
"reversed(range(0, 128, 32))] # 加解密时使用的轮密钥顺序不同 for i in range(32) if",
"range(4)] # 反序变换 return sum(output) def encrypt(self, x): \"\"\"加密函数 Args:",
"input] K = [input[i] ^ FK[i] for i in range(4)]",
"x in input_list: if mode == ENCRYPT: output_list.append(self._crypt(x ^ iv,",
"to ENCRYPT. Returns: int: 输出 \"\"\" input_list = bytes_to_list(input, BLOCK_BYTE)",
"== 'ecb' else c.encrypt_CBC( input, args.iv) else: output = c.decrypt_ECB(input)",
"1] ^ K[i + 2] ^ K[i + 3] ^",
"\"\"\"线性变换L,用于轮函数中 L(B) = B ^ (B <<< 2) ^ (B",
"13) ^ (B <<< 23) Args: input (int): 输入数据 Returns:",
"int(hexlify(self.check_key_iv(iv)), 16) # 初始化向量 input_list = bytes_to_list(input, BLOCK_BYTE) # 拆分成block",
"\"\"\"解密函数 Args: x (int): 需解密的数据 Returns: int: 输出 \"\"\" return",
"key或iv Raises: TypeError: 密钥或初始化向量类型错误 ValueError: 密钥或初始化向量长度过长 Returns: bytes: key或iv \"\"\"",
"B = [B[i] << (i * 8) for i in",
"23) def check_key_iv(self, key_iv): \"\"\"检验key或iv的合法性并转换成字节串 Args: key_iv (int, str or",
"(i * 8) for i in range(4)] C = L_func(sum(B))",
"A (int): 输入数据 L_func (function): 线性变换L Returns: int: 输出数据 \"\"\"",
"return unpadding(self._crypt_ECB(cipher_text, DECRYPT)) def _crypt_CBC(self, input, iv, mode=ENCRYPT): \"\"\"CBC加解密函数 Args:",
"'rb') as f: input = f.read() else: from PIL import",
"需解密的数据 Returns: int: 输出 \"\"\" return self._crypt(x, DECRYPT) def _crypt_ECB(self,",
"__init__(self): self.rk = [] def T(self, A, L_func): \"\"\"合成置换函数T T(.)",
"^ iv) iv = x output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX))",
"输出 \"\"\" return self._crypt_CBC(padding(plain_text), iv, ENCRYPT) def decrypt_CBC(self, cipher_text, iv):",
"X_2, X_3),轮密钥为rk Args: X (list): 输入 i (int): 轮密钥的下标 Returns:",
"in img.flatten()])) if args.crypt == 'encrypt': output = c.encrypt_ECB(input) if",
"x (int): 需解密的数据 Returns: int: 输出 \"\"\" try: cipher_text =",
"加密 DECRYPT = 1 # 解密 class CryptSM4(object): def __init__(self):",
"input_list: if mode == ENCRYPT: output_list.append(self._crypt(x ^ iv, mode)) iv",
"output_list.append(self._crypt(x, mode) ^ iv) iv = x output_list = [",
"# 分别加解密 output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX)) for o in",
"sm4加密算法的实现 @Date : 2021/10/28 15:59:51 @Author : ZelKnow @Github :",
"Returns: int: 输出 \"\"\" try: cipher_text = unhexlify(cipher_text) except: pass",
"input = [(x >> i) & (0xffffffff) for i in",
"output = c.encrypt_ECB(input) if args.mode == 'ecb' else c.encrypt_CBC( input,",
"bytes_to_list, list_to_bytes, padding, unpadding ENCRYPT = 0 # 加密 DECRYPT",
"output_list.append(self._crypt(x ^ iv, mode)) iv = output_list[-1] else: output_list.append(self._crypt(x, mode)",
"== 'input': input = args.source if input[:2].lower() == '0x': input",
"== 'cbc' and args.iv is None: raise ArgumentError(\"请输入初始化向量的值\") if args.source_type",
"输入数据 Returns: int: 输出数据 \"\"\" return input ^ rotl(input, 13)",
"range(0, len(output), 8)] output = np.array(output) output = Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output)",
"^ (B <<< 23) Args: input (int): 输入数据 Returns: int:",
"= [int(i, 16) for i in input] K = [input[i]",
"\"\"\" __author__ = \"ZelKnow\" from argparse import ArgumentParser, ArgumentError from",
"= K[4:] def F(self, X, i): \"\"\"轮函数F F = X_0",
"Returns: int: 输出 \"\"\" input = [(x >> i) &",
"optional): 加密或解密. Defaults to ENCRYPT. Returns: int: 输出 \"\"\" input_list",
"] # 转成字节流 return list_to_bytes(output_list) # 合并 def encrypt_ECB(self, plain_text):",
"raise ArgumentError(\"请输入初始化向量的值\") if args.source_type == 'input': input = args.source if",
"str or bytes): 密钥 \"\"\" key = self.check_key_iv(key) input =",
"key_iv = key_iv.encode(encoding='UTF8') elif isinstance(key_iv, int): print(len(num2hex(key_iv, width=32))) key_iv =",
"def T(self, A, L_func): \"\"\"合成置换函数T T(.) = L(\\tau(.)) Args: A",
"rk) 其中输入为(X_0, X_1, X_2, X_3),轮密钥为rk Args: X (list): 输入 i",
"<< (i * 8) for i in range(4)] C =",
"else: output_list.append(self._crypt(x, mode) ^ iv) iv = x output_list =",
"key或iv \"\"\" if isinstance(key_iv, str): key_iv = key_iv.encode(encoding='UTF8') elif isinstance(key_iv,",
"18) ^ (B <<< 24) Args: input (int): 输入数据 Returns:",
"input): \"\"\"线性变换L,用于轮函数中 L(B) = B ^ (B <<< 2) ^",
"Args: X (list): 输入 i (int): 轮密钥的下标 Returns: int: 输出",
"output.save(args.output) elif args.output: with open(args.output, \"wb\") as f: f.write(output) else:",
"int: 输出 \"\"\" return self._crypt_ECB(padding(plain_text), ENCRYPT) def decrypt_ECB(self, cipher_text): \"\"\"ECB解密函数",
"int: 输出数据 \"\"\" return input ^ rotl(input, 13) ^ rotl(input,",
"= c.decrypt_ECB(input) if args.mode == 'ecb' else c.decrypt_CBC( input, args.iv)",
"DECRYPT)) def _crypt_CBC(self, input, iv, mode=ENCRYPT): \"\"\"CBC加解密函数 Args: x (int):",
"18) ^ rotl(input, 24) def L_prime(self, input): \"\"\"线性变换L',用于密钥扩展算法 L'(B) =",
"if input[:2].lower() == '0x': input = int(input[2:], 16) elif args.source_type",
"optional): 加密或解密. Defaults to ENCRYPT. Returns: int: 输出 \"\"\" input",
"S_BOX, BLOCK_BYTE, FK, CK, BLOCK_HEX from utils import rotl, num2hex,",
"optional): 加密或解密. Defaults to ENCRYPT. Returns: int: 输出 \"\"\" iv",
"Returns: int: 输出 \"\"\" return self._crypt(x, DECRYPT) def _crypt_ECB(self, input,",
"Returns: int: 输出 \"\"\" iv = int(hexlify(self.check_key_iv(iv)), 16) # 初始化向量",
"2)] for i in range(0, len(output), 8)] output = np.array(output)",
"Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output) elif args.output: with open(args.output, \"wb\") as f: f.write(output)",
"int: 输出 \"\"\" return X[0] ^ self.T(X[1] ^ X[2] ^",
"c.decrypt_CBC( input, args.iv) if args.source_type == 'image': output = hexlify(output).decode()",
"== '__main__': parser = ArgumentParser(description=\"SM4加解密\") parser.add_argument('crypt', choices=['encrypt', 'decrypt'], help='加密或解密') parser.add_argument('mode',",
"class CryptSM4(object): def __init__(self): self.rk = [] def T(self, A,",
"for x in input_list] # 分别加解密 output_list = [ unhexlify(num2hex(o,",
"def decrypt_CBC(self, cipher_text, iv): \"\"\"CBC解密函数 Args: x (int): 需解密的数据 Returns:",
"input_list] # 分别加解密 output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX)) for o",
"except: pass return unpadding(self._crypt_CBC(cipher_text, iv, DECRYPT)) if __name__ == '__main__':",
"Defaults to ENCRYPT. Returns: int: 输出 \"\"\" input = [(x",
"x): \"\"\"解密函数 Args: x (int): 需解密的数据 Returns: int: 输出 \"\"\"",
"0 # 加密 DECRYPT = 1 # 解密 class CryptSM4(object):",
"输入 i (int): 轮密钥的下标 Returns: int: 输出 \"\"\" return X[0]",
"rotl(input, 23) def check_key_iv(self, key_iv): \"\"\"检验key或iv的合法性并转换成字节串 Args: key_iv (int, str",
"input = bytes_to_list(hexlify(key), BLOCK_HEX / 4) input = [int(i, 16)",
"for o in output_list ] return list_to_bytes(output_list) def encrypt_CBC(self, plain_text,",
"输出 \"\"\" return self._crypt(x, ENCRYPT) def decrypt(self, x): \"\"\"解密函数 Args:",
"\"\"\" B = [S_BOX[(A >> i) & (0x000000ff)] for i",
"Args: x (int): 需加密的数据 Returns: int: 输出 \"\"\" return self._crypt_CBC(padding(plain_text),",
"or bytes): 密钥 \"\"\" key = self.check_key_iv(key) input = bytes_to_list(hexlify(key),",
"parser.add_argument('--output', help='输出文件名,如不指定则输出至标准输出流') args = parser.parse_args() c = CryptSM4() c.set_key(args.key) if",
"for x in input_list: if mode == ENCRYPT: output_list.append(self._crypt(x ^",
"source = Image.open(args.source) img = np.array(source.convert('RGBA')) shape = img.shape size",
"^ (B <<< 2) ^ (B <<< 10) ^ (B",
"unhexlify(num2hex(key_iv, width=32)) elif not isinstance(key_iv, bytes): raise TypeError(\"密钥或初始化向量类型错误\") if len(key_iv)",
"密钥 \"\"\" key = self.check_key_iv(key) input = bytes_to_list(hexlify(key), BLOCK_HEX /",
"i in input] K = [input[i] ^ FK[i] for i",
"def encrypt_ECB(self, plain_text): \"\"\"ECB加密函数 Args: x (int): 需加密的数据 Returns: int:",
"合并 def encrypt_ECB(self, plain_text): \"\"\"ECB加密函数 Args: x (int): 需加密的数据 Returns:",
"输入数据 Returns: int: 输出数据 \"\"\" return input ^ rotl(input, 2)",
"= unhexlify(num2hex(key_iv, width=32)) elif not isinstance(key_iv, bytes): raise TypeError(\"密钥或初始化向量类型错误\") if",
"轮密钥的下标 Returns: int: 输出 \"\"\" return X[0] ^ self.T(X[1] ^",
"int: 输出数据 \"\"\" B = [S_BOX[(A >> i) & (0x000000ff)]",
"bytes): raise TypeError(\"密钥或初始化向量类型错误\") if len(key_iv) > BLOCK_BYTE: raise ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE)) return",
"@Description : sm4加密算法的实现 @Date : 2021/10/28 15:59:51 @Author : ZelKnow",
"def L(self, input): \"\"\"线性变换L,用于轮函数中 L(B) = B ^ (B <<<",
"'input': input = args.source if input[:2].lower() == '0x': input =",
"i in range(0, len(output), 8)] output = np.array(output) output =",
"^ rotl(input, 10) ^ rotl( input, 18) ^ rotl(input, 24)",
"np.array(source.convert('RGBA')) shape = img.shape size = img.size input = unhexlify(''.join([num2hex(i,",
"sm4.py @Description : sm4加密算法的实现 @Date : 2021/10/28 15:59:51 @Author :",
"parser.add_argument('source', help='加密/解密目标') parser.add_argument('key', help='密钥') parser.add_argument('--iv', help='初始化向量,cbc模式使用') parser.add_argument('--source_type', choices=['input', 'bin_file', 'image'],",
"input, 18) ^ rotl(input, 24) def L_prime(self, input): \"\"\"线性变换L',用于密钥扩展算法 L'(B)",
"#!/usr/bin/env python # -*- encoding: utf-8 -*- \"\"\" @File :",
"<<< 24) Args: input (int): 输入数据 Returns: int: 输出数据 \"\"\"",
"[input[i] ^ FK[i] for i in range(4)] # 存储轮密钥 for",
"\"\"\"ECB解密函数 Args: x (int): 需解密的数据 Returns: int: 输出 \"\"\" try:",
"if args.mode == 'ecb' else c.encrypt_CBC( input, args.iv) else: output",
"def check_key_iv(self, key_iv): \"\"\"检验key或iv的合法性并转换成字节串 Args: key_iv (int, str or bytes):",
"pass return unpadding(self._crypt_ECB(cipher_text, DECRYPT)) def _crypt_CBC(self, input, iv, mode=ENCRYPT): \"\"\"CBC加解密函数",
": https://github.com/ZelKnow \"\"\" __author__ = \"ZelKnow\" from argparse import ArgumentParser,",
"list_to_bytes, padding, unpadding ENCRYPT = 0 # 加密 DECRYPT =",
"return self._crypt_CBC(padding(plain_text), iv, ENCRYPT) def decrypt_CBC(self, cipher_text, iv): \"\"\"CBC解密函数 Args:",
"if args.crypt == 'encrypt': output = c.encrypt_ECB(input) if args.mode ==",
"key_iv): \"\"\"检验key或iv的合法性并转换成字节串 Args: key_iv (int, str or bytes): key或iv Raises:",
"'bin_file': with open(args.source, 'rb') as f: input = f.read() else:",
"def _crypt_CBC(self, input, iv, mode=ENCRYPT): \"\"\"CBC加解密函数 Args: x (int): 需加解密的数据",
"Raises: TypeError: 密钥或初始化向量类型错误 ValueError: 密钥或初始化向量长度过长 Returns: bytes: key或iv \"\"\" if",
"input ^ rotl(input, 13) ^ rotl(input, 23) def check_key_iv(self, key_iv):",
"\"\"\"合成置换函数T T(.) = L(\\tau(.)) Args: A (int): 输入数据 L_func (function):",
"- len(key_iv)) + key_iv def set_key(self, key): \"\"\"设置key Args: key",
"(int): 输入数据 L_func (function): 线性变换L Returns: int: 输出数据 \"\"\" B",
"i (int): 轮密钥的下标 Returns: int: 输出 \"\"\" return X[0] ^",
"for o in output_list ] # 转成字节流 return list_to_bytes(output_list) #",
"mode) ^ iv) iv = x output_list = [ unhexlify(num2hex(o,",
"len(key_iv) > BLOCK_BYTE: raise ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE)) return unhexlify('00') * (BLOCK_BYTE -",
"\"\"\" return input ^ rotl(input, 2) ^ rotl(input, 10) ^",
"'ecb' else c.decrypt_CBC( input, args.iv) if args.source_type == 'image': output",
"F = X_0 ^ T(X_1 ^ X_2 ^ X_3 ^",
"elif args.source_type == 'bin_file': with open(args.source, 'rb') as f: input",
"int: 输出 \"\"\" return self._crypt(x, DECRYPT) def _crypt_ECB(self, input, mode=ENCRYPT):",
"cipher_text): \"\"\"ECB解密函数 Args: x (int): 需解密的数据 Returns: int: 输出 \"\"\"",
"8, 2)] for i in range(0, len(output), 8)] output =",
"\"\"\"检验key或iv的合法性并转换成字节串 Args: key_iv (int, str or bytes): key或iv Raises: TypeError:",
"\"\"\" try: cipher_text = unhexlify(cipher_text) except: pass return unpadding(self._crypt_ECB(cipher_text, DECRYPT))",
"x (int): 需加密的数据 Returns: int: 输出 \"\"\" return self._crypt(x, ENCRYPT)",
"bytes): key或iv Raises: TypeError: 密钥或初始化向量类型错误 ValueError: 密钥或初始化向量长度过长 Returns: bytes: key或iv",
"unhexlify(cipher_text) except: pass return unpadding(self._crypt_CBC(cipher_text, iv, DECRYPT)) if __name__ ==",
"output = c.decrypt_ECB(input) if args.mode == 'ecb' else c.decrypt_CBC( input,",
"o in output_list ] # 转成字节流 return list_to_bytes(output_list) # 合并",
"mode == ENCRYPT: output_list.append(self._crypt(x ^ iv, mode)) iv = output_list[-1]",
"X[3] ^ self.rk[i], self.L) def _crypt(self, x, mode=ENCRYPT): \"\"\"加解密函数 Args:",
"ENCRYPT. Returns: int: 输出 \"\"\" input = [(x >> i)",
"= hexlify(output).decode() output = output[:size * 2] output = [[int(output[i",
"rotl( input, 18) ^ rotl(input, 24) def L_prime(self, input): \"\"\"线性变换L',用于密钥扩展算法",
"padding, unpadding ENCRYPT = 0 # 加密 DECRYPT = 1",
"(B <<< 10) ^ (B <<< 18) ^ (B <<<",
"Args: key_iv (int, str or bytes): key或iv Raises: TypeError: 密钥或初始化向量类型错误",
"Image import numpy as np source = Image.open(args.source) img =",
"unhexlify(num2hex(o, width=BLOCK_HEX)) for o in output_list ] # 转成字节流 return",
": 2021/10/28 15:59:51 @Author : ZelKnow @Github : https://github.com/ZelKnow \"\"\"",
"= [output[i] << (i * 32) for i in range(4)]",
"Returns: int: 输出 \"\"\" input_list = bytes_to_list(input, BLOCK_BYTE) # 将输入拆分成block",
"encrypt_CBC(self, plain_text, iv): \"\"\"CBC加密函数 Args: x (int): 需加密的数据 Returns: int:",
"x): \"\"\"加密函数 Args: x (int): 需加密的数据 Returns: int: 输出 \"\"\"",
": sm4加密算法的实现 @Date : 2021/10/28 15:59:51 @Author : ZelKnow @Github",
"^ rotl(input, 24) def L_prime(self, input): \"\"\"线性变换L',用于密钥扩展算法 L'(B) = B",
"args.iv) else: output = c.decrypt_ECB(input) if args.mode == 'ecb' else",
"Returns: int: 输出 \"\"\" return self._crypt_ECB(padding(plain_text), ENCRYPT) def decrypt_ECB(self, cipher_text):",
"def _crypt(self, x, mode=ENCRYPT): \"\"\"加解密函数 Args: x (int): 需加解密的数据 mode",
"i in img.flatten()])) if args.crypt == 'encrypt': output = c.encrypt_ECB(input)",
"BLOCK_BYTE: raise ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE)) return unhexlify('00') * (BLOCK_BYTE - len(key_iv)) +",
"i in range(32) if mode == ENCRYPT else reversed(range(32)): input.append(self.F(input[-4:],",
"else c.encrypt_CBC( input, args.iv) else: output = c.decrypt_ECB(input) if args.mode",
"args.iv is None: raise ArgumentError(\"请输入初始化向量的值\") if args.source_type == 'input': input",
"CryptSM4() c.set_key(args.key) if args.mode == 'cbc' and args.iv is None:",
"转成字节流 return list_to_bytes(output_list) # 合并 def encrypt_ECB(self, plain_text): \"\"\"ECB加密函数 Args:",
"parser.add_argument('key', help='密钥') parser.add_argument('--iv', help='初始化向量,cbc模式使用') parser.add_argument('--source_type', choices=['input', 'bin_file', 'image'], help='加密目标类型', default='input')",
"^ rotl( input, 18) ^ rotl(input, 24) def L_prime(self, input):",
": sm4.py @Description : sm4加密算法的实现 @Date : 2021/10/28 15:59:51 @Author",
"# 合并 def encrypt_ECB(self, plain_text): \"\"\"ECB加密函数 Args: x (int): 需加密的数据",
"range(32) if mode == ENCRYPT else reversed(range(32)): input.append(self.F(input[-4:], i)) #",
"return self._crypt_ECB(padding(plain_text), ENCRYPT) def decrypt_ECB(self, cipher_text): \"\"\"ECB解密函数 Args: x (int):",
"需解密的数据 Returns: int: 输出 \"\"\" try: cipher_text = unhexlify(cipher_text) except:",
"(list): 输入 i (int): 轮密钥的下标 Returns: int: 输出 \"\"\" return",
"输出 \"\"\" input_list = bytes_to_list(input, BLOCK_BYTE) # 将输入拆分成block input_list =",
"for i in input_list] output_list = [] for x in",
"if args.source_type == 'input': input = args.source if input[:2].lower() ==",
"def set_key(self, key): \"\"\"设置key Args: key (int, str or bytes):",
"16) for i in input_list] output_list = [self._crypt(x, mode) for",
"iv, DECRYPT)) if __name__ == '__main__': parser = ArgumentParser(description=\"SM4加解密\") parser.add_argument('crypt',",
"argparse import ArgumentParser, ArgumentError from binascii import hexlify, unhexlify from",
"A, L_func): \"\"\"合成置换函数T T(.) = L(\\tau(.)) Args: A (int): 输入数据",
"return X[0] ^ self.T(X[1] ^ X[2] ^ X[3] ^ self.rk[i],",
"<filename>sm4.py #!/usr/bin/env python # -*- encoding: utf-8 -*- \"\"\" @File",
"from PIL import Image import numpy as np source =",
"def __init__(self): self.rk = [] def T(self, A, L_func): \"\"\"合成置换函数T",
"= Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output) elif args.output: with open(args.output, \"wb\") as f:",
"= L_func(sum(B)) return C def L(self, input): \"\"\"线性变换L,用于轮函数中 L(B) =",
"input_list] output_list = [] for x in input_list: if mode",
"= c.encrypt_ECB(input) if args.mode == 'ecb' else c.encrypt_CBC( input, args.iv)",
"parser.add_argument('crypt', choices=['encrypt', 'decrypt'], help='加密或解密') parser.add_argument('mode', choices=['ecb', 'cbc'], help='加密模式') parser.add_argument('source', help='加密/解密目标')",
"加密或解密. Defaults to ENCRYPT. Returns: int: 输出 \"\"\" input_list =",
"Returns: int: 输出数据 \"\"\" B = [S_BOX[(A >> i) &",
"/ 4) input = [int(i, 16) for i in input]",
"width=BLOCK_HEX)) for o in output_list ] # 转成字节流 return list_to_bytes(output_list)",
"输出 \"\"\" iv = int(hexlify(self.check_key_iv(iv)), 16) # 初始化向量 input_list =",
"10) ^ (B <<< 18) ^ (B <<< 24) Args:",
"in input_list: if mode == ENCRYPT: output_list.append(self._crypt(x ^ iv, mode))",
"return unpadding(self._crypt_CBC(cipher_text, iv, DECRYPT)) if __name__ == '__main__': parser =",
"<<< 2) ^ (B <<< 10) ^ (B <<< 18)",
"[output[i] << (i * 32) for i in range(4)] #",
"bytes_to_list(input, BLOCK_BYTE) # 拆分成block input_list = [int(hexlify(i), 16) for i",
"[] for x in input_list: if mode == ENCRYPT: output_list.append(self._crypt(x",
"\"\"\" return self._crypt(x, ENCRYPT) def decrypt(self, x): \"\"\"解密函数 Args: x",
"if isinstance(key_iv, str): key_iv = key_iv.encode(encoding='UTF8') elif isinstance(key_iv, int): print(len(num2hex(key_iv,",
"input = int(input[2:], 16) elif args.source_type == 'bin_file': with open(args.source,",
"__name__ == '__main__': parser = ArgumentParser(description=\"SM4加解密\") parser.add_argument('crypt', choices=['encrypt', 'decrypt'], help='加密或解密')",
"* 32) for i in range(4)] # 反序变换 return sum(output)",
"if args.mode == 'cbc' and args.iv is None: raise ArgumentError(\"请输入初始化向量的值\")",
"input_list = [int(hexlify(i), 16) for i in input_list] output_list =",
"choices=['encrypt', 'decrypt'], help='加密或解密') parser.add_argument('mode', choices=['ecb', 'cbc'], help='加密模式') parser.add_argument('source', help='加密/解密目标') parser.add_argument('key',",
"iv, mode=ENCRYPT): \"\"\"CBC加解密函数 Args: x (int): 需加解密的数据 mode (int, optional):",
"^ (B <<< 13) ^ (B <<< 23) Args: input",
"img = np.array(source.convert('RGBA')) shape = img.shape size = img.size input",
"input = unhexlify(''.join([num2hex(i, width=2) for i in img.flatten()])) if args.crypt",
"_crypt_ECB(self, input, mode=ENCRYPT): \"\"\"ECB加解密函数 Args: x (int): 需加解密的数据 mode (int,",
"Args: input (int): 输入数据 Returns: int: 输出数据 \"\"\" return input",
"^ K[i + 3] ^ CK[i], self.L_prime)) self.rk = K[4:]",
"+ j + 2], 16) for j in range(0, 8,",
"len(key_iv)) + key_iv def set_key(self, key): \"\"\"设置key Args: key (int,",
"self.L) def _crypt(self, x, mode=ENCRYPT): \"\"\"加解密函数 Args: x (int): 需加解密的数据",
"-*- encoding: utf-8 -*- \"\"\" @File : sm4.py @Description :",
"[int(i, 16) for i in input] K = [input[i] ^",
"mode) for x in input_list] # 分别加解密 output_list = [",
"return list_to_bytes(output_list) # 合并 def encrypt_ECB(self, plain_text): \"\"\"ECB加密函数 Args: x",
"BLOCK_HEX from utils import rotl, num2hex, bytes_to_list, list_to_bytes, padding, unpadding",
"== ENCRYPT: output_list.append(self._crypt(x ^ iv, mode)) iv = output_list[-1] else:",
"cipher_text, iv): \"\"\"CBC解密函数 Args: x (int): 需解密的数据 Returns: int: 输出",
"(function): 线性变换L Returns: int: 输出数据 \"\"\" B = [S_BOX[(A >>",
"input, mode=ENCRYPT): \"\"\"ECB加解密函数 Args: x (int): 需加解密的数据 mode (int, optional):",
"# 密钥扩展算法 K.append(K[i] ^ self.T(K[i + 1] ^ K[i +",
"13) ^ rotl(input, 23) def check_key_iv(self, key_iv): \"\"\"检验key或iv的合法性并转换成字节串 Args: key_iv",
"# 将输入拆分成block input_list = [int(hexlify(i), 16) for i in input_list]",
"else: from PIL import Image import numpy as np source",
"K = [input[i] ^ FK[i] for i in range(4)] #",
"for i in range(32): # 密钥扩展算法 K.append(K[i] ^ self.T(K[i +",
"[int(hexlify(i), 16) for i in input_list] output_list = [] for",
"'decrypt'], help='加密或解密') parser.add_argument('mode', choices=['ecb', 'cbc'], help='加密模式') parser.add_argument('source', help='加密/解密目标') parser.add_argument('key', help='密钥')",
"for i in img.flatten()])) if args.crypt == 'encrypt': output =",
"in range(32): # 密钥扩展算法 K.append(K[i] ^ self.T(K[i + 1] ^",
"args.source_type == 'image': output = hexlify(output).decode() output = output[:size *",
"iv, ENCRYPT) def decrypt_CBC(self, cipher_text, iv): \"\"\"CBC解密函数 Args: x (int):",
"in input_list] output_list = [self._crypt(x, mode) for x in input_list]",
"ENCRYPT) def decrypt_ECB(self, cipher_text): \"\"\"ECB解密函数 Args: x (int): 需解密的数据 Returns:",
"^ (B <<< 10) ^ (B <<< 18) ^ (B",
"= ArgumentParser(description=\"SM4加解密\") parser.add_argument('crypt', choices=['encrypt', 'decrypt'], help='加密或解密') parser.add_argument('mode', choices=['ecb', 'cbc'], help='加密模式')",
"'ecb' else c.encrypt_CBC( input, args.iv) else: output = c.decrypt_ECB(input) if",
"x (int): 需加密的数据 Returns: int: 输出 \"\"\" return self._crypt_ECB(padding(plain_text), ENCRYPT)",
"Returns: int: 输出数据 \"\"\" return input ^ rotl(input, 13) ^",
"choices=['ecb', 'cbc'], help='加密模式') parser.add_argument('source', help='加密/解密目标') parser.add_argument('key', help='密钥') parser.add_argument('--iv', help='初始化向量,cbc模式使用') parser.add_argument('--source_type',",
"args.mode == 'ecb' else c.encrypt_CBC( input, args.iv) else: output =",
"choices=['input', 'bin_file', 'image'], help='加密目标类型', default='input') parser.add_argument('--output', help='输出文件名,如不指定则输出至标准输出流') args = parser.parse_args()",
"^ T(X_1 ^ X_2 ^ X_3 ^ rk) 其中输入为(X_0, X_1,",
"Args: x (int): 需加密的数据 Returns: int: 输出 \"\"\" return self._crypt(x,",
"= args.source if input[:2].lower() == '0x': input = int(input[2:], 16)",
"24) def L_prime(self, input): \"\"\"线性变换L',用于密钥扩展算法 L'(B) = B ^ (B",
"(int, optional): 加密或解密. Defaults to ENCRYPT. Returns: int: 输出 \"\"\"",
"输出 \"\"\" return self._crypt(x, DECRYPT) def _crypt_ECB(self, input, mode=ENCRYPT): \"\"\"ECB加解密函数",
"mode)) iv = output_list[-1] else: output_list.append(self._crypt(x, mode) ^ iv) iv",
"size = img.size input = unhexlify(''.join([num2hex(i, width=2) for i in",
"& (0x000000ff)] for i in range(0, 32, 8)] B =",
"== '0x': input = int(input[2:], 16) elif args.source_type == 'bin_file':",
"i in input_list] output_list = [] for x in input_list:",
"int: 输出 \"\"\" input_list = bytes_to_list(input, BLOCK_BYTE) # 将输入拆分成block input_list",
"(0x000000ff)] for i in range(0, 32, 8)] B = [B[i]",
"for i in input_list] output_list = [self._crypt(x, mode) for x",
"except: pass return unpadding(self._crypt_ECB(cipher_text, DECRYPT)) def _crypt_CBC(self, input, iv, mode=ENCRYPT):",
"\"\"\"CBC加解密函数 Args: x (int): 需加解密的数据 mode (int, optional): 加密或解密. Defaults",
"= output[:size * 2] output = [[int(output[i + j:i +",
"8)] output = np.array(output) output = Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output) elif args.output:",
"K[i + 3] ^ CK[i], self.L_prime)) self.rk = K[4:] def",
"密钥或初始化向量类型错误 ValueError: 密钥或初始化向量长度过长 Returns: bytes: key或iv \"\"\" if isinstance(key_iv, str):",
"8)] B = [B[i] << (i * 8) for i",
"2] ^ K[i + 3] ^ CK[i], self.L_prime)) self.rk =",
"int: 输出数据 \"\"\" return input ^ rotl(input, 2) ^ rotl(input,",
"i in range(32): # 密钥扩展算法 K.append(K[i] ^ self.T(K[i + 1]",
"B = [S_BOX[(A >> i) & (0x000000ff)] for i in",
"(B <<< 2) ^ (B <<< 10) ^ (B <<<",
"\"\"\" return self._crypt_ECB(padding(plain_text), ENCRYPT) def decrypt_ECB(self, cipher_text): \"\"\"ECB解密函数 Args: x",
"decrypt(self, x): \"\"\"解密函数 Args: x (int): 需解密的数据 Returns: int: 输出",
"分别加解密 output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX)) for o in output_list",
"self._crypt_CBC(padding(plain_text), iv, ENCRYPT) def decrypt_CBC(self, cipher_text, iv): \"\"\"CBC解密函数 Args: x",
"default='input') parser.add_argument('--output', help='输出文件名,如不指定则输出至标准输出流') args = parser.parse_args() c = CryptSM4() c.set_key(args.key)",
"= unhexlify(''.join([num2hex(i, width=2) for i in img.flatten()])) if args.crypt ==",
"bytes_to_list(hexlify(key), BLOCK_HEX / 4) input = [int(i, 16) for i",
"输出 \"\"\" try: cipher_text = unhexlify(cipher_text) except: pass return unpadding(self._crypt_ECB(cipher_text,",
"\"\"\" key = self.check_key_iv(key) input = bytes_to_list(hexlify(key), BLOCK_HEX / 4)",
"Defaults to ENCRYPT. Returns: int: 输出 \"\"\" iv = int(hexlify(self.check_key_iv(iv)),",
"for i in range(32) if mode == ENCRYPT else reversed(range(32)):",
"key): \"\"\"设置key Args: key (int, str or bytes): 密钥 \"\"\"",
"return self._crypt(x, DECRYPT) def _crypt_ECB(self, input, mode=ENCRYPT): \"\"\"ECB加解密函数 Args: x",
"in input] K = [input[i] ^ FK[i] for i in",
"args.crypt == 'encrypt': output = c.encrypt_ECB(input) if args.mode == 'ecb'",
"\"\"\"轮函数F F = X_0 ^ T(X_1 ^ X_2 ^ X_3",
"output = output[:size * 2] output = [[int(output[i + j:i",
"self.T(K[i + 1] ^ K[i + 2] ^ K[i +",
"(int): 需加密的数据 Returns: int: 输出 \"\"\" return self._crypt_ECB(padding(plain_text), ENCRYPT) def",
"int: 输出 \"\"\" try: cipher_text = unhexlify(cipher_text) except: pass return",
"\"\"\"CBC解密函数 Args: x (int): 需解密的数据 Returns: int: 输出 \"\"\" try:",
"str): key_iv = key_iv.encode(encoding='UTF8') elif isinstance(key_iv, int): print(len(num2hex(key_iv, width=32))) key_iv",
"# 转成字节流 return list_to_bytes(output_list) # 合并 def encrypt_ECB(self, plain_text): \"\"\"ECB加密函数",
"32次迭代运算 output = input[-4:] output = [output[i] << (i *",
"decrypt_ECB(self, cipher_text): \"\"\"ECB解密函数 Args: x (int): 需解密的数据 Returns: int: 输出",
"print(len(num2hex(key_iv, width=32))) key_iv = unhexlify(num2hex(key_iv, width=32)) elif not isinstance(key_iv, bytes):",
"to ENCRYPT. Returns: int: 输出 \"\"\" iv = int(hexlify(self.check_key_iv(iv)), 16)",
"= Image.open(args.source) img = np.array(source.convert('RGBA')) shape = img.shape size =",
"set_key(self, key): \"\"\"设置key Args: key (int, str or bytes): 密钥",
"self.rk = K[4:] def F(self, X, i): \"\"\"轮函数F F =",
"(B <<< 24) Args: input (int): 输入数据 Returns: int: 输出数据",
"Returns: int: 输出 \"\"\" return self._crypt_CBC(padding(plain_text), iv, ENCRYPT) def decrypt_CBC(self,",
"^ rotl(input, 2) ^ rotl(input, 10) ^ rotl( input, 18)",
"10) ^ rotl( input, 18) ^ rotl(input, 24) def L_prime(self,",
"ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE)) return unhexlify('00') * (BLOCK_BYTE - len(key_iv)) + key_iv def",
"rotl(input, 10) ^ rotl( input, 18) ^ rotl(input, 24) def",
"width=32))) key_iv = unhexlify(num2hex(key_iv, width=32)) elif not isinstance(key_iv, bytes): raise",
"* 2] output = [[int(output[i + j:i + j +",
"self.check_key_iv(key) input = bytes_to_list(hexlify(key), BLOCK_HEX / 4) input = [int(i,",
"self._crypt_ECB(padding(plain_text), ENCRYPT) def decrypt_ECB(self, cipher_text): \"\"\"ECB解密函数 Args: x (int): 需解密的数据",
"def encrypt(self, x): \"\"\"加密函数 Args: x (int): 需加密的数据 Returns: int:",
"== 'bin_file': with open(args.source, 'rb') as f: input = f.read()",
"^ X_3 ^ rk) 其中输入为(X_0, X_1, X_2, X_3),轮密钥为rk Args: X",
"output = Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output) elif args.output: with open(args.output, \"wb\") as",
"+ 2] ^ K[i + 3] ^ CK[i], self.L_prime)) self.rk",
"reversed(range(32)): input.append(self.F(input[-4:], i)) # 32次迭代运算 output = input[-4:] output =",
"\"\"\" return self._crypt_CBC(padding(plain_text), iv, ENCRYPT) def decrypt_CBC(self, cipher_text, iv): \"\"\"CBC解密函数",
"X[2] ^ X[3] ^ self.rk[i], self.L) def _crypt(self, x, mode=ENCRYPT):",
"* (BLOCK_BYTE - len(key_iv)) + key_iv def set_key(self, key): \"\"\"设置key",
"CryptSM4(object): def __init__(self): self.rk = [] def T(self, A, L_func):",
"self.rk[i], self.L) def _crypt(self, x, mode=ENCRYPT): \"\"\"加解密函数 Args: x (int):",
"\"\"\"CBC加密函数 Args: x (int): 需加密的数据 Returns: int: 输出 \"\"\" return",
"int: 输出 \"\"\" input = [(x >> i) & (0xffffffff)",
">> i) & (0xffffffff) for i in reversed(range(0, 128, 32))]",
"to ENCRYPT. Returns: int: 输出 \"\"\" input = [(x >>",
"\"\"\" input = [(x >> i) & (0xffffffff) for i",
"i in range(4)] C = L_func(sum(B)) return C def L(self,",
"i in input_list] output_list = [self._crypt(x, mode) for x in",
"> BLOCK_BYTE: raise ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE)) return unhexlify('00') * (BLOCK_BYTE - len(key_iv))",
"线性变换L Returns: int: 输出数据 \"\"\" B = [S_BOX[(A >> i)",
"str or bytes): key或iv Raises: TypeError: 密钥或初始化向量类型错误 ValueError: 密钥或初始化向量长度过长 Returns:",
"cipher_text = unhexlify(cipher_text) except: pass return unpadding(self._crypt_ECB(cipher_text, DECRYPT)) def _crypt_CBC(self,",
"T(X_1 ^ X_2 ^ X_3 ^ rk) 其中输入为(X_0, X_1, X_2,",
"= unhexlify(cipher_text) except: pass return unpadding(self._crypt_ECB(cipher_text, DECRYPT)) def _crypt_CBC(self, input,",
"num2hex, bytes_to_list, list_to_bytes, padding, unpadding ENCRYPT = 0 # 加密",
"# 加密 DECRYPT = 1 # 解密 class CryptSM4(object): def",
"isinstance(key_iv, str): key_iv = key_iv.encode(encoding='UTF8') elif isinstance(key_iv, int): print(len(num2hex(key_iv, width=32)))",
"= key_iv.encode(encoding='UTF8') elif isinstance(key_iv, int): print(len(num2hex(key_iv, width=32))) key_iv = unhexlify(num2hex(key_iv,",
"output = np.array(output) output = Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output) elif args.output: with",
"f: input = f.read() else: from PIL import Image import",
"if args.mode == 'ecb' else c.decrypt_CBC( input, args.iv) if args.source_type",
"Args: key (int, str or bytes): 密钥 \"\"\" key =",
"utils import rotl, num2hex, bytes_to_list, list_to_bytes, padding, unpadding ENCRYPT =",
"L_func(sum(B)) return C def L(self, input): \"\"\"线性变换L,用于轮函数中 L(B) = B",
"key (int, str or bytes): 密钥 \"\"\" key = self.check_key_iv(key)",
"^ (B <<< 24) Args: input (int): 输入数据 Returns: int:",
"= np.array(source.convert('RGBA')) shape = img.shape size = img.size input =",
"DECRYPT = 1 # 解密 class CryptSM4(object): def __init__(self): self.rk",
"with open(args.output, \"wb\") as f: f.write(output) else: try: print(output.decode()) except:",
"B ^ (B <<< 2) ^ (B <<< 10) ^",
"from utils import rotl, num2hex, bytes_to_list, list_to_bytes, padding, unpadding ENCRYPT",
"== 'image': output = hexlify(output).decode() output = output[:size * 2]",
"'image'], help='加密目标类型', default='input') parser.add_argument('--output', help='输出文件名,如不指定则输出至标准输出流') args = parser.parse_args() c =",
"[] def T(self, A, L_func): \"\"\"合成置换函数T T(.) = L(\\tau(.)) Args:",
"(int): 需加密的数据 Returns: int: 输出 \"\"\" return self._crypt(x, ENCRYPT) def",
"Args: x (int): 需加密的数据 Returns: int: 输出 \"\"\" return self._crypt_ECB(padding(plain_text),",
"self._crypt(x, DECRYPT) def _crypt_ECB(self, input, mode=ENCRYPT): \"\"\"ECB加解密函数 Args: x (int):",
"j:i + j + 2], 16) for j in range(0,",
"unpadding(self._crypt_CBC(cipher_text, iv, DECRYPT)) if __name__ == '__main__': parser = ArgumentParser(description=\"SM4加解密\")",
"= [(x >> i) & (0xffffffff) for i in reversed(range(0,",
"int: 输出 \"\"\" return self._crypt(x, ENCRYPT) def decrypt(self, x): \"\"\"解密函数",
"in input_list] # 分别加解密 output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX)) for",
"= output_list[-1] else: output_list.append(self._crypt(x, mode) ^ iv) iv = x",
"check_key_iv(self, key_iv): \"\"\"检验key或iv的合法性并转换成字节串 Args: key_iv (int, str or bytes): key或iv",
"def encrypt_CBC(self, plain_text, iv): \"\"\"CBC加密函数 Args: x (int): 需加密的数据 Returns:",
"output_list[-1] else: output_list.append(self._crypt(x, mode) ^ iv) iv = x output_list",
"^ X[3] ^ self.rk[i], self.L) def _crypt(self, x, mode=ENCRYPT): \"\"\"加解密函数",
"open(args.output, \"wb\") as f: f.write(output) else: try: print(output.decode()) except: print(hexlify(output).decode())",
"\"\"\" try: cipher_text = unhexlify(cipher_text) except: pass return unpadding(self._crypt_CBC(cipher_text, iv,",
"= X_0 ^ T(X_1 ^ X_2 ^ X_3 ^ rk)",
"加密或解密. Defaults to ENCRYPT. Returns: int: 输出 \"\"\" input =",
"mode == ENCRYPT else reversed(range(32)): input.append(self.F(input[-4:], i)) # 32次迭代运算 output",
"L_func): \"\"\"合成置换函数T T(.) = L(\\tau(.)) Args: A (int): 输入数据 L_func",
"x (int): 需解密的数据 Returns: int: 输出 \"\"\" return self._crypt(x, DECRYPT)",
"plain_text): \"\"\"ECB加密函数 Args: x (int): 需加密的数据 Returns: int: 输出 \"\"\"",
"# 拆分成block input_list = [int(hexlify(i), 16) for i in input_list]",
">> i) & (0x000000ff)] for i in range(0, 32, 8)]",
"_crypt_CBC(self, input, iv, mode=ENCRYPT): \"\"\"CBC加解密函数 Args: x (int): 需加解密的数据 mode",
"(i * 32) for i in range(4)] # 反序变换 return",
"# 存储轮密钥 for i in range(32): # 密钥扩展算法 K.append(K[i] ^",
"i)) # 32次迭代运算 output = input[-4:] output = [output[i] <<",
"(int, str or bytes): 密钥 \"\"\" key = self.check_key_iv(key) input",
"[ unhexlify(num2hex(o, width=BLOCK_HEX)) for o in output_list ] return list_to_bytes(output_list)",
"input[-4:] output = [output[i] << (i * 32) for i",
"in range(32) if mode == ENCRYPT else reversed(range(32)): input.append(self.F(input[-4:], i))",
"for i in range(4)] C = L_func(sum(B)) return C def",
"iv) iv = x output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX)) for",
"需加密的数据 Returns: int: 输出 \"\"\" return self._crypt_ECB(padding(plain_text), ENCRYPT) def decrypt_ECB(self,",
"(B <<< 13) ^ (B <<< 23) Args: input (int):",
"else c.decrypt_CBC( input, args.iv) if args.source_type == 'image': output =",
"X_3),轮密钥为rk Args: X (list): 输入 i (int): 轮密钥的下标 Returns: int:",
"input, iv, mode=ENCRYPT): \"\"\"CBC加解密函数 Args: x (int): 需加解密的数据 mode (int,",
"for i in input] K = [input[i] ^ FK[i] for",
"__author__ = \"ZelKnow\" from argparse import ArgumentParser, ArgumentError from binascii",
"output = [output[i] << (i * 32) for i in",
"len(output), 8)] output = np.array(output) output = Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output) elif",
"input (int): 输入数据 Returns: int: 输出数据 \"\"\" return input ^",
"+ 1] ^ K[i + 2] ^ K[i + 3]",
"for i in range(4)] # 存储轮密钥 for i in range(32):",
"4) input = [int(i, 16) for i in input] K",
"(int): 需加密的数据 Returns: int: 输出 \"\"\" return self._crypt_CBC(padding(plain_text), iv, ENCRYPT)",
"rotl(input, 13) ^ rotl(input, 23) def check_key_iv(self, key_iv): \"\"\"检验key或iv的合法性并转换成字节串 Args:",
"binascii import hexlify, unhexlify from utils import S_BOX, BLOCK_BYTE, FK,",
"'0x': input = int(input[2:], 16) elif args.source_type == 'bin_file': with",
"& (0xffffffff) for i in reversed(range(0, 128, 32))] # 加解密时使用的轮密钥顺序不同",
"BLOCK_BYTE, FK, CK, BLOCK_HEX from utils import rotl, num2hex, bytes_to_list,",
"\"\"\"线性变换L',用于密钥扩展算法 L'(B) = B ^ (B <<< 13) ^ (B",
"反序变换 return sum(output) def encrypt(self, x): \"\"\"加密函数 Args: x (int):",
"^ X_2 ^ X_3 ^ rk) 其中输入为(X_0, X_1, X_2, X_3),轮密钥为rk",
"] return list_to_bytes(output_list) def encrypt_CBC(self, plain_text, iv): \"\"\"CBC加密函数 Args: x",
"iv): \"\"\"CBC加密函数 Args: x (int): 需加密的数据 Returns: int: 输出 \"\"\"",
"K[i + 2] ^ K[i + 3] ^ CK[i], self.L_prime))",
"(int): 需解密的数据 Returns: int: 输出 \"\"\" return self._crypt(x, DECRYPT) def",
"<<< 10) ^ (B <<< 18) ^ (B <<< 24)",
"密钥扩展算法 K.append(K[i] ^ self.T(K[i + 1] ^ K[i + 2]",
"return self._crypt(x, ENCRYPT) def decrypt(self, x): \"\"\"解密函数 Args: x (int):",
"= [ unhexlify(num2hex(o, width=BLOCK_HEX)) for o in output_list ] return",
"<<< 18) ^ (B <<< 24) Args: input (int): 输入数据",
"self._crypt(x, ENCRYPT) def decrypt(self, x): \"\"\"解密函数 Args: x (int): 需解密的数据",
"C def L(self, input): \"\"\"线性变换L,用于轮函数中 L(B) = B ^ (B",
"import numpy as np source = Image.open(args.source) img = np.array(source.convert('RGBA'))",
"i in reversed(range(0, 128, 32))] # 加解密时使用的轮密钥顺序不同 for i in",
"help='加密模式') parser.add_argument('source', help='加密/解密目标') parser.add_argument('key', help='密钥') parser.add_argument('--iv', help='初始化向量,cbc模式使用') parser.add_argument('--source_type', choices=['input', 'bin_file',",
"elif isinstance(key_iv, int): print(len(num2hex(key_iv, width=32))) key_iv = unhexlify(num2hex(key_iv, width=32)) elif",
"^ self.T(X[1] ^ X[2] ^ X[3] ^ self.rk[i], self.L) def",
"iv, mode)) iv = output_list[-1] else: output_list.append(self._crypt(x, mode) ^ iv)",
"parser.add_argument('--iv', help='初始化向量,cbc模式使用') parser.add_argument('--source_type', choices=['input', 'bin_file', 'image'], help='加密目标类型', default='input') parser.add_argument('--output', help='输出文件名,如不指定则输出至标准输出流')",
"help='输出文件名,如不指定则输出至标准输出流') args = parser.parse_args() c = CryptSM4() c.set_key(args.key) if args.mode",
"DECRYPT) def _crypt_ECB(self, input, mode=ENCRYPT): \"\"\"ECB加解密函数 Args: x (int): 需加解密的数据",
"try: cipher_text = unhexlify(cipher_text) except: pass return unpadding(self._crypt_ECB(cipher_text, DECRYPT)) def",
"16) for i in input_list] output_list = [] for x",
"i in range(4)] # 存储轮密钥 for i in range(32): #",
"input = args.source if input[:2].lower() == '0x': input = int(input[2:],",
"^ CK[i], self.L_prime)) self.rk = K[4:] def F(self, X, i):",
"# 32次迭代运算 output = input[-4:] output = [output[i] << (i",
"in range(4)] # 反序变换 return sum(output) def encrypt(self, x): \"\"\"加密函数",
"'image': output = hexlify(output).decode() output = output[:size * 2] output",
"= int(hexlify(self.check_key_iv(iv)), 16) # 初始化向量 input_list = bytes_to_list(input, BLOCK_BYTE) #",
"T(.) = L(\\tau(.)) Args: A (int): 输入数据 L_func (function): 线性变换L",
"c.encrypt_CBC( input, args.iv) else: output = c.decrypt_ECB(input) if args.mode ==",
"24) Args: input (int): 输入数据 Returns: int: 输出数据 \"\"\" return",
"F(self, X, i): \"\"\"轮函数F F = X_0 ^ T(X_1 ^",
"ENCRYPT) def decrypt(self, x): \"\"\"解密函数 Args: x (int): 需解密的数据 Returns:",
"elif not isinstance(key_iv, bytes): raise TypeError(\"密钥或初始化向量类型错误\") if len(key_iv) > BLOCK_BYTE:",
"\"\"\" if isinstance(key_iv, str): key_iv = key_iv.encode(encoding='UTF8') elif isinstance(key_iv, int):",
"= img.shape size = img.size input = unhexlify(''.join([num2hex(i, width=2) for",
"args.iv) if args.source_type == 'image': output = hexlify(output).decode() output =",
"else: output = c.decrypt_ECB(input) if args.mode == 'ecb' else c.decrypt_CBC(",
"encoding: utf-8 -*- \"\"\" @File : sm4.py @Description : sm4加密算法的实现",
"^ rotl(input, 13) ^ rotl(input, 23) def check_key_iv(self, key_iv): \"\"\"检验key或iv的合法性并转换成字节串",
"output_list ] # 转成字节流 return list_to_bytes(output_list) # 合并 def encrypt_ECB(self,",
"L(B) = B ^ (B <<< 2) ^ (B <<<",
"parser = ArgumentParser(description=\"SM4加解密\") parser.add_argument('crypt', choices=['encrypt', 'decrypt'], help='加密或解密') parser.add_argument('mode', choices=['ecb', 'cbc'],",
"x, mode=ENCRYPT): \"\"\"加解密函数 Args: x (int): 需加解密的数据 mode (int, optional):",
"raise ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE)) return unhexlify('00') * (BLOCK_BYTE - len(key_iv)) + key_iv",
"\"\"\" return X[0] ^ self.T(X[1] ^ X[2] ^ X[3] ^",
"(B <<< 18) ^ (B <<< 24) Args: input (int):",
"from argparse import ArgumentParser, ArgumentError from binascii import hexlify, unhexlify",
"16) for j in range(0, 8, 2)] for i in",
"+ 3] ^ CK[i], self.L_prime)) self.rk = K[4:] def F(self,",
"img.shape size = img.size input = unhexlify(''.join([num2hex(i, width=2) for i",
"c.decrypt_ECB(input) if args.mode == 'ecb' else c.decrypt_CBC( input, args.iv) if",
"B ^ (B <<< 13) ^ (B <<< 23) Args:",
"args.source_type == 'input': input = args.source if input[:2].lower() == '0x':",
"BLOCK_HEX / 4) input = [int(i, 16) for i in",
"^ X[2] ^ X[3] ^ self.rk[i], self.L) def _crypt(self, x,",
"if __name__ == '__main__': parser = ArgumentParser(description=\"SM4加解密\") parser.add_argument('crypt', choices=['encrypt', 'decrypt'],",
"encrypt(self, x): \"\"\"加密函数 Args: x (int): 需加密的数据 Returns: int: 输出",
"encrypt_ECB(self, plain_text): \"\"\"ECB加密函数 Args: x (int): 需加密的数据 Returns: int: 输出",
"L(self, input): \"\"\"线性变换L,用于轮函数中 L(B) = B ^ (B <<< 2)",
"X_1, X_2, X_3),轮密钥为rk Args: X (list): 输入 i (int): 轮密钥的下标",
"args.source_type == 'bin_file': with open(args.source, 'rb') as f: input =",
"'encrypt': output = c.encrypt_ECB(input) if args.mode == 'ecb' else c.encrypt_CBC(",
"ENCRYPT) def decrypt_CBC(self, cipher_text, iv): \"\"\"CBC解密函数 Args: x (int): 需解密的数据",
"^ rotl(input, 23) def check_key_iv(self, key_iv): \"\"\"检验key或iv的合法性并转换成字节串 Args: key_iv (int,",
"key_iv (int, str or bytes): key或iv Raises: TypeError: 密钥或初始化向量类型错误 ValueError:",
"= bytes_to_list(hexlify(key), BLOCK_HEX / 4) input = [int(i, 16) for",
"^ rk) 其中输入为(X_0, X_1, X_2, X_3),轮密钥为rk Args: X (list): 输入",
"15:59:51 @Author : ZelKnow @Github : https://github.com/ZelKnow \"\"\" __author__ =",
"16) elif args.source_type == 'bin_file': with open(args.source, 'rb') as f:",
"[ unhexlify(num2hex(o, width=BLOCK_HEX)) for o in output_list ] # 转成字节流",
"try: cipher_text = unhexlify(cipher_text) except: pass return unpadding(self._crypt_CBC(cipher_text, iv, DECRYPT))",
"output = [[int(output[i + j:i + j + 2], 16)",
"return input ^ rotl(input, 13) ^ rotl(input, 23) def check_key_iv(self,",
"c.encrypt_ECB(input) if args.mode == 'ecb' else c.encrypt_CBC( input, args.iv) else:",
"加解密时使用的轮密钥顺序不同 for i in range(32) if mode == ENCRYPT else",
"^ K[i + 2] ^ K[i + 3] ^ CK[i],",
"range(4)] # 存储轮密钥 for i in range(32): # 密钥扩展算法 K.append(K[i]",
"width=2) for i in img.flatten()])) if args.crypt == 'encrypt': output",
"= [ unhexlify(num2hex(o, width=BLOCK_HEX)) for o in output_list ] #",
"input[:2].lower() == '0x': input = int(input[2:], 16) elif args.source_type ==",
"(int): 需加解密的数据 mode (int, optional): 加密或解密. Defaults to ENCRYPT. Returns:",
"'cbc' and args.iv is None: raise ArgumentError(\"请输入初始化向量的值\") if args.source_type ==",
"= int(input[2:], 16) elif args.source_type == 'bin_file': with open(args.source, 'rb')",
"\"\"\" input_list = bytes_to_list(input, BLOCK_BYTE) # 将输入拆分成block input_list = [int(hexlify(i),",
"i) & (0x000000ff)] for i in range(0, 32, 8)] B",
"K[4:] def F(self, X, i): \"\"\"轮函数F F = X_0 ^",
"in output_list ] return list_to_bytes(output_list) def encrypt_CBC(self, plain_text, iv): \"\"\"CBC加密函数",
"Defaults to ENCRYPT. Returns: int: 输出 \"\"\" input_list = bytes_to_list(input,",
"ArgumentParser(description=\"SM4加解密\") parser.add_argument('crypt', choices=['encrypt', 'decrypt'], help='加密或解密') parser.add_argument('mode', choices=['ecb', 'cbc'], help='加密模式') parser.add_argument('source',",
"bytes_to_list(input, BLOCK_BYTE) # 将输入拆分成block input_list = [int(hexlify(i), 16) for i",
"import hexlify, unhexlify from utils import S_BOX, BLOCK_BYTE, FK, CK,",
"unpadding(self._crypt_ECB(cipher_text, DECRYPT)) def _crypt_CBC(self, input, iv, mode=ENCRYPT): \"\"\"CBC加解密函数 Args: x",
"args.mode == 'ecb' else c.decrypt_CBC( input, args.iv) if args.source_type ==",
"\"\"\"ECB加密函数 Args: x (int): 需加密的数据 Returns: int: 输出 \"\"\" return",
"\"\"\" return self._crypt(x, DECRYPT) def _crypt_ECB(self, input, mode=ENCRYPT): \"\"\"ECB加解密函数 Args:",
"in range(0, 8, 2)] for i in range(0, len(output), 8)]",
"range(0, 8, 2)] for i in range(0, len(output), 8)] output",
"self.rk = [] def T(self, A, L_func): \"\"\"合成置换函数T T(.) =",
"def F(self, X, i): \"\"\"轮函数F F = X_0 ^ T(X_1",
"output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX)) for o in output_list ]",
"'cbc'], help='加密模式') parser.add_argument('source', help='加密/解密目标') parser.add_argument('key', help='密钥') parser.add_argument('--iv', help='初始化向量,cbc模式使用') parser.add_argument('--source_type', choices=['input',",
"isinstance(key_iv, bytes): raise TypeError(\"密钥或初始化向量类型错误\") if len(key_iv) > BLOCK_BYTE: raise ValueError('密钥或初始化向量长度不能大于{}'.format(BLOCK_BYTE))",
"# -*- encoding: utf-8 -*- \"\"\" @File : sm4.py @Description",
"ArgumentError from binascii import hexlify, unhexlify from utils import S_BOX,",
"2] output = [[int(output[i + j:i + j + 2],",
"= L(\\tau(.)) Args: A (int): 输入数据 L_func (function): 线性变换L Returns:",
"input_list] output_list = [self._crypt(x, mode) for x in input_list] #",
"@Date : 2021/10/28 15:59:51 @Author : ZelKnow @Github : https://github.com/ZelKnow",
"Args: x (int): 需加解密的数据 mode (int, optional): 加密或解密. Defaults to",
"width=BLOCK_HEX)) for o in output_list ] return list_to_bytes(output_list) def encrypt_CBC(self,",
"output_list = [self._crypt(x, mode) for x in input_list] # 分别加解密",
"BLOCK_BYTE) # 拆分成block input_list = [int(hexlify(i), 16) for i in",
"ArgumentError(\"请输入初始化向量的值\") if args.source_type == 'input': input = args.source if input[:2].lower()",
"_crypt(self, x, mode=ENCRYPT): \"\"\"加解密函数 Args: x (int): 需加解密的数据 mode (int,",
"iv = output_list[-1] else: output_list.append(self._crypt(x, mode) ^ iv) iv =",
"None: raise ArgumentError(\"请输入初始化向量的值\") if args.source_type == 'input': input = args.source",
"32))] # 加解密时使用的轮密钥顺序不同 for i in range(32) if mode ==",
"'__main__': parser = ArgumentParser(description=\"SM4加解密\") parser.add_argument('crypt', choices=['encrypt', 'decrypt'], help='加密或解密') parser.add_argument('mode', choices=['ecb',",
"= parser.parse_args() c = CryptSM4() c.set_key(args.key) if args.mode == 'cbc'",
"unhexlify(''.join([num2hex(i, width=2) for i in img.flatten()])) if args.crypt == 'encrypt':",
"需加密的数据 Returns: int: 输出 \"\"\" return self._crypt(x, ENCRYPT) def decrypt(self,",
"if mode == ENCRYPT else reversed(range(32)): input.append(self.F(input[-4:], i)) # 32次迭代运算",
"[B[i] << (i * 8) for i in range(4)] C",
"= [input[i] ^ FK[i] for i in range(4)] # 存储轮密钥",
"img.size input = unhexlify(''.join([num2hex(i, width=2) for i in img.flatten()])) if",
"i) & (0xffffffff) for i in reversed(range(0, 128, 32))] #",
"f.read() else: from PIL import Image import numpy as np",
"输入数据 L_func (function): 线性变换L Returns: int: 输出数据 \"\"\" B =",
"input, args.iv) else: output = c.decrypt_ECB(input) if args.mode == 'ecb'",
"= f.read() else: from PIL import Image import numpy as",
"input_list = bytes_to_list(input, BLOCK_BYTE) # 将输入拆分成block input_list = [int(hexlify(i), 16)",
"in range(0, 32, 8)] B = [B[i] << (i *",
"input.append(self.F(input[-4:], i)) # 32次迭代运算 output = input[-4:] output = [output[i]",
"hexlify, unhexlify from utils import S_BOX, BLOCK_BYTE, FK, CK, BLOCK_HEX",
"np.array(output) output = Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output) elif args.output: with open(args.output, \"wb\")",
"L_func (function): 线性变换L Returns: int: 输出数据 \"\"\" B = [S_BOX[(A",
"+ 2], 16) for j in range(0, 8, 2)] for",
"in input_list] output_list = [] for x in input_list: if",
"L(\\tau(.)) Args: A (int): 输入数据 L_func (function): 线性变换L Returns: int:",
"shape = img.shape size = img.size input = unhexlify(''.join([num2hex(i, width=2)",
"输出数据 \"\"\" return input ^ rotl(input, 13) ^ rotl(input, 23)",
"return unhexlify('00') * (BLOCK_BYTE - len(key_iv)) + key_iv def set_key(self,",
"ENCRYPT: output_list.append(self._crypt(x ^ iv, mode)) iv = output_list[-1] else: output_list.append(self._crypt(x,",
"list_to_bytes(output_list) # 合并 def encrypt_ECB(self, plain_text): \"\"\"ECB加密函数 Args: x (int):",
"int: 输出 \"\"\" return self._crypt_CBC(padding(plain_text), iv, ENCRYPT) def decrypt_CBC(self, cipher_text,",
"pass return unpadding(self._crypt_CBC(cipher_text, iv, DECRYPT)) if __name__ == '__main__': parser",
"^ FK[i] for i in range(4)] # 存储轮密钥 for i",
"存储轮密钥 for i in range(32): # 密钥扩展算法 K.append(K[i] ^ self.T(K[i",
"output[:size * 2] output = [[int(output[i + j:i + j",
"return input ^ rotl(input, 2) ^ rotl(input, 10) ^ rotl(",
"TypeError: 密钥或初始化向量类型错误 ValueError: 密钥或初始化向量长度过长 Returns: bytes: key或iv \"\"\" if isinstance(key_iv,",
"np source = Image.open(args.source) img = np.array(source.convert('RGBA')) shape = img.shape",
"(int): 输入数据 Returns: int: 输出数据 \"\"\" return input ^ rotl(input,",
"[[int(output[i + j:i + j + 2], 16) for j",
"需加解密的数据 mode (int, optional): 加密或解密. Defaults to ENCRYPT. Returns: int:",
"x (int): 需加密的数据 Returns: int: 输出 \"\"\" return self._crypt_CBC(padding(plain_text), iv,",
"CK, BLOCK_HEX from utils import rotl, num2hex, bytes_to_list, list_to_bytes, padding,",
"T(self, A, L_func): \"\"\"合成置换函数T T(.) = L(\\tau(.)) Args: A (int):",
"C = L_func(sum(B)) return C def L(self, input): \"\"\"线性变换L,用于轮函数中 L(B)",
"X_2 ^ X_3 ^ rk) 其中输入为(X_0, X_1, X_2, X_3),轮密钥为rk Args:",
"parser.add_argument('mode', choices=['ecb', 'cbc'], help='加密模式') parser.add_argument('source', help='加密/解密目标') parser.add_argument('key', help='密钥') parser.add_argument('--iv', help='初始化向量,cbc模式使用')",
"i): \"\"\"轮函数F F = X_0 ^ T(X_1 ^ X_2 ^",
"BLOCK_BYTE) # 将输入拆分成block input_list = [int(hexlify(i), 16) for i in",
"# 解密 class CryptSM4(object): def __init__(self): self.rk = [] def",
"if mode == ENCRYPT: output_list.append(self._crypt(x ^ iv, mode)) iv =",
"32, 8)] B = [B[i] << (i * 8) for",
"X[0] ^ self.T(X[1] ^ X[2] ^ X[3] ^ self.rk[i], self.L)",
"== 'encrypt': output = c.encrypt_ECB(input) if args.mode == 'ecb' else",
"x (int): 需加解密的数据 mode (int, optional): 加密或解密. Defaults to ENCRYPT.",
"ENCRYPT. Returns: int: 输出 \"\"\" input_list = bytes_to_list(input, BLOCK_BYTE) #",
"decrypt_CBC(self, cipher_text, iv): \"\"\"CBC解密函数 Args: x (int): 需解密的数据 Returns: int:",
"in reversed(range(0, 128, 32))] # 加解密时使用的轮密钥顺序不同 for i in range(32)",
"X_0 ^ T(X_1 ^ X_2 ^ X_3 ^ rk) 其中输入为(X_0,",
"i in range(4)] # 反序变换 return sum(output) def encrypt(self, x):",
"https://github.com/ZelKnow \"\"\" __author__ = \"ZelKnow\" from argparse import ArgumentParser, ArgumentError",
"初始化向量 input_list = bytes_to_list(input, BLOCK_BYTE) # 拆分成block input_list = [int(hexlify(i),",
"@Github : https://github.com/ZelKnow \"\"\" __author__ = \"ZelKnow\" from argparse import",
"(int): 轮密钥的下标 Returns: int: 输出 \"\"\" return X[0] ^ self.T(X[1]",
"if args.source_type == 'image': output = hexlify(output).decode() output = output[:size",
"Returns: int: 输出 \"\"\" return self._crypt(x, ENCRYPT) def decrypt(self, x):",
"^ self.T(K[i + 1] ^ K[i + 2] ^ K[i",
"mode=ENCRYPT): \"\"\"加解密函数 Args: x (int): 需加解密的数据 mode (int, optional): 加密或解密.",
"x output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX)) for o in output_list",
"^ iv, mode)) iv = output_list[-1] else: output_list.append(self._crypt(x, mode) ^",
"bytes): 密钥 \"\"\" key = self.check_key_iv(key) input = bytes_to_list(hexlify(key), BLOCK_HEX",
"^ self.rk[i], self.L) def _crypt(self, x, mode=ENCRYPT): \"\"\"加解密函数 Args: x",
"<<< 23) Args: input (int): 输入数据 Returns: int: 输出数据 \"\"\"",
"key_iv = unhexlify(num2hex(key_iv, width=32)) elif not isinstance(key_iv, bytes): raise TypeError(\"密钥或初始化向量类型错误\")",
"input ^ rotl(input, 2) ^ rotl(input, 10) ^ rotl( input,",
"拆分成block input_list = [int(hexlify(i), 16) for i in input_list] output_list",
"mode=ENCRYPT): \"\"\"CBC加解密函数 Args: x (int): 需加解密的数据 mode (int, optional): 加密或解密.",
"\"\"\" iv = int(hexlify(self.check_key_iv(iv)), 16) # 初始化向量 input_list = bytes_to_list(input,",
"'bin_file', 'image'], help='加密目标类型', default='input') parser.add_argument('--output', help='输出文件名,如不指定则输出至标准输出流') args = parser.parse_args() c",
"as f: input = f.read() else: from PIL import Image",
"2) ^ rotl(input, 10) ^ rotl( input, 18) ^ rotl(input,",
"iv = x output_list = [ unhexlify(num2hex(o, width=BLOCK_HEX)) for o",
"from binascii import hexlify, unhexlify from utils import S_BOX, BLOCK_BYTE,",
"(int, str or bytes): key或iv Raises: TypeError: 密钥或初始化向量类型错误 ValueError: 密钥或初始化向量长度过长",
"X_3 ^ rk) 其中输入为(X_0, X_1, X_2, X_3),轮密钥为rk Args: X (list):",
"FK, CK, BLOCK_HEX from utils import rotl, num2hex, bytes_to_list, list_to_bytes,",
"unhexlify from utils import S_BOX, BLOCK_BYTE, FK, CK, BLOCK_HEX from",
"range(4)] C = L_func(sum(B)) return C def L(self, input): \"\"\"线性变换L,用于轮函数中",
"for i in reversed(range(0, 128, 32))] # 加解密时使用的轮密钥顺序不同 for i",
"i in range(0, 32, 8)] B = [B[i] << (i",
"for i in range(4)] # 反序变换 return sum(output) def encrypt(self,",
"def decrypt(self, x): \"\"\"解密函数 Args: x (int): 需解密的数据 Returns: int:",
"(B <<< 23) Args: input (int): 输入数据 Returns: int: 输出数据",
"Args: x (int): 需解密的数据 Returns: int: 输出 \"\"\" try: cipher_text",
"in range(4)] # 存储轮密钥 for i in range(32): # 密钥扩展算法",
"输出数据 \"\"\" return input ^ rotl(input, 2) ^ rotl(input, 10)",
"self.L_prime)) self.rk = K[4:] def F(self, X, i): \"\"\"轮函数F F",
"将输入拆分成block input_list = [int(hexlify(i), 16) for i in input_list] output_list",
"iv = int(hexlify(self.check_key_iv(iv)), 16) # 初始化向量 input_list = bytes_to_list(input, BLOCK_BYTE)",
"args.source if input[:2].lower() == '0x': input = int(input[2:], 16) elif",
"def decrypt_ECB(self, cipher_text): \"\"\"ECB解密函数 Args: x (int): 需解密的数据 Returns: int:",
"args.mode == 'cbc' and args.iv is None: raise ArgumentError(\"请输入初始化向量的值\") if",
"Args: x (int): 需解密的数据 Returns: int: 输出 \"\"\" return self._crypt(x,",
"128, 32))] # 加解密时使用的轮密钥顺序不同 for i in range(32) if mode",
"def _crypt_ECB(self, input, mode=ENCRYPT): \"\"\"ECB加解密函数 Args: x (int): 需加解密的数据 mode",
"plain_text, iv): \"\"\"CBC加密函数 Args: x (int): 需加密的数据 Returns: int: 输出",
"img.flatten()])) if args.crypt == 'encrypt': output = c.encrypt_ECB(input) if args.mode",
"= [] for x in input_list: if mode == ENCRYPT:",
"32) for i in range(4)] # 反序变换 return sum(output) def",
"= np.array(output) output = Image.fromarray(output.reshape(shape).astype('uint8')) output.save(args.output) elif args.output: with open(args.output,",
"X, i): \"\"\"轮函数F F = X_0 ^ T(X_1 ^ X_2",
"= [self._crypt(x, mode) for x in input_list] # 分别加解密 output_list",
"and args.iv is None: raise ArgumentError(\"请输入初始化向量的值\") if args.source_type == 'input':",
"rotl(input, 2) ^ rotl(input, 10) ^ rotl( input, 18) ^",
"input = [int(i, 16) for i in input] K =",
"= bytes_to_list(input, BLOCK_BYTE) # 将输入拆分成block input_list = [int(hexlify(i), 16) for",
"iv): \"\"\"CBC解密函数 Args: x (int): 需解密的数据 Returns: int: 输出 \"\"\"",
"hexlify(output).decode() output = output[:size * 2] output = [[int(output[i +",
"return list_to_bytes(output_list) def encrypt_CBC(self, plain_text, iv): \"\"\"CBC加密函数 Args: x (int):",
"3] ^ CK[i], self.L_prime)) self.rk = K[4:] def F(self, X,",
"output = input[-4:] output = [output[i] << (i * 32)",
"需加密的数据 Returns: int: 输出 \"\"\" return self._crypt_CBC(padding(plain_text), iv, ENCRYPT) def",
"= CryptSM4() c.set_key(args.key) if args.mode == 'cbc' and args.iv is",
"output_list ] return list_to_bytes(output_list) def encrypt_CBC(self, plain_text, iv): \"\"\"CBC加密函数 Args:",
": ZelKnow @Github : https://github.com/ZelKnow \"\"\" __author__ = \"ZelKnow\" from",
"L'(B) = B ^ (B <<< 13) ^ (B <<<",
"ValueError: 密钥或初始化向量长度过长 Returns: bytes: key或iv \"\"\" if isinstance(key_iv, str): key_iv",
"其中输入为(X_0, X_1, X_2, X_3),轮密钥为rk Args: X (list): 输入 i (int):",
"list_to_bytes(output_list) def encrypt_CBC(self, plain_text, iv): \"\"\"CBC加密函数 Args: x (int): 需加密的数据",
"# 初始化向量 input_list = bytes_to_list(input, BLOCK_BYTE) # 拆分成block input_list =",
"c.set_key(args.key) if args.mode == 'cbc' and args.iv is None: raise",
"[int(hexlify(i), 16) for i in input_list] output_list = [self._crypt(x, mode)",
"输出 \"\"\" return X[0] ^ self.T(X[1] ^ X[2] ^ X[3]",
"\"\"\"ECB加解密函数 Args: x (int): 需加解密的数据 mode (int, optional): 加密或解密. Defaults",
"key_iv def set_key(self, key): \"\"\"设置key Args: key (int, str or",
"= B ^ (B <<< 2) ^ (B <<< 10)",
"help='加密或解密') parser.add_argument('mode', choices=['ecb', 'cbc'], help='加密模式') parser.add_argument('source', help='加密/解密目标') parser.add_argument('key', help='密钥') parser.add_argument('--iv',",
"import S_BOX, BLOCK_BYTE, FK, CK, BLOCK_HEX from utils import rotl,",
"\"\"\"加解密函数 Args: x (int): 需加解密的数据 mode (int, optional): 加密或解密. Defaults",
"range(32): # 密钥扩展算法 K.append(K[i] ^ self.T(K[i + 1] ^ K[i",
"2021/10/28 15:59:51 @Author : ZelKnow @Github : https://github.com/ZelKnow \"\"\" __author__",
"int: 输出 \"\"\" iv = int(hexlify(self.check_key_iv(iv)), 16) # 初始化向量 input_list",
"width=32)) elif not isinstance(key_iv, bytes): raise TypeError(\"密钥或初始化向量类型错误\") if len(key_iv) >",
"c = CryptSM4() c.set_key(args.key) if args.mode == 'cbc' and args.iv",
"+ key_iv def set_key(self, key): \"\"\"设置key Args: key (int, str",
"cipher_text = unhexlify(cipher_text) except: pass return unpadding(self._crypt_CBC(cipher_text, iv, DECRYPT)) if"
] |
[
"random import randint class sendotp: def __init__(self, key, msg): self.baseUrl",
"key try: msg except NameError: self.msg = \"Your otp is",
"self.authkey, 'mobile': contactNumber, 'retrytype': retrytype } print (values) response =",
"contactNumber, 'otp': otp } response = self.call('verifyRequestOTP.php', values) return response;",
"sendotp: def __init__(self, key, msg): self.baseUrl = \"http://control.msg91.com\" self.authkey =",
"'authkey': self.authkey, 'mobile': contactNumber, 'retrytype': retrytype } print (values) response",
"self.msg = \"Your otp is {{otp}}. Please do not share",
"= \"Your otp is {{otp}}. Please do not share it",
"'mobile': contactNumber, 'message': self.msg.replace(\"{{otp}}\", str(otp)), 'sender': senderId, 'otp': otp }",
"contactNumber, senderId, otp): values = { 'authkey': self.authkey, 'mobile': contactNumber,",
"'otp': otp } response = self.call('verifyRequestOTP.php', values) return response; def",
"values = { 'authkey': self.authkey, 'mobile': contactNumber, 'otp': otp }",
"randint(1000, 9999) def send(self, contactNumber, senderId, otp): values = {",
"(actionurl) return self.baseUrl + '/api/' + str(actionurl) def generateOtp(self): return",
"try: msg except NameError: self.msg = \"Your otp is {{otp}}.",
"randint class sendotp: def __init__(self, key, msg): self.baseUrl = \"http://control.msg91.com\"",
"def actionURLBuilder(self, actionurl): # print self.baseUrl + '/api/' +str(actionurl) print",
"print (actionurl) return self.baseUrl + '/api/' + str(actionurl) def generateOtp(self):",
"send(self, contactNumber, senderId, otp): values = { 'authkey': self.authkey, 'mobile':",
"senderId, 'otp': otp } print (self.call('sendotp.php', values)) return otp def",
"self.actionURLBuilder(actionurl) print (url) payload = (args) response = requests.post(url, data=payload,",
"self.call('retryotp.php', values) return; def verify(self, contactNumber, otp): values = {",
"share it with anybody\" else: self.msg = msg def actionURLBuilder(self,",
"def __init__(self, key, msg): self.baseUrl = \"http://control.msg91.com\" self.authkey = key",
"self.authkey, 'mobile': contactNumber, 'otp': otp } response = self.call('verifyRequestOTP.php', values)",
"self.baseUrl + '/api/' + str(actionurl) def generateOtp(self): return randint(1000, 9999)",
"'authkey': self.authkey, 'mobile': contactNumber, 'message': self.msg.replace(\"{{otp}}\", str(otp)), 'sender': senderId, 'otp':",
"values) return; def verify(self, contactNumber, otp): values = { 'authkey':",
"actionurl): # print self.baseUrl + '/api/' +str(actionurl) print (actionurl) return",
"'mobile': contactNumber, 'retrytype': retrytype } print (values) response = self.call('retryotp.php',",
"from random import randint class sendotp: def __init__(self, key, msg):",
"return response; def call(self, actionurl, args): url = self.actionURLBuilder(actionurl) print",
"} print (self.call('sendotp.php', values)) return otp def retry(self, contactNumber, retrytype='voice'):",
"{ 'authkey': self.authkey, 'mobile': contactNumber, 'retrytype': retrytype } print (values)",
"retrytype='voice'): values = { 'authkey': self.authkey, 'mobile': contactNumber, 'retrytype': retrytype",
"not share it with anybody\" else: self.msg = msg def",
"print self.baseUrl + '/api/' +str(actionurl) print (actionurl) return self.baseUrl +",
"{{otp}}. Please do not share it with anybody\" else: self.msg",
"return; def verify(self, contactNumber, otp): values = { 'authkey': self.authkey,",
"actionURLBuilder(self, actionurl): # print self.baseUrl + '/api/' +str(actionurl) print (actionurl)",
"import requests from random import randint class sendotp: def __init__(self,",
"<reponame>saadmk11/sendotp-python<filename>sendotp/sendotp.py import json import requests from random import randint class",
"except NameError: self.msg = \"Your otp is {{otp}}. Please do",
"contactNumber, otp): values = { 'authkey': self.authkey, 'mobile': contactNumber, 'otp':",
"= { 'authkey': self.authkey, 'mobile': contactNumber, 'message': self.msg.replace(\"{{otp}}\", str(otp)), 'sender':",
"def generateOtp(self): return randint(1000, 9999) def send(self, contactNumber, senderId, otp):",
"(url) payload = (args) response = requests.post(url, data=payload, verify=False) print",
"} response = self.call('verifyRequestOTP.php', values) return response; def call(self, actionurl,",
"= (args) response = requests.post(url, data=payload, verify=False) print (response.text) return",
"= msg def actionURLBuilder(self, actionurl): # print self.baseUrl + '/api/'",
"otp): values = { 'authkey': self.authkey, 'mobile': contactNumber, 'otp': otp",
"(args) response = requests.post(url, data=payload, verify=False) print (response.text) return response.status_code",
"msg): self.baseUrl = \"http://control.msg91.com\" self.authkey = key try: msg except",
"} print (values) response = self.call('retryotp.php', values) return; def verify(self,",
"key, msg): self.baseUrl = \"http://control.msg91.com\" self.authkey = key try: msg",
"(values) response = self.call('retryotp.php', values) return; def verify(self, contactNumber, otp):",
"str(otp)), 'sender': senderId, 'otp': otp } print (self.call('sendotp.php', values)) return",
"payload = (args) response = requests.post(url, data=payload, verify=False) print (response.text)",
"__init__(self, key, msg): self.baseUrl = \"http://control.msg91.com\" self.authkey = key try:",
"anybody\" else: self.msg = msg def actionURLBuilder(self, actionurl): # print",
"{ 'authkey': self.authkey, 'mobile': contactNumber, 'otp': otp } response =",
"generateOtp(self): return randint(1000, 9999) def send(self, contactNumber, senderId, otp): values",
"it with anybody\" else: self.msg = msg def actionURLBuilder(self, actionurl):",
"'sender': senderId, 'otp': otp } print (self.call('sendotp.php', values)) return otp",
"contactNumber, 'retrytype': retrytype } print (values) response = self.call('retryotp.php', values)",
"def call(self, actionurl, args): url = self.actionURLBuilder(actionurl) print (url) payload",
"= self.actionURLBuilder(actionurl) print (url) payload = (args) response = requests.post(url,",
"otp } print (self.call('sendotp.php', values)) return otp def retry(self, contactNumber,",
"actionurl, args): url = self.actionURLBuilder(actionurl) print (url) payload = (args)",
"call(self, actionurl, args): url = self.actionURLBuilder(actionurl) print (url) payload =",
"senderId, otp): values = { 'authkey': self.authkey, 'mobile': contactNumber, 'message':",
"self.authkey = key try: msg except NameError: self.msg = \"Your",
"values = { 'authkey': self.authkey, 'mobile': contactNumber, 'retrytype': retrytype }",
"response; def call(self, actionurl, args): url = self.actionURLBuilder(actionurl) print (url)",
"retry(self, contactNumber, retrytype='voice'): values = { 'authkey': self.authkey, 'mobile': contactNumber,",
"return self.baseUrl + '/api/' + str(actionurl) def generateOtp(self): return randint(1000,",
"'/api/' + str(actionurl) def generateOtp(self): return randint(1000, 9999) def send(self,",
"self.msg.replace(\"{{otp}}\", str(otp)), 'sender': senderId, 'otp': otp } print (self.call('sendotp.php', values))",
"= \"http://control.msg91.com\" self.authkey = key try: msg except NameError: self.msg",
"otp def retry(self, contactNumber, retrytype='voice'): values = { 'authkey': self.authkey,",
"url = self.actionURLBuilder(actionurl) print (url) payload = (args) response =",
"otp): values = { 'authkey': self.authkey, 'mobile': contactNumber, 'message': self.msg.replace(\"{{otp}}\",",
"import randint class sendotp: def __init__(self, key, msg): self.baseUrl =",
"Please do not share it with anybody\" else: self.msg =",
"+ str(actionurl) def generateOtp(self): return randint(1000, 9999) def send(self, contactNumber,",
"self.authkey, 'mobile': contactNumber, 'message': self.msg.replace(\"{{otp}}\", str(otp)), 'sender': senderId, 'otp': otp",
"contactNumber, retrytype='voice'): values = { 'authkey': self.authkey, 'mobile': contactNumber, 'retrytype':",
"def verify(self, contactNumber, otp): values = { 'authkey': self.authkey, 'mobile':",
"requests from random import randint class sendotp: def __init__(self, key,",
"'retrytype': retrytype } print (values) response = self.call('retryotp.php', values) return;",
"+str(actionurl) print (actionurl) return self.baseUrl + '/api/' + str(actionurl) def",
"str(actionurl) def generateOtp(self): return randint(1000, 9999) def send(self, contactNumber, senderId,",
"return randint(1000, 9999) def send(self, contactNumber, senderId, otp): values =",
"9999) def send(self, contactNumber, senderId, otp): values = { 'authkey':",
"= { 'authkey': self.authkey, 'mobile': contactNumber, 'retrytype': retrytype } print",
"(self.call('sendotp.php', values)) return otp def retry(self, contactNumber, retrytype='voice'): values =",
"retrytype } print (values) response = self.call('retryotp.php', values) return; def",
"import json import requests from random import randint class sendotp:",
"class sendotp: def __init__(self, key, msg): self.baseUrl = \"http://control.msg91.com\" self.authkey",
"# print self.baseUrl + '/api/' +str(actionurl) print (actionurl) return self.baseUrl",
"self.baseUrl + '/api/' +str(actionurl) print (actionurl) return self.baseUrl + '/api/'",
"= key try: msg except NameError: self.msg = \"Your otp",
"'message': self.msg.replace(\"{{otp}}\", str(otp)), 'sender': senderId, 'otp': otp } print (self.call('sendotp.php',",
"print (self.call('sendotp.php', values)) return otp def retry(self, contactNumber, retrytype='voice'): values",
"'mobile': contactNumber, 'otp': otp } response = self.call('verifyRequestOTP.php', values) return",
"values) return response; def call(self, actionurl, args): url = self.actionURLBuilder(actionurl)",
"json import requests from random import randint class sendotp: def",
"contactNumber, 'message': self.msg.replace(\"{{otp}}\", str(otp)), 'sender': senderId, 'otp': otp } print",
"print (url) payload = (args) response = requests.post(url, data=payload, verify=False)",
"'/api/' +str(actionurl) print (actionurl) return self.baseUrl + '/api/' + str(actionurl)",
"+ '/api/' +str(actionurl) print (actionurl) return self.baseUrl + '/api/' +",
"print (values) response = self.call('retryotp.php', values) return; def verify(self, contactNumber,",
"+ '/api/' + str(actionurl) def generateOtp(self): return randint(1000, 9999) def",
"with anybody\" else: self.msg = msg def actionURLBuilder(self, actionurl): #",
"NameError: self.msg = \"Your otp is {{otp}}. Please do not",
"else: self.msg = msg def actionURLBuilder(self, actionurl): # print self.baseUrl",
"\"Your otp is {{otp}}. Please do not share it with",
"'authkey': self.authkey, 'mobile': contactNumber, 'otp': otp } response = self.call('verifyRequestOTP.php',",
"def retry(self, contactNumber, retrytype='voice'): values = { 'authkey': self.authkey, 'mobile':",
"args): url = self.actionURLBuilder(actionurl) print (url) payload = (args) response",
"values)) return otp def retry(self, contactNumber, retrytype='voice'): values = {",
"is {{otp}}. Please do not share it with anybody\" else:",
"= { 'authkey': self.authkey, 'mobile': contactNumber, 'otp': otp } response",
"msg def actionURLBuilder(self, actionurl): # print self.baseUrl + '/api/' +str(actionurl)",
"self.baseUrl = \"http://control.msg91.com\" self.authkey = key try: msg except NameError:",
"self.call('verifyRequestOTP.php', values) return response; def call(self, actionurl, args): url =",
"otp is {{otp}}. Please do not share it with anybody\"",
"'otp': otp } print (self.call('sendotp.php', values)) return otp def retry(self,",
"{ 'authkey': self.authkey, 'mobile': contactNumber, 'message': self.msg.replace(\"{{otp}}\", str(otp)), 'sender': senderId,",
"do not share it with anybody\" else: self.msg = msg",
"response = self.call('retryotp.php', values) return; def verify(self, contactNumber, otp): values",
"verify(self, contactNumber, otp): values = { 'authkey': self.authkey, 'mobile': contactNumber,",
"return otp def retry(self, contactNumber, retrytype='voice'): values = { 'authkey':",
"def send(self, contactNumber, senderId, otp): values = { 'authkey': self.authkey,",
"msg except NameError: self.msg = \"Your otp is {{otp}}. Please",
"otp } response = self.call('verifyRequestOTP.php', values) return response; def call(self,",
"response = self.call('verifyRequestOTP.php', values) return response; def call(self, actionurl, args):",
"values = { 'authkey': self.authkey, 'mobile': contactNumber, 'message': self.msg.replace(\"{{otp}}\", str(otp)),",
"= self.call('retryotp.php', values) return; def verify(self, contactNumber, otp): values =",
"self.msg = msg def actionURLBuilder(self, actionurl): # print self.baseUrl +",
"= self.call('verifyRequestOTP.php', values) return response; def call(self, actionurl, args): url",
"\"http://control.msg91.com\" self.authkey = key try: msg except NameError: self.msg ="
] |
[
"s = '(()())(())(()(()))' s = '()()' ret = Solution().removeOuterParentheses(s) print(ret)",
"# s = '(()())(())' # s = '(()())(())(()(()))' s =",
"s: str) -> str: ans = [] ct = 0",
"if ct != 0: ans.append(ch) return ''.join(ans) if __name__ ==",
"[] ct = 0 for ch in s: if ch",
"class Solution: def removeOuterParentheses(self, s: str) -> str: ans =",
"ct != 1: ans.append(ch) else: ct -= 1 if ct",
"if ch == '(': ct += 1 if ct !=",
"+= 1 if ct != 1: ans.append(ch) else: ct -=",
"s = '(()())(())' # s = '(()())(())(()(()))' s = '()()'",
"ct = 0 for ch in s: if ch ==",
"!= 0: ans.append(ch) return ''.join(ans) if __name__ == '__main__': #",
"== '(': ct += 1 if ct != 1: ans.append(ch)",
"s: if ch == '(': ct += 1 if ct",
"'(()())(())' # s = '(()())(())(()(()))' s = '()()' ret =",
"__name__ == '__main__': # s = '(()())(())' # s =",
"in s: if ch == '(': ct += 1 if",
"-> str: ans = [] ct = 0 for ch",
"= '(()())(())' # s = '(()())(())(()(()))' s = '()()' ret",
"ch in s: if ch == '(': ct += 1",
"1 if ct != 1: ans.append(ch) else: ct -= 1",
"= [] ct = 0 for ch in s: if",
"ct != 0: ans.append(ch) return ''.join(ans) if __name__ == '__main__':",
"ans.append(ch) else: ct -= 1 if ct != 0: ans.append(ch)",
"'(': ct += 1 if ct != 1: ans.append(ch) else:",
"str: ans = [] ct = 0 for ch in",
"removeOuterParentheses(self, s: str) -> str: ans = [] ct =",
"-= 1 if ct != 0: ans.append(ch) return ''.join(ans) if",
"if ct != 1: ans.append(ch) else: ct -= 1 if",
"= 0 for ch in s: if ch == '(':",
"0: ans.append(ch) return ''.join(ans) if __name__ == '__main__': # s",
"Solution: def removeOuterParentheses(self, s: str) -> str: ans = []",
"ans = [] ct = 0 for ch in s:",
"def removeOuterParentheses(self, s: str) -> str: ans = [] ct",
"str) -> str: ans = [] ct = 0 for",
"ch == '(': ct += 1 if ct != 1:",
"return ''.join(ans) if __name__ == '__main__': # s = '(()())(())'",
"0 for ch in s: if ch == '(': ct",
"1: ans.append(ch) else: ct -= 1 if ct != 0:",
"if __name__ == '__main__': # s = '(()())(())' # s",
"!= 1: ans.append(ch) else: ct -= 1 if ct !=",
"== '__main__': # s = '(()())(())' # s = '(()())(())(()(()))'",
"ans.append(ch) return ''.join(ans) if __name__ == '__main__': # s =",
"for ch in s: if ch == '(': ct +=",
"'__main__': # s = '(()())(())' # s = '(()())(())(()(()))' s",
"''.join(ans) if __name__ == '__main__': # s = '(()())(())' #",
"ct += 1 if ct != 1: ans.append(ch) else: ct",
"else: ct -= 1 if ct != 0: ans.append(ch) return",
"1 if ct != 0: ans.append(ch) return ''.join(ans) if __name__",
"# s = '(()())(())(()(()))' s = '()()' ret = Solution().removeOuterParentheses(s)",
"ct -= 1 if ct != 0: ans.append(ch) return ''.join(ans)"
] |
[
"tabuada: ')) for c in range(0, 11): print(f'{n} * {c}",
"para ver sua tabuada: ')) for c in range(0, 11):",
"in range(0, 11): print(f'{n} * {c} = {n * c}')",
"n = int(input('Digite um número para ver sua tabuada: '))",
"um número para ver sua tabuada: ')) for c in",
"')) for c in range(0, 11): print(f'{n} * {c} =",
"for c in range(0, 11): print(f'{n} * {c} = {n",
"ver sua tabuada: ')) for c in range(0, 11): print(f'{n}",
"sua tabuada: ')) for c in range(0, 11): print(f'{n} *",
"número para ver sua tabuada: ')) for c in range(0,",
"c in range(0, 11): print(f'{n} * {c} = {n *",
"int(input('Digite um número para ver sua tabuada: ')) for c",
"= int(input('Digite um número para ver sua tabuada: ')) for"
] |
[
"os.remove(filename) try: os.remove(filename + 'c') except: pass def eval_debug(self, expression):",
"the converted js is cached for re-use. That means next",
"Number, String, Boolean and other base types returns appropriate python",
"javascript console with console method!\"\"\" def __init__(self, context={}, enable_require=False): self.__dict__['_context']",
"run interactive javascript console with console method!\"\"\" def __init__(self, context={},",
"either a dict or have __dict__ attr') for k, v",
"compared to actually running the generated python code. Note that",
"[ 'EvalJs', 'translate_js', 'import_js', 'eval_js', 'translate_file', 'eval_js6', 'translate_js6', 'run_file', 'disable_pyimport',",
">>> example.a(30) 30 ''' js = get_file_contents(input_path) py_code = translate_js(js)",
"\"r\", \"utf-8\") as f: js = f.read() e = EvalJs()",
"we have a file 'example.js' with: var a = function(x)",
"That means next time you run the same javascript snippet",
"process is typically expensive compared to actually running the generated",
"example.py can be easily importend and used: >>> from example",
"relative to cwd return os.path.join(os.getcwd(), path) def import_js(path, lib_name, globals):",
"should be available to JavaScript For example: >>> ctx =",
"for example: >>> ctx = EvalJs(enable_require=True) >>> ctx.execute(\"var esprima =",
"or have __dict__ attr') for k, v in six.iteritems(context): setattr(self._var,",
"= context.__dict__ except: raise TypeError( 'context has to be either",
"use_compilation_plan=use_compilation_plan) compiled = cache[hashkey] = compile(code, '<EvalJS snippet>', 'exec') exec",
"[python code] } NOTE: For Js Number, String, Boolean and",
"= EvalJs() return e.eval(js) def eval_js6(js): \"\"\"Just like eval_js but",
"self.__dict__['_context'] = {} exec (DEFAULT_HEADER, self._context) self.__dict__['_var'] = self._context['var'].to_python() if",
"context = EvalJs() if not isinstance(context, EvalJs): raise TypeError('context must",
"3 6 >>> add('1', 2, 3) u'12' >>> add.constructor function",
"translate_js(js6_to_js5(js)) class EvalJs(object): \"\"\"This class supports continuous execution of javascript",
"You can enable JS require function via enable_require. With this",
"actually running the generated python code. Note that the cache",
"generated python code. Note that the cache is just a",
"code gets translated from es6 to es5 before being executed.\"\"\"",
"be the instance of EvalJs') eval_value = context.eval(get_file_contents(path_or_file)) return eval_value,",
"eval_js but with experimental support for js6 via babel.\"\"\" return",
"given path as a JS program. Returns (eval_value, context). '''",
"dict you can use to_dict method. \"\"\" e = EvalJs()",
"= js2py.eval_js('function add(a, b) {return a + b}') >>> add(1,",
"es5_expression = js6_to_js5(expression) return self.eval(es5_expression, use_compilation_plan) def execute_debug(self, js): \"\"\"executes",
"a temp folder: filename = 'temp' + os.sep + '_'",
"return setattr(self._var, var, val) def console(self): \"\"\"starts to interact (starts",
"import time import json import six import os import hashlib",
"to python, executes and returns python object. js is javascript",
"require('esprima');\") >>> ctx.execute(\"esprima.parse('var a = 1')\") You can run interactive",
"During initial execute() the converted js is cached for re-use.",
"- basically behaves like normal python object. If you really",
"= EvalJs() e.execute(js) var = e.context['var'] globals[lib_name] = var.to_python() def",
"import js2py >>> add = js2py.eval_js('function add(a, b) {return a",
"method, you can use your regular debugger to set breakpoints",
"{return x} translate_file('example.js', 'example.py') Now example.py can be easily importend",
"TypeError('context must be the instance of EvalJs') eval_value = context.eval(get_file_contents(path_or_file))",
"compile(code, '<EvalJS snippet>', 'exec') exec (compiled, self._context) def eval(self, expression,",
"js in current context During initial execute() the converted js",
"with console method!\"\"\" def __init__(self, context={}, enable_require=False): self.__dict__['_context'] = {}",
"that the cache is just a dict, it has no",
"getattr(self._var, var) def __setattr__(self, var, val): return setattr(self._var, var, val)",
"opposed to the (faster) self.execute method, you can use your",
"head = '__all__ = [%s]\\n\\n# Don\\'t look below, you will",
"debugger to set breakpoints and inspect the generated python code",
"= cache[hashkey] except KeyError: code = translate_js( js, '', use_compilation_plan=use_compilation_plan)",
"= self.__dict__['cache'] = {} hashkey = hashlib.md5(js.encode('utf-8')).digest() try: compiled =",
"if DEBUG: sys.stderr.write(traceback.format_exc()) else: sys.stderr.write('EXCEPTION: ' + str(e) + '\\n')",
"below, you will not understand this Python code :) I",
"a = 1')\") You can run interactive javascript console with",
"as eval, except that the JS code gets translated from",
"'translate_js', 'import_js', 'eval_js', 'translate_file', 'eval_js6', 'translate_js6', 'run_file', 'disable_pyimport', 'get_file_contents', 'write_file_contents'",
"has to be either a dict or have __dict__ attr')",
"os.path.basename(output_path).split('.')[0] head = '__all__ = [%s]\\n\\n# Don\\'t look below, you",
"being executed.\"\"\" es5_expression = js6_to_js5(expression) return self.eval(es5_expression, use_compilation_plan) def execute_debug(self,",
"must be the instance of EvalJs') eval_value = context.eval(get_file_contents(path_or_file)) return",
"+ os.sep + '_' + hashlib.md5( code.encode(\"utf-8\")).hexdigest() + '.py' try:",
"self.execute_debug(code) return self['PyJsEvalResult'] @property def context(self): return self._context def __getattr__(self,",
"Returns (eval_value, context). ''' if context is None: context =",
"python object. js is javascript source code EXAMPLE: >>> import",
"context During initial execute() the converted js is cached for",
"= 'temp' + os.sep + '_' + hashlib.md5( code.encode(\"utf-8\")).hexdigest() +",
"__setitem__(self, var, val): return setattr(self._var, var, val) def console(self): \"\"\"starts",
"is just a dict, it has no expiration or cleanup",
"val): return setattr(self._var, var, val) def console(self): \"\"\"starts to interact",
"open('C:\\Users\\Piotrek\\Desktop\\esprima.js', 'rb') as f: # x = f.read() e =",
"f.write(contents) def translate_file(input_path, output_path): ''' Translates input JS file to",
"= f.read() return js def write_file_contents(path_or_file, contents): if hasattr(path_or_file, 'write'):",
"code :) I don\\'t.\\n\\n' % repr( lib_name) tail = '\\n\\n#",
"that contains python variables that should be available to JavaScript",
"don\\'t.\\n\\n' % repr( lib_name) tail = '\\n\\n# Add lib to",
"importend and used: >>> from example import example >>> example.a(30)",
"% lib_name out = head + py_code + tail write_file_contents(output_path,",
"\"\"\"starts to interact (starts interactive console) Something like code.InteractiveConsole\"\"\" while",
"If you really want to convert object to python dict",
"you run the same javascript snippet you save many instructions",
"supports continuous execution of javascript under same context. >>> ctx",
"_js_require_impl) if not isinstance(context, dict): try: context = context.__dict__ except:",
"that it is easy to import JS objects. For example",
"eval(%s)' % json.dumps(expression) self.execute_debug(code) return self['PyJsEvalResult'] @property def context(self): return",
"like normal python object. If you really want to convert",
"#print x if __name__ == '__main__': #with open('C:\\Users\\Piotrek\\Desktop\\esprima.js', 'rb') as",
"returns appropriate python BUILTIN type. For Js functions and objects,",
">>> add(1, 2) + 3 6 >>> add('1', 2, 3)",
"BUILTIN type. For Js functions and objects, returns Python wrapper",
"generated python code \"\"\" code = translate_js(js, '') # make",
">>> ctx.a 10 context is a python dict or object",
"feature enabled you can use js modules from npm, for",
"python object. If you really want to convert object to",
"None: context = EvalJs() if not isinstance(context, EvalJs): raise TypeError('context",
"the module scope\\n%s = var.to_python()' % lib_name out = head",
"your globals()\"\"\" with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f: js =",
"f(x) {return x*x};') >>> ctx.f(9) 81 >>> ctx.a 10 context",
"be either a dict or have __dict__ attr') for k,",
"under same context. >>> ctx = EvalJs() >>> ctx.execute('var a",
"convert the js code to python code. This cache causes",
"+ tail write_file_contents(output_path, out) def run_file(path_or_file, context=None): ''' Context must",
"= EvalJs(enable_require=True) >>> ctx.execute(\"var esprima = require('esprima');\") >>> ctx.execute(\"esprima.parse('var a",
"gets translated from es6 to es5 before being executed.\"\"\" es5_expression",
"a dict, it has no expiration or cleanup so when",
"self._context) self.__dict__['_var'] = self._context['var'].to_python() if enable_require: def _js_require_impl(npm_module_name): from .node_import",
"the generated python code. Note that the cache is just",
"# relative to cwd return os.path.join(os.getcwd(), path) def import_js(path, lib_name,",
"interactive console) Something like code.InteractiveConsole\"\"\" while True: if six.PY2: code",
"Translates input JS file to python and saves the it",
"f.read() return js def write_file_contents(path_or_file, contents): if hasattr(path_or_file, 'write'): path_or_file.write(contents)",
"this Python code :) I don\\'t.\\n\\n' % repr( lib_name) tail",
"current context and returns its value as opposed to the",
"EvalJs(enable_require=True) >>> ctx.execute(\"var esprima = require('esprima');\") >>> ctx.execute(\"esprima.parse('var a =",
"instructions needed to parse and convert the js code to",
"(eval_value, context). ''' if context is None: context = EvalJs()",
"execute_debug(self, js): \"\"\"executes javascript js in current context as opposed",
"+ 'c') except: pass def eval_debug(self, expression): \"\"\"evaluates expression in",
"JS objects. For example we have a file 'example.js' with:",
"= [%s]\\n\\n# Don\\'t look below, you will not understand this",
"Js Number, String, Boolean and other base types returns appropriate",
"same context. >>> ctx = EvalJs() >>> ctx.execute('var a =",
"running this in automated situations with vast amounts of snippets",
"1')\") You can run interactive javascript console with console method!\"\"\"",
"try: with open(filename, mode='w') as f: f.write(code) with open(filename, \"r\")",
"be available to JavaScript For example: >>> ctx = EvalJs({'a':",
"function Function() { [python code] } NOTE: For Js Number,",
"eval. Translates javascript to python, executes and returns python object.",
"False def disable_pyimport(): import pyjsparser.parser pyjsparser.parser.ENABLE_PYIMPORT = False def path_as_local(path):",
"example: >>> ctx = EvalJs(enable_require=True) >>> ctx.execute(\"var esprima = require('esprima');\")",
"context def eval_js(js): \"\"\"Just like javascript eval. Translates javascript to",
"six import os import hashlib import codecs __all__ = [",
"except Exception as err: raise err finally: os.remove(filename) try: os.remove(filename",
"'c') except: pass def eval_debug(self, expression): \"\"\"evaluates expression in current",
"DEBUG = False def disable_pyimport(): import pyjsparser.parser pyjsparser.parser.ENABLE_PYIMPORT = False",
"class EvalJs(object): \"\"\"This class supports continuous execution of javascript under",
"def translate_file(input_path, output_path): ''' Translates input JS file to python",
"method. \"\"\" e = EvalJs() return e.eval(js) def eval_js6(js): \"\"\"Just",
"With this feature enabled you can use js modules from",
"self.__dict__['_var'] = self._context['var'].to_python() if enable_require: def _js_require_impl(npm_module_name): from .node_import import",
"is cached for re-use. That means next time you run",
"= 'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute_debug(code) return self['PyJsEvalResult'] @property",
"if not isinstance(context, dict): try: context = context.__dict__ except: raise",
"vast amounts of snippets it might increase memory usage. \"\"\"",
"def __init__(self, context={}, enable_require=False): self.__dict__['_context'] = {} exec (DEFAULT_HEADER, self._context)",
"It appends some convenience code at the end so that",
"eval_js(js): \"\"\"Just like javascript eval. Translates javascript to python, executes",
"self.__dict__['cache'] = {} hashkey = hashlib.md5(js.encode('utf-8')).digest() try: compiled = cache[hashkey]",
"can enable JS require function via enable_require. With this feature",
"you really want to convert object to python dict you",
"code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute(code, use_compilation_plan=use_compilation_plan) return",
"as opposed to the (faster) self.execute method, you can use",
"use js modules from npm, for example: >>> ctx =",
"input JS file to python and saves the it to",
"executed.\"\"\" es5_expression = js6_to_js5(expression) return self.eval(es5_expression, use_compilation_plan) def execute_debug(self, js):",
"execution of javascript under same context. >>> ctx = EvalJs()",
"def write_file_contents(path_or_file, contents): if hasattr(path_or_file, 'write'): path_or_file.write(contents) else: with open(path_as_local(path_or_file),",
"from javascript source file. globals is your globals()\"\"\" with codecs.open(path_as_local(path),",
"js): \"\"\"executes javascript js in current context as opposed to",
"while True: if six.PY2: code = raw_input('>>> ') else: code",
"this feature enabled you can use js modules from npm,",
"setattr(self._var, 'require', _js_require_impl) if not isinstance(context, dict): try: context =",
"val) def __setitem__(self, var, val): return setattr(self._var, var, val) def",
">>> ctx.x 30 You can enable JS require function via",
"DEBUG: sys.stderr.write(traceback.format_exc()) else: sys.stderr.write('EXCEPTION: ' + str(e) + '\\n') time.sleep(0.01)",
">>> add = js2py.eval_js('function add(a, b) {return a + b}')",
"'context has to be either a dict or have __dict__",
"'__all__ = [%s]\\n\\n# Don\\'t look below, you will not understand",
"\"utf-8\") as f: js = f.read() return js def write_file_contents(path_or_file,",
"def context(self): return self._context def __getattr__(self, var): return getattr(self._var, var)",
"input('>>>') try: print(self.eval(code)) except KeyboardInterrupt: break except Exception as e:",
"import hashlib import codecs __all__ = [ 'EvalJs', 'translate_js', 'import_js',",
"conversion process is typically expensive compared to actually running the",
"v in six.iteritems(context): setattr(self._var, k, v) def execute(self, js=None, use_compilation_plan=False):",
"For example we have a file 'example.js' with: var a",
"with vast amounts of snippets it might increase memory usage.",
"NOTE: For Js Number, String, Boolean and other base types",
"python code. Note that the cache is just a dict,",
"6 >>> add('1', 2, 3) u'12' >>> add.constructor function Function()",
"a python dict or object that contains python variables that",
"'write'): path_or_file.write(contents) else: with open(path_as_local(path_or_file), 'w') as f: f.write(contents) def",
"if not isinstance(context, EvalJs): raise TypeError('context must be the instance",
"= cache[hashkey] = compile(code, '<EvalJS snippet>', 'exec') exec (compiled, self._context)",
"{return x*x};') >>> ctx.f(9) 81 >>> ctx.a 10 context is",
"program. Returns (eval_value, context). ''' if context is None: context",
"you have a temp folder: filename = 'temp' + os.sep",
"ctx.a 10 context is a python dict or object that",
"DEFAULT_HEADER from .es6 import js6_to_js5 import sys import time import",
"\"utf-8\") as f: js = f.read() e = EvalJs() e.execute(js)",
"current context as opposed to the (faster) self.execute method, you",
"typically expensive compared to actually running the generated python code.",
"tail = '\\n\\n# Add lib to the module scope\\n%s =",
"make sure you have a temp folder: filename = 'temp'",
"its value as opposed to the (faster) self.execute method, you",
"= eval(%s)' % json.dumps(expression) self.execute_debug(code) return self['PyJsEvalResult'] @property def context(self):",
"path_as_local(path): if os.path.isabs(path): return path # relative to cwd return",
"wrapper - basically behaves like normal python object. If you",
"def execute(self, js=None, use_compilation_plan=False): \"\"\"executes javascript js in current context",
"code.encode(\"utf-8\")).hexdigest() + '.py' try: with open(filename, mode='w') as f: f.write(code)",
"javascript eval. Translates javascript to python, executes and returns python",
"Python code :) I don\\'t.\\n\\n' % repr( lib_name) tail =",
"'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute(code, use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult'] def",
"eval_debug(self, expression): \"\"\"evaluates expression in current context and returns its",
"def console(self): \"\"\"starts to interact (starts interactive console) Something like",
"to_python return require(to_python(npm_module_name), context=self._context) setattr(self._var, 'require', _js_require_impl) if not isinstance(context,",
"(compiled, self._context) def eval(self, expression, use_compilation_plan=False): \"\"\"evaluates expression in current",
"like javascript eval. Translates javascript to python, executes and returns",
"3) u'12' >>> add.constructor function Function() { [python code] }",
"js2py >>> add = js2py.eval_js('function add(a, b) {return a +",
"EvalJS object. Runs given path as a JS program. Returns",
"eval_js6(js): \"\"\"Just like eval_js but with experimental support for js6",
"context.eval(get_file_contents(path_or_file)) return eval_value, context def eval_js(js): \"\"\"Just like javascript eval.",
"js in current context as opposed to the (faster) self.execute",
"''' js = get_file_contents(input_path) py_code = translate_js(js) lib_name = os.path.basename(output_path).split('.')[0]",
"e.eval(js) def eval_js6(js): \"\"\"Just like eval_js but with experimental support",
"else: sys.stderr.write('EXCEPTION: ' + str(e) + '\\n') time.sleep(0.01) #print x",
"f: js = f.read() e = EvalJs() e.execute(js) var =",
"{return a + b}') >>> add(1, 2) + 3 6",
"enable_require=False): self.__dict__['_context'] = {} exec (DEFAULT_HEADER, self._context) self.__dict__['_var'] = self._context['var'].to_python()",
"function(x) {return x} translate_file('example.js', 'example.py') Now example.py can be easily",
"the end so that it is easy to import JS",
"30}) >>> ctx.execute('var x = a') >>> ctx.x 30 You",
"open(path_as_local(path_or_file), 'w') as f: f.write(contents) def translate_file(input_path, output_path): ''' Translates",
"globals is your globals()\"\"\" with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f:",
"js is javascript source code EXAMPLE: >>> import js2py >>>",
"six.iteritems(context): setattr(self._var, k, v) def execute(self, js=None, use_compilation_plan=False): \"\"\"executes javascript",
"support for js6 via babel.\"\"\" return eval_js(js6_to_js5(js)) def translate_js6(js): \"\"\"Just",
"return self._context def __getattr__(self, var): return getattr(self._var, var) def __getitem__(self,",
"import sys import time import json import six import os",
"disable_pyimport(): import pyjsparser.parser pyjsparser.parser.ENABLE_PYIMPORT = False def path_as_local(path): if os.path.isabs(path):",
"memory usage. \"\"\" try: cache = self.__dict__['cache'] except KeyError: cache",
"regular debugger to set breakpoints and inspect the generated python",
"file 'example.js' with: var a = function(x) {return x} translate_file('example.js',",
"translate_file(input_path, output_path): ''' Translates input JS file to python and",
"self._context) except Exception as err: raise err finally: os.remove(filename) try:",
"+ '_' + hashlib.md5( code.encode(\"utf-8\")).hexdigest() + '.py' try: with open(filename,",
"filename = 'temp' + os.sep + '_' + hashlib.md5( code.encode(\"utf-8\")).hexdigest()",
"as e: import traceback if DEBUG: sys.stderr.write(traceback.format_exc()) else: sys.stderr.write('EXCEPTION: '",
"= e.context['var'] globals[lib_name] = var.to_python() def get_file_contents(path_or_file): if hasattr(path_or_file, 'read'):",
"+ b}') >>> add(1, 2) + 3 6 >>> add('1',",
"and inspect the generated python code \"\"\" code = 'PyJsEvalResult",
"inspect the generated python code \"\"\" code = 'PyJsEvalResult =",
"and saves the it to the output path. It appends",
">>> ctx.execute('var a = 10;function f(x) {return x*x};') >>> ctx.f(9)",
"and used: >>> from example import example >>> example.a(30) 30",
"def run_file(path_or_file, context=None): ''' Context must be EvalJS object. Runs",
"as f: f.write(code) with open(filename, \"r\") as f: pyCode =",
"javascript under same context. >>> ctx = EvalJs() >>> ctx.execute('var",
"code = input('>>>') try: print(self.eval(code)) except KeyboardInterrupt: break except Exception",
"ctx = EvalJs(enable_require=True) >>> ctx.execute(\"var esprima = require('esprima');\") >>> ctx.execute(\"esprima.parse('var",
"needed to parse and convert the js code to python",
".es6 import js6_to_js5 import sys import time import json import",
"'import_js', 'eval_js', 'translate_file', 'eval_js6', 'translate_js6', 'run_file', 'disable_pyimport', 'get_file_contents', 'write_file_contents' ]",
"err: raise err finally: os.remove(filename) try: os.remove(filename + 'c') except:",
"'\\n\\n# Add lib to the module scope\\n%s = var.to_python()' %",
"self.execute method, you can use your regular debugger to set",
"% json.dumps(expression) self.execute_debug(code) return self['PyJsEvalResult'] @property def context(self): return self._context",
"get_file_contents(path_or_file): if hasattr(path_or_file, 'read'): js = path_or_file.read() else: with codecs.open(path_as_local(path_or_file),",
"source code EXAMPLE: >>> import js2py >>> add = js2py.eval_js('function",
"\"\"\" e = EvalJs() return e.eval(js) def eval_js6(js): \"\"\"Just like",
">>> ctx.execute(\"esprima.parse('var a = 1')\") You can run interactive javascript",
"os.sep + '_' + hashlib.md5( code.encode(\"utf-8\")).hexdigest() + '.py' try: with",
"self['PyJsEvalResult'] def eval_js6(self, expression, use_compilation_plan=False): \"\"\"same as eval, except that",
"module scope\\n%s = var.to_python()' % lib_name out = head +",
"= EvalJs({'a': 30}) >>> ctx.execute('var x = a') >>> ctx.x",
"pyjsparser.parser.ENABLE_PYIMPORT = False def path_as_local(path): if os.path.isabs(path): return path #",
"x if __name__ == '__main__': #with open('C:\\Users\\Piotrek\\Desktop\\esprima.js', 'rb') as f:",
"code. Note that the cache is just a dict, it",
"for js6 via babel.\"\"\" return eval_js(js6_to_js5(js)) def translate_js6(js): \"\"\"Just like",
"code.InteractiveConsole\"\"\" while True: if six.PY2: code = raw_input('>>> ') else:",
"a + b}') >>> add(1, 2) + 3 6 >>>",
"Context must be EvalJS object. Runs given path as a",
"(a cache dicts is updated) but the Js=>Py conversion process",
"# coding=utf-8 from .translators import translate_js, DEFAULT_HEADER from .es6 import",
"js modules from npm, for example: >>> ctx = EvalJs(enable_require=True)",
"snippets it might increase memory usage. \"\"\" try: cache =",
"try: compiled = cache[hashkey] except KeyError: code = translate_js( js,",
"the generated python code \"\"\" code = translate_js(js, '') #",
"convenience code at the end so that it is easy",
"hashkey = hashlib.md5(js.encode('utf-8')).digest() try: compiled = cache[hashkey] except KeyError: code",
"def eval_js6(self, expression, use_compilation_plan=False): \"\"\"same as eval, except that the",
"attr') for k, v in six.iteritems(context): setattr(self._var, k, v) def",
"to interact (starts interactive console) Something like code.InteractiveConsole\"\"\" while True:",
"+ 3 6 >>> add('1', 2, 3) u'12' >>> add.constructor",
"f: f.write(contents) def translate_file(input_path, output_path): ''' Translates input JS file",
"'write_file_contents' ] DEBUG = False def disable_pyimport(): import pyjsparser.parser pyjsparser.parser.ENABLE_PYIMPORT",
"continuous execution of javascript under same context. >>> ctx =",
"lib_name) tail = '\\n\\n# Add lib to the module scope\\n%s",
"this in automated situations with vast amounts of snippets it",
"filename, 'exec') exec(pyCode, self._context) except Exception as err: raise err",
"sys import time import json import six import os import",
"ctx.execute('var x = a') >>> ctx.x 30 You can enable",
"to parse and convert the js code to python code.",
"code \"\"\" code = translate_js(js, '') # make sure you",
"return getattr(self._var, var) def __setattr__(self, var, val): return setattr(self._var, var,",
"must be EvalJS object. Runs given path as a JS",
"raise TypeError('context must be the instance of EvalJs') eval_value =",
"javascript snippet you save many instructions needed to parse and",
"var): return getattr(self._var, var) def __setattr__(self, var, val): return setattr(self._var,",
"f.write(code) with open(filename, \"r\") as f: pyCode = compile(f.read(), filename,",
"to be either a dict or have __dict__ attr') for",
"a dict or have __dict__ attr') for k, v in",
"globals()\"\"\" with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f: js = f.read()",
"e = EvalJs() e.execute(js) var = e.context['var'] globals[lib_name] = var.to_python()",
"== '__main__': #with open('C:\\Users\\Piotrek\\Desktop\\esprima.js', 'rb') as f: # x =",
"is typically expensive compared to actually running the generated python",
"as f: f.write(contents) def translate_file(input_path, output_path): ''' Translates input JS",
"def eval_js(js): \"\"\"Just like javascript eval. Translates javascript to python,",
"same javascript snippet you save many instructions needed to parse",
"self.eval(es5_expression, use_compilation_plan) def execute_debug(self, js): \"\"\"executes javascript js in current",
"setattr(self._var, var, val) def __setitem__(self, var, val): return setattr(self._var, var,",
"cached for re-use. That means next time you run the",
"context is a python dict or object that contains python",
"expiration or cleanup so when running this in automated situations",
"js6_to_js5(expression) return self.eval(es5_expression, use_compilation_plan) def execute_debug(self, js): \"\"\"executes javascript js",
"and objects, returns Python wrapper - basically behaves like normal",
"import to_python return require(to_python(npm_module_name), context=self._context) setattr(self._var, 'require', _js_require_impl) if not",
"\"\"\"Just like javascript eval. Translates javascript to python, executes and",
"expensive compared to actually running the generated python code. Note",
"Add lib to the module scope\\n%s = var.to_python()' % lib_name",
"'require', _js_require_impl) if not isinstance(context, dict): try: context = context.__dict__",
"javascript source code EXAMPLE: >>> import js2py >>> add =",
"\"\"\"evaluates expression in current context and returns its value\"\"\" code",
"return getattr(self._var, var) def __getitem__(self, var): return getattr(self._var, var) def",
"= input('>>>') try: print(self.eval(code)) except KeyboardInterrupt: break except Exception as",
"but with experimental support for js6 via babel.\"\"\" return eval_js(js6_to_js5(js))",
"output_path): ''' Translates input JS file to python and saves",
"self.__dict__['cache'] except KeyError: cache = self.__dict__['cache'] = {} hashkey =",
"a file 'example.js' with: var a = function(x) {return x}",
"cache[hashkey] except KeyError: code = translate_js( js, '', use_compilation_plan=use_compilation_plan) compiled",
"time.sleep(0.01) #print x if __name__ == '__main__': #with open('C:\\Users\\Piotrek\\Desktop\\esprima.js', 'rb')",
"% json.dumps(expression) self.execute(code, use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult'] def eval_js6(self, expression, use_compilation_plan=False):",
"self._context def __getattr__(self, var): return getattr(self._var, var) def __getitem__(self, var):",
"situations with vast amounts of snippets it might increase memory",
"= get_file_contents(input_path) py_code = translate_js(js) lib_name = os.path.basename(output_path).split('.')[0] head =",
"to python dict you can use to_dict method. \"\"\" e",
"+ hashlib.md5( code.encode(\"utf-8\")).hexdigest() + '.py' try: with open(filename, mode='w') as",
"folder: filename = 'temp' + os.sep + '_' + hashlib.md5(",
"hasattr(path_or_file, 'write'): path_or_file.write(contents) else: with open(path_as_local(path_or_file), 'w') as f: f.write(contents)",
"except that the JS code gets translated from es6 to",
"else: with codecs.open(path_as_local(path_or_file), \"r\", \"utf-8\") as f: js = f.read()",
"import pyjsparser.parser pyjsparser.parser.ENABLE_PYIMPORT = False def path_as_local(path): if os.path.isabs(path): return",
"lib_name = os.path.basename(output_path).split('.')[0] head = '__all__ = [%s]\\n\\n# Don\\'t look",
"'_' + hashlib.md5( code.encode(\"utf-8\")).hexdigest() + '.py' try: with open(filename, mode='w')",
"import require from .base import to_python return require(to_python(npm_module_name), context=self._context) setattr(self._var,",
"with experimental support for js6 via babel.\"\"\" return translate_js(js6_to_js5(js)) class",
"try: context = context.__dict__ except: raise TypeError( 'context has to",
"will not understand this Python code :) I don\\'t.\\n\\n' %",
"from es6 to es5 before being executed.\"\"\" es5_expression = js6_to_js5(expression)",
"raise TypeError( 'context has to be either a dict or",
"= translate_js(js, '') # make sure you have a temp",
"to the module scope\\n%s = var.to_python()' % lib_name out =",
"with open(path_as_local(path_or_file), 'w') as f: f.write(contents) def translate_file(input_path, output_path): '''",
"context). ''' if context is None: context = EvalJs() if",
"e.execute(js) var = e.context['var'] globals[lib_name] = var.to_python() def get_file_contents(path_or_file): if",
"EvalJs') eval_value = context.eval(get_file_contents(path_or_file)) return eval_value, context def eval_js(js): \"\"\"Just",
"compiled = cache[hashkey] = compile(code, '<EvalJS snippet>', 'exec') exec (compiled,",
"the (faster) self.execute method, you can use your regular debugger",
"of EvalJs') eval_value = context.eval(get_file_contents(path_or_file)) return eval_value, context def eval_js(js):",
"a = 10;function f(x) {return x*x};') >>> ctx.f(9) 81 >>>",
"use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult'] def eval_js6(self, expression, use_compilation_plan=False): \"\"\"same as eval,",
"'eval_js', 'translate_file', 'eval_js6', 'translate_js6', 'run_file', 'disable_pyimport', 'get_file_contents', 'write_file_contents' ] DEBUG",
"json.dumps(expression) self.execute(code, use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult'] def eval_js6(self, expression, use_compilation_plan=False): \"\"\"same",
"babel.\"\"\" return eval_js(js6_to_js5(js)) def translate_js6(js): \"\"\"Just like translate_js but with",
"python code \"\"\" code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression)",
"cleanup so when running this in automated situations with vast",
"so when running this in automated situations with vast amounts",
"hasattr(path_or_file, 'read'): js = path_or_file.read() else: with codecs.open(path_as_local(path_or_file), \"r\", \"utf-8\")",
"Note that the cache is just a dict, it has",
"e.context['var'] globals[lib_name] = var.to_python() def get_file_contents(path_or_file): if hasattr(path_or_file, 'read'): js",
"context.__dict__ except: raise TypeError( 'context has to be either a",
"want to convert object to python dict you can use",
"return eval_js(js6_to_js5(js)) def translate_js6(js): \"\"\"Just like translate_js but with experimental",
"class supports continuous execution of javascript under same context. >>>",
"add = js2py.eval_js('function add(a, b) {return a + b}') >>>",
"os.path.join(os.getcwd(), path) def import_js(path, lib_name, globals): \"\"\"Imports from javascript source",
"coding=utf-8 from .translators import translate_js, DEFAULT_HEADER from .es6 import js6_to_js5",
"with codecs.open(path_as_local(path_or_file), \"r\", \"utf-8\") as f: js = f.read() return",
"print(self.eval(code)) except KeyboardInterrupt: break except Exception as e: import traceback",
"= 10;function f(x) {return x*x};') >>> ctx.f(9) 81 >>> ctx.a",
"if six.PY2: code = raw_input('>>> ') else: code = input('>>>')",
"f: js = f.read() return js def write_file_contents(path_or_file, contents): if",
"self._context) def eval(self, expression, use_compilation_plan=False): \"\"\"evaluates expression in current context",
"return eval_value, context def eval_js(js): \"\"\"Just like javascript eval. Translates",
"= '\\n\\n# Add lib to the module scope\\n%s = var.to_python()'",
"in current context as opposed to the (faster) self.execute method,",
"or cleanup so when running this in automated situations with",
"js = path_or_file.read() else: with codecs.open(path_as_local(path_or_file), \"r\", \"utf-8\") as f:",
"True: if six.PY2: code = raw_input('>>> ') else: code =",
"from .es6 import js6_to_js5 import sys import time import json",
"experimental support for js6 via babel.\"\"\" return eval_js(js6_to_js5(js)) def translate_js6(js):",
"require(to_python(npm_module_name), context=self._context) setattr(self._var, 'require', _js_require_impl) if not isinstance(context, dict): try:",
"js, '', use_compilation_plan=use_compilation_plan) compiled = cache[hashkey] = compile(code, '<EvalJS snippet>',",
"you will not understand this Python code :) I don\\'t.\\n\\n'",
"cwd return os.path.join(os.getcwd(), path) def import_js(path, lib_name, globals): \"\"\"Imports from",
"{ [python code] } NOTE: For Js Number, String, Boolean",
"you can use to_dict method. \"\"\" e = EvalJs() return",
"set breakpoints and inspect the generated python code \"\"\" code",
"'run_file', 'disable_pyimport', 'get_file_contents', 'write_file_contents' ] DEBUG = False def disable_pyimport():",
"'.py' try: with open(filename, mode='w') as f: f.write(code) with open(filename,",
"= self._context['var'].to_python() if enable_require: def _js_require_impl(npm_module_name): from .node_import import require",
"function via enable_require. With this feature enabled you can use",
"import six import os import hashlib import codecs __all__ =",
"cache = self.__dict__['cache'] except KeyError: cache = self.__dict__['cache'] = {}",
"var, val) def __setitem__(self, var, val): return setattr(self._var, var, val)",
"generated python code \"\"\" code = 'PyJsEvalResult = eval(%s)' %",
"import traceback if DEBUG: sys.stderr.write(traceback.format_exc()) else: sys.stderr.write('EXCEPTION: ' + str(e)",
"add(1, 2) + 3 6 >>> add('1', 2, 3) u'12'",
"import js6_to_js5 import sys import time import json import six",
"re-use. That means next time you run the same javascript",
"def import_js(path, lib_name, globals): \"\"\"Imports from javascript source file. globals",
"example >>> example.a(30) 30 ''' js = get_file_contents(input_path) py_code =",
"if os.path.isabs(path): return path # relative to cwd return os.path.join(os.getcwd(),",
"js6 via babel.\"\"\" return translate_js(js6_to_js5(js)) class EvalJs(object): \"\"\"This class supports",
"code at the end so that it is easy to",
"out = head + py_code + tail write_file_contents(output_path, out) def",
"the it to the output path. It appends some convenience",
"10 context is a python dict or object that contains",
"pyjsparser.parser pyjsparser.parser.ENABLE_PYIMPORT = False def path_as_local(path): if os.path.isabs(path): return path",
"some convenience code at the end so that it is",
"interactive javascript console with console method!\"\"\" def __init__(self, context={}, enable_require=False):",
"functions and objects, returns Python wrapper - basically behaves like",
"from .node_import import require from .base import to_python return require(to_python(npm_module_name),",
"translate_js6(js): \"\"\"Just like translate_js but with experimental support for js6",
"False def path_as_local(path): if os.path.isabs(path): return path # relative to",
"x = a') >>> ctx.x 30 You can enable JS",
"write_file_contents(output_path, out) def run_file(path_or_file, context=None): ''' Context must be EvalJS",
"run_file(path_or_file, context=None): ''' Context must be EvalJS object. Runs given",
"'temp' + os.sep + '_' + hashlib.md5( code.encode(\"utf-8\")).hexdigest() + '.py'",
"object. Runs given path as a JS program. Returns (eval_value,",
"JavaScript For example: >>> ctx = EvalJs({'a': 30}) >>> ctx.execute('var",
"_js_require_impl(npm_module_name): from .node_import import require from .base import to_python return",
"snippet you save many instructions needed to parse and convert",
"\"\"\" try: cache = self.__dict__['cache'] except KeyError: cache = self.__dict__['cache']",
"__name__ == '__main__': #with open('C:\\Users\\Piotrek\\Desktop\\esprima.js', 'rb') as f: # x",
"import codecs __all__ = [ 'EvalJs', 'translate_js', 'import_js', 'eval_js', 'translate_file',",
"context and returns its value as opposed to the (faster)",
"saves the it to the output path. It appends some",
"codecs __all__ = [ 'EvalJs', 'translate_js', 'import_js', 'eval_js', 'translate_file', 'eval_js6',",
"as err: raise err finally: os.remove(filename) try: os.remove(filename + 'c')",
"'w') as f: f.write(contents) def translate_file(input_path, output_path): ''' Translates input",
"= context.eval(get_file_contents(path_or_file)) return eval_value, context def eval_js(js): \"\"\"Just like javascript",
"the JS code gets translated from es6 to es5 before",
"expression, use_compilation_plan=False): \"\"\"evaluates expression in current context and returns its",
"translate_js(js) lib_name = os.path.basename(output_path).split('.')[0] head = '__all__ = [%s]\\n\\n# Don\\'t",
"json.dumps(expression) self.execute_debug(code) return self['PyJsEvalResult'] @property def context(self): return self._context def",
"basically behaves like normal python object. If you really want",
"mode='w') as f: f.write(code) with open(filename, \"r\") as f: pyCode",
"current context and returns its value\"\"\" code = 'PyJsEvalResult =",
"lib to the module scope\\n%s = var.to_python()' % lib_name out",
"sure you have a temp folder: filename = 'temp' +",
"next time you run the same javascript snippet you save",
"= False def path_as_local(path): if os.path.isabs(path): return path # relative",
"sys.stderr.write(traceback.format_exc()) else: sys.stderr.write('EXCEPTION: ' + str(e) + '\\n') time.sleep(0.01) #print",
"a JS program. Returns (eval_value, context). ''' if context is",
"def __getattr__(self, var): return getattr(self._var, var) def __getitem__(self, var): return",
"available to JavaScript For example: >>> ctx = EvalJs({'a': 30})",
"[%s]\\n\\n# Don\\'t look below, you will not understand this Python",
"self['PyJsEvalResult'] @property def context(self): return self._context def __getattr__(self, var): return",
"KeyError: code = translate_js( js, '', use_compilation_plan=use_compilation_plan) compiled = cache[hashkey]",
"k, v in six.iteritems(context): setattr(self._var, k, v) def execute(self, js=None,",
"EvalJs() e.execute(js) var = e.context['var'] globals[lib_name] = var.to_python() def get_file_contents(path_or_file):",
"= os.path.basename(output_path).split('.')[0] head = '__all__ = [%s]\\n\\n# Don\\'t look below,",
"enable_require. With this feature enabled you can use js modules",
"console method!\"\"\" def __init__(self, context={}, enable_require=False): self.__dict__['_context'] = {} exec",
"context = context.__dict__ except: raise TypeError( 'context has to be",
"var.to_python() def get_file_contents(path_or_file): if hasattr(path_or_file, 'read'): js = path_or_file.read() else:",
"not isinstance(context, dict): try: context = context.__dict__ except: raise TypeError(",
"save many instructions needed to parse and convert the js",
"be EvalJS object. Runs given path as a JS program.",
"of javascript under same context. >>> ctx = EvalJs() >>>",
"types returns appropriate python BUILTIN type. For Js functions and",
"10;function f(x) {return x*x};') >>> ctx.f(9) 81 >>> ctx.a 10",
"except KeyboardInterrupt: break except Exception as e: import traceback if",
"context(self): return self._context def __getattr__(self, var): return getattr(self._var, var) def",
"= '__all__ = [%s]\\n\\n# Don\\'t look below, you will not",
"2, 3) u'12' >>> add.constructor function Function() { [python code]",
"head + py_code + tail write_file_contents(output_path, out) def run_file(path_or_file, context=None):",
"err finally: os.remove(filename) try: os.remove(filename + 'c') except: pass def",
"is javascript source code EXAMPLE: >>> import js2py >>> add",
"returns Python wrapper - basically behaves like normal python object.",
"setattr(self._var, k, v) def execute(self, js=None, use_compilation_plan=False): \"\"\"executes javascript js",
"not isinstance(context, EvalJs): raise TypeError('context must be the instance of",
"the same javascript snippet you save many instructions needed to",
"write_file_contents(path_or_file, contents): if hasattr(path_or_file, 'write'): path_or_file.write(contents) else: with open(path_as_local(path_or_file), 'w')",
"Don\\'t look below, you will not understand this Python code",
"for k, v in six.iteritems(context): setattr(self._var, k, v) def execute(self,",
"end so that it is easy to import JS objects.",
"use_compilation_plan=False): \"\"\"same as eval, except that the JS code gets",
"__getattr__(self, var): return getattr(self._var, var) def __getitem__(self, var): return getattr(self._var,",
"'\\n') time.sleep(0.01) #print x if __name__ == '__main__': #with open('C:\\Users\\Piotrek\\Desktop\\esprima.js',",
"TypeError( 'context has to be either a dict or have",
"self.execute(code, use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult'] def eval_js6(self, expression, use_compilation_plan=False): \"\"\"same as",
"ctx.execute(\"esprima.parse('var a = 1')\") You can run interactive javascript console",
"file. globals is your globals()\"\"\" with codecs.open(path_as_local(path), \"r\", \"utf-8\") as",
"return require(to_python(npm_module_name), context=self._context) setattr(self._var, 'require', _js_require_impl) if not isinstance(context, dict):",
"v) def execute(self, js=None, use_compilation_plan=False): \"\"\"executes javascript js in current",
"import translate_js, DEFAULT_HEADER from .es6 import js6_to_js5 import sys import",
"example.a(30) 30 ''' js = get_file_contents(input_path) py_code = translate_js(js) lib_name",
"python BUILTIN type. For Js functions and objects, returns Python",
"Now example.py can be easily importend and used: >>> from",
"eval_value, context def eval_js(js): \"\"\"Just like javascript eval. Translates javascript",
"via babel.\"\"\" return eval_js(js6_to_js5(js)) def translate_js6(js): \"\"\"Just like translate_js but",
"py_code + tail write_file_contents(output_path, out) def run_file(path_or_file, context=None): ''' Context",
"EvalJs(object): \"\"\"This class supports continuous execution of javascript under same",
"'') # make sure you have a temp folder: filename",
"= function(x) {return x} translate_file('example.js', 'example.py') Now example.py can be",
"var) def __getitem__(self, var): return getattr(self._var, var) def __setattr__(self, var,",
"expression, use_compilation_plan=False): \"\"\"same as eval, except that the JS code",
"it might increase memory usage. \"\"\" try: cache = self.__dict__['cache']",
"return js def write_file_contents(path_or_file, contents): if hasattr(path_or_file, 'write'): path_or_file.write(contents) else:",
"__getitem__(self, var): return getattr(self._var, var) def __setattr__(self, var, val): return",
"val) def console(self): \"\"\"starts to interact (starts interactive console) Something",
"ctx.execute(\"var esprima = require('esprima');\") >>> ctx.execute(\"esprima.parse('var a = 1')\") You",
"enable JS require function via enable_require. With this feature enabled",
"via babel.\"\"\" return translate_js(js6_to_js5(js)) class EvalJs(object): \"\"\"This class supports continuous",
"= eval(%s)' % json.dumps(expression) self.execute(code, use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult'] def eval_js6(self,",
"it has no expiration or cleanup so when running this",
"except KeyError: cache = self.__dict__['cache'] = {} hashkey = hashlib.md5(js.encode('utf-8')).digest()",
"import JS objects. For example we have a file 'example.js'",
"= [ 'EvalJs', 'translate_js', 'import_js', 'eval_js', 'translate_file', 'eval_js6', 'translate_js6', 'run_file',",
"can be easily importend and used: >>> from example import",
"expression): \"\"\"evaluates expression in current context and returns its value",
"objects, returns Python wrapper - basically behaves like normal python",
"(faster) self.execute method, you can use your regular debugger to",
"use your regular debugger to set breakpoints and inspect the",
"= translate_js(js) lib_name = os.path.basename(output_path).split('.')[0] head = '__all__ = [%s]\\n\\n#",
"the cache is just a dict, it has no expiration",
"type. For Js functions and objects, returns Python wrapper -",
"+ '\\n') time.sleep(0.01) #print x if __name__ == '__main__': #with",
"cache dicts is updated) but the Js=>Py conversion process is",
"automated situations with vast amounts of snippets it might increase",
"__setattr__(self, var, val): return setattr(self._var, var, val) def __setitem__(self, var,",
"= path_or_file.read() else: with codecs.open(path_as_local(path_or_file), \"r\", \"utf-8\") as f: js",
"convert object to python dict you can use to_dict method.",
"if hasattr(path_or_file, 'write'): path_or_file.write(contents) else: with open(path_as_local(path_or_file), 'w') as f:",
"understand this Python code :) I don\\'t.\\n\\n' % repr( lib_name)",
"have __dict__ attr') for k, v in six.iteritems(context): setattr(self._var, k,",
"= {} hashkey = hashlib.md5(js.encode('utf-8')).digest() try: compiled = cache[hashkey] except",
"js2py.eval_js('function add(a, b) {return a + b}') >>> add(1, 2)",
"require function via enable_require. With this feature enabled you can",
"return e.eval(js) def eval_js6(js): \"\"\"Just like eval_js but with experimental",
"via enable_require. With this feature enabled you can use js",
"can use your regular debugger to set breakpoints and inspect",
"file to python and saves the it to the output",
"2) + 3 6 >>> add('1', 2, 3) u'12' >>>",
"in current context and returns its value\"\"\" code = 'PyJsEvalResult",
">>> from example import example >>> example.a(30) 30 ''' js",
"var = e.context['var'] globals[lib_name] = var.to_python() def get_file_contents(path_or_file): if hasattr(path_or_file,",
"For Js functions and objects, returns Python wrapper - basically",
"eval_js6(self, expression, use_compilation_plan=False): \"\"\"same as eval, except that the JS",
"python code. This cache causes minor overhead (a cache dicts",
"def get_file_contents(path_or_file): if hasattr(path_or_file, 'read'): js = path_or_file.read() else: with",
"hashlib.md5(js.encode('utf-8')).digest() try: compiled = cache[hashkey] except KeyError: code = translate_js(",
"really want to convert object to python dict you can",
"tail write_file_contents(output_path, out) def run_file(path_or_file, context=None): ''' Context must be",
"cache causes minor overhead (a cache dicts is updated) but",
"ctx.execute('var a = 10;function f(x) {return x*x};') >>> ctx.f(9) 81",
"context is None: context = EvalJs() if not isinstance(context, EvalJs):",
"python dict you can use to_dict method. \"\"\" e =",
"try: cache = self.__dict__['cache'] except KeyError: cache = self.__dict__['cache'] =",
"eval(%s)' % json.dumps(expression) self.execute(code, use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult'] def eval_js6(self, expression,",
"def eval_js6(js): \"\"\"Just like eval_js but with experimental support for",
"running the generated python code. Note that the cache is",
"value\"\"\" code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute(code, use_compilation_plan=use_compilation_plan)",
"time you run the same javascript snippet you save many",
"\"r\") as f: pyCode = compile(f.read(), filename, 'exec') exec(pyCode, self._context)",
"return setattr(self._var, var, val) def __setitem__(self, var, val): return setattr(self._var,",
"use_compilation_plan=False): \"\"\"executes javascript js in current context During initial execute()",
"\"\"\" code = translate_js(js, '') # make sure you have",
"js code to python code. This cache causes minor overhead",
"var, val): return setattr(self._var, var, val) def __setitem__(self, var, val):",
"python dict or object that contains python variables that should",
"as a JS program. Returns (eval_value, context). ''' if context",
"context and returns its value\"\"\" code = 'PyJsEvalResult = eval(%s)'",
"with open(filename, \"r\") as f: pyCode = compile(f.read(), filename, 'exec')",
"except: raise TypeError( 'context has to be either a dict",
"Boolean and other base types returns appropriate python BUILTIN type.",
"raw_input('>>> ') else: code = input('>>>') try: print(self.eval(code)) except KeyboardInterrupt:",
"JS file to python and saves the it to the",
"return self.eval(es5_expression, use_compilation_plan) def execute_debug(self, js): \"\"\"executes javascript js in",
"def __setattr__(self, var, val): return setattr(self._var, var, val) def __setitem__(self,",
"normal python object. If you really want to convert object",
"This cache causes minor overhead (a cache dicts is updated)",
"javascript to python, executes and returns python object. js is",
"appends some convenience code at the end so that it",
"code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute_debug(code) return self['PyJsEvalResult']",
"compiled = cache[hashkey] except KeyError: code = translate_js( js, '',",
"EvalJs() return e.eval(js) def eval_js6(js): \"\"\"Just like eval_js but with",
"context=self._context) setattr(self._var, 'require', _js_require_impl) if not isinstance(context, dict): try: context",
"ctx.f(9) 81 >>> ctx.a 10 context is a python dict",
"get_file_contents(input_path) py_code = translate_js(js) lib_name = os.path.basename(output_path).split('.')[0] head = '__all__",
"you can use js modules from npm, for example: >>>",
"__init__(self, context={}, enable_require=False): self.__dict__['_context'] = {} exec (DEFAULT_HEADER, self._context) self.__dict__['_var']",
"hashlib.md5( code.encode(\"utf-8\")).hexdigest() + '.py' try: with open(filename, mode='w') as f:",
"enabled you can use js modules from npm, for example:",
"no expiration or cleanup so when running this in automated",
"'translate_file', 'eval_js6', 'translate_js6', 'run_file', 'disable_pyimport', 'get_file_contents', 'write_file_contents' ] DEBUG =",
"initial execute() the converted js is cached for re-use. That",
"'', use_compilation_plan=use_compilation_plan) compiled = cache[hashkey] = compile(code, '<EvalJS snippet>', 'exec')",
"six.PY2: code = raw_input('>>> ') else: code = input('>>>') try:",
"from .translators import translate_js, DEFAULT_HEADER from .es6 import js6_to_js5 import",
"can use to_dict method. \"\"\" e = EvalJs() return e.eval(js)",
"time import json import six import os import hashlib import",
"returns its value\"\"\" code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression)",
"and convert the js code to python code. This cache",
"with experimental support for js6 via babel.\"\"\" return eval_js(js6_to_js5(js)) def",
"is updated) but the Js=>Py conversion process is typically expensive",
"to_dict method. \"\"\" e = EvalJs() return e.eval(js) def eval_js6(js):",
"open(filename, mode='w') as f: f.write(code) with open(filename, \"r\") as f:",
"objects. For example we have a file 'example.js' with: var",
"use to_dict method. \"\"\" e = EvalJs() return e.eval(js) def",
"''' if context is None: context = EvalJs() if not",
"<reponame>inprod/Js2Py # coding=utf-8 from .translators import translate_js, DEFAULT_HEADER from .es6",
":) I don\\'t.\\n\\n' % repr( lib_name) tail = '\\n\\n# Add",
"b}') >>> add(1, 2) + 3 6 >>> add('1', 2,",
"context. >>> ctx = EvalJs() >>> ctx.execute('var a = 10;function",
"__all__ = [ 'EvalJs', 'translate_js', 'import_js', 'eval_js', 'translate_file', 'eval_js6', 'translate_js6',",
"dict or object that contains python variables that should be",
"modules from npm, for example: >>> ctx = EvalJs(enable_require=True) >>>",
"you save many instructions needed to parse and convert the",
"exec(pyCode, self._context) except Exception as err: raise err finally: os.remove(filename)",
"= require('esprima');\") >>> ctx.execute(\"esprima.parse('var a = 1')\") You can run",
"+ str(e) + '\\n') time.sleep(0.01) #print x if __name__ ==",
"example: >>> ctx = EvalJs({'a': 30}) >>> ctx.execute('var x =",
"var) def __setattr__(self, var, val): return setattr(self._var, var, val) def",
"the Js=>Py conversion process is typically expensive compared to actually",
"open(filename, \"r\") as f: pyCode = compile(f.read(), filename, 'exec') exec(pyCode,",
"var.to_python()' % lib_name out = head + py_code + tail",
"def translate_js6(js): \"\"\"Just like translate_js but with experimental support for",
"exec (compiled, self._context) def eval(self, expression, use_compilation_plan=False): \"\"\"evaluates expression in",
"cache = self.__dict__['cache'] = {} hashkey = hashlib.md5(js.encode('utf-8')).digest() try: compiled",
"return translate_js(js6_to_js5(js)) class EvalJs(object): \"\"\"This class supports continuous execution of",
"eval(self, expression, use_compilation_plan=False): \"\"\"evaluates expression in current context and returns",
"isinstance(context, dict): try: context = context.__dict__ except: raise TypeError( 'context",
"if hasattr(path_or_file, 'read'): js = path_or_file.read() else: with codecs.open(path_as_local(path_or_file), \"r\",",
"var, val): return setattr(self._var, var, val) def console(self): \"\"\"starts to",
"compile(f.read(), filename, 'exec') exec(pyCode, self._context) except Exception as err: raise",
"try: os.remove(filename + 'c') except: pass def eval_debug(self, expression): \"\"\"evaluates",
"from .base import to_python return require(to_python(npm_module_name), context=self._context) setattr(self._var, 'require', _js_require_impl)",
"execute() the converted js is cached for re-use. That means",
"add('1', 2, 3) u'12' >>> add.constructor function Function() { [python",
"'exec') exec(pyCode, self._context) except Exception as err: raise err finally:",
"= f.read() e = EvalJs() e.execute(js) var = e.context['var'] globals[lib_name]",
"is easy to import JS objects. For example we have",
"} NOTE: For Js Number, String, Boolean and other base",
"'<EvalJS snippet>', 'exec') exec (compiled, self._context) def eval(self, expression, use_compilation_plan=False):",
"to cwd return os.path.join(os.getcwd(), path) def import_js(path, lib_name, globals): \"\"\"Imports",
"if __name__ == '__main__': #with open('C:\\Users\\Piotrek\\Desktop\\esprima.js', 'rb') as f: #",
"contents): if hasattr(path_or_file, 'write'): path_or_file.write(contents) else: with open(path_as_local(path_or_file), 'w') as",
"js6 via babel.\"\"\" return eval_js(js6_to_js5(js)) def translate_js6(js): \"\"\"Just like translate_js",
"current context During initial execute() the converted js is cached",
"if context is None: context = EvalJs() if not isinstance(context,",
"many instructions needed to parse and convert the js code",
"pass def eval_debug(self, expression): \"\"\"evaluates expression in current context and",
"f: # x = f.read() e = EvalJs() e.execute('square(x)') #e.execute(x)",
"that the JS code gets translated from es6 to es5",
"except Exception as e: import traceback if DEBUG: sys.stderr.write(traceback.format_exc()) else:",
"lib_name, globals): \"\"\"Imports from javascript source file. globals is your",
"os import hashlib import codecs __all__ = [ 'EvalJs', 'translate_js',",
"to import JS objects. For example we have a file",
"js = f.read() return js def write_file_contents(path_or_file, contents): if hasattr(path_or_file,",
"exec (DEFAULT_HEADER, self._context) self.__dict__['_var'] = self._context['var'].to_python() if enable_require: def _js_require_impl(npm_module_name):",
"= translate_js( js, '', use_compilation_plan=use_compilation_plan) compiled = cache[hashkey] = compile(code,",
"hashlib import codecs __all__ = [ 'EvalJs', 'translate_js', 'import_js', 'eval_js',",
"Runs given path as a JS program. Returns (eval_value, context).",
"out) def run_file(path_or_file, context=None): ''' Context must be EvalJS object.",
"= 1')\") You can run interactive javascript console with console",
"require from .base import to_python return require(to_python(npm_module_name), context=self._context) setattr(self._var, 'require',",
"from npm, for example: >>> ctx = EvalJs(enable_require=True) >>> ctx.execute(\"var",
"npm, for example: >>> ctx = EvalJs(enable_require=True) >>> ctx.execute(\"var esprima",
"example import example >>> example.a(30) 30 ''' js = get_file_contents(input_path)",
"source file. globals is your globals()\"\"\" with codecs.open(path_as_local(path), \"r\", \"utf-8\")",
"json import six import os import hashlib import codecs __all__",
"finally: os.remove(filename) try: os.remove(filename + 'c') except: pass def eval_debug(self,",
"= a') >>> ctx.x 30 You can enable JS require",
"is your globals()\"\"\" with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f: js",
"def __getitem__(self, var): return getattr(self._var, var) def __setattr__(self, var, val):",
"codecs.open(path_as_local(path_or_file), \"r\", \"utf-8\") as f: js = f.read() return js",
"not understand this Python code :) I don\\'t.\\n\\n' % repr(",
"js is cached for re-use. That means next time you",
"it to the output path. It appends some convenience code",
"u'12' >>> add.constructor function Function() { [python code] } NOTE:",
"code to python code. This cache causes minor overhead (a",
"x*x};') >>> ctx.f(9) 81 >>> ctx.a 10 context is a",
"= EvalJs() >>> ctx.execute('var a = 10;function f(x) {return x*x};')",
"pyCode = compile(f.read(), filename, 'exec') exec(pyCode, self._context) except Exception as",
"def eval(self, expression, use_compilation_plan=False): \"\"\"evaluates expression in current context and",
"python, executes and returns python object. js is javascript source",
"expression in current context and returns its value as opposed",
"used: >>> from example import example >>> example.a(30) 30 '''",
"parse and convert the js code to python code. This",
"execute(self, js=None, use_compilation_plan=False): \"\"\"executes javascript js in current context During",
"to set breakpoints and inspect the generated python code \"\"\"",
"I don\\'t.\\n\\n' % repr( lib_name) tail = '\\n\\n# Add lib",
"python code \"\"\" code = translate_js(js, '') # make sure",
"JS program. Returns (eval_value, context). ''' if context is None:",
"path_or_file.read() else: with codecs.open(path_as_local(path_or_file), \"r\", \"utf-8\") as f: js =",
"x} translate_file('example.js', 'example.py') Now example.py can be easily importend and",
"experimental support for js6 via babel.\"\"\" return translate_js(js6_to_js5(js)) class EvalJs(object):",
"sys.stderr.write('EXCEPTION: ' + str(e) + '\\n') time.sleep(0.01) #print x if",
"have a file 'example.js' with: var a = function(x) {return",
"the js code to python code. This cache causes minor",
"EXAMPLE: >>> import js2py >>> add = js2py.eval_js('function add(a, b)",
"import_js(path, lib_name, globals): \"\"\"Imports from javascript source file. globals is",
"= 'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute(code, use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult']",
"path as a JS program. Returns (eval_value, context). ''' if",
"def eval_debug(self, expression): \"\"\"evaluates expression in current context and returns",
"translate_js, DEFAULT_HEADER from .es6 import js6_to_js5 import sys import time",
">>> ctx = EvalJs() >>> ctx.execute('var a = 10;function f(x)",
"JS code gets translated from es6 to es5 before being",
">>> add.constructor function Function() { [python code] } NOTE: For",
"expression in current context and returns its value\"\"\" code =",
"but with experimental support for js6 via babel.\"\"\" return translate_js(js6_to_js5(js))",
"cache[hashkey] = compile(code, '<EvalJS snippet>', 'exec') exec (compiled, self._context) def",
"babel.\"\"\" return translate_js(js6_to_js5(js)) class EvalJs(object): \"\"\"This class supports continuous execution",
"to convert object to python dict you can use to_dict",
"k, v) def execute(self, js=None, use_compilation_plan=False): \"\"\"executes javascript js in",
"run the same javascript snippet you save many instructions needed",
"that should be available to JavaScript For example: >>> ctx",
"path # relative to cwd return os.path.join(os.getcwd(), path) def import_js(path,",
"your regular debugger to set breakpoints and inspect the generated",
"returns its value as opposed to the (faster) self.execute method,",
"except: pass def eval_debug(self, expression): \"\"\"evaluates expression in current context",
"a') >>> ctx.x 30 You can enable JS require function",
"interact (starts interactive console) Something like code.InteractiveConsole\"\"\" while True: if",
"str(e) + '\\n') time.sleep(0.01) #print x if __name__ == '__main__':",
"example we have a file 'example.js' with: var a =",
">>> ctx.execute('var x = a') >>> ctx.x 30 You can",
"like eval_js but with experimental support for js6 via babel.\"\"\"",
"before being executed.\"\"\" es5_expression = js6_to_js5(expression) return self.eval(es5_expression, use_compilation_plan) def",
"breakpoints and inspect the generated python code \"\"\" code =",
"Function() { [python code] } NOTE: For Js Number, String,",
"= compile(f.read(), filename, 'exec') exec(pyCode, self._context) except Exception as err:",
">>> import js2py >>> add = js2py.eval_js('function add(a, b) {return",
"is None: context = EvalJs() if not isinstance(context, EvalJs): raise",
".node_import import require from .base import to_python return require(to_python(npm_module_name), context=self._context)",
"{} hashkey = hashlib.md5(js.encode('utf-8')).digest() try: compiled = cache[hashkey] except KeyError:",
"KeyError: cache = self.__dict__['cache'] = {} hashkey = hashlib.md5(js.encode('utf-8')).digest() try:",
"use_compilation_plan=False): \"\"\"evaluates expression in current context and returns its value\"\"\"",
"the output path. It appends some convenience code at the",
"easily importend and used: >>> from example import example >>>",
">>> ctx = EvalJs(enable_require=True) >>> ctx.execute(\"var esprima = require('esprima');\") >>>",
"a = function(x) {return x} translate_file('example.js', 'example.py') Now example.py can",
"for js6 via babel.\"\"\" return translate_js(js6_to_js5(js)) class EvalJs(object): \"\"\"This class",
"can use js modules from npm, for example: >>> ctx",
"'EvalJs', 'translate_js', 'import_js', 'eval_js', 'translate_file', 'eval_js6', 'translate_js6', 'run_file', 'disable_pyimport', 'get_file_contents',",
"to python and saves the it to the output path.",
"For Js Number, String, Boolean and other base types returns",
"value as opposed to the (faster) self.execute method, you can",
"val): return setattr(self._var, var, val) def __setitem__(self, var, val): return",
"ctx = EvalJs({'a': 30}) >>> ctx.execute('var x = a') >>>",
"Exception as err: raise err finally: os.remove(filename) try: os.remove(filename +",
"import os import hashlib import codecs __all__ = [ 'EvalJs',",
"= raw_input('>>> ') else: code = input('>>>') try: print(self.eval(code)) except",
"ctx.x 30 You can enable JS require function via enable_require.",
"in current context During initial execute() the converted js is",
"break except Exception as e: import traceback if DEBUG: sys.stderr.write(traceback.format_exc())",
"\"\"\"Just like translate_js but with experimental support for js6 via",
"JS require function via enable_require. With this feature enabled you",
"context=None): ''' Context must be EvalJS object. Runs given path",
"context as opposed to the (faster) self.execute method, you can",
"be easily importend and used: >>> from example import example",
"You can run interactive javascript console with console method!\"\"\" def",
"for re-use. That means next time you run the same",
"self._context['var'].to_python() if enable_require: def _js_require_impl(npm_module_name): from .node_import import require from",
"81 >>> ctx.a 10 context is a python dict or",
"Js functions and objects, returns Python wrapper - basically behaves",
"\"\"\" code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute_debug(code) return",
"and returns its value\"\"\" code = 'PyJsEvalResult = eval(%s)' %",
"cache is just a dict, it has no expiration or",
"appropriate python BUILTIN type. For Js functions and objects, returns",
"= hashlib.md5(js.encode('utf-8')).digest() try: compiled = cache[hashkey] except KeyError: code =",
"as f: js = f.read() return js def write_file_contents(path_or_file, contents):",
"inspect the generated python code \"\"\" code = translate_js(js, '')",
"'translate_js6', 'run_file', 'disable_pyimport', 'get_file_contents', 'write_file_contents' ] DEBUG = False def",
"it is easy to import JS objects. For example we",
"method!\"\"\" def __init__(self, context={}, enable_require=False): self.__dict__['_context'] = {} exec (DEFAULT_HEADER,",
"to python code. This cache causes minor overhead (a cache",
"output path. It appends some convenience code at the end",
">>> add('1', 2, 3) u'12' >>> add.constructor function Function() {",
"from example import example >>> example.a(30) 30 ''' js =",
"= head + py_code + tail write_file_contents(output_path, out) def run_file(path_or_file,",
"variables that should be available to JavaScript For example: >>>",
"is a python dict or object that contains python variables",
"just a dict, it has no expiration or cleanup so",
"import json import six import os import hashlib import codecs",
"causes minor overhead (a cache dicts is updated) but the",
"os.remove(filename + 'c') except: pass def eval_debug(self, expression): \"\"\"evaluates expression",
"'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute_debug(code) return self['PyJsEvalResult'] @property def",
"try: print(self.eval(code)) except KeyboardInterrupt: break except Exception as e: import",
"and inspect the generated python code \"\"\" code = translate_js(js,",
"temp folder: filename = 'temp' + os.sep + '_' +",
"js6_to_js5 import sys import time import json import six import",
"console with console method!\"\"\" def __init__(self, context={}, enable_require=False): self.__dict__['_context'] =",
"'get_file_contents', 'write_file_contents' ] DEBUG = False def disable_pyimport(): import pyjsparser.parser",
"Python wrapper - basically behaves like normal python object. If",
"eval, except that the JS code gets translated from es6",
"and returns python object. js is javascript source code EXAMPLE:",
"'rb') as f: # x = f.read() e = EvalJs()",
"# make sure you have a temp folder: filename =",
"to JavaScript For example: >>> ctx = EvalJs({'a': 30}) >>>",
"% repr( lib_name) tail = '\\n\\n# Add lib to the",
"eval_value = context.eval(get_file_contents(path_or_file)) return eval_value, context def eval_js(js): \"\"\"Just like",
"+ '.py' try: with open(filename, mode='w') as f: f.write(code) with",
"return self['PyJsEvalResult'] @property def context(self): return self._context def __getattr__(self, var):",
"else: code = input('>>>') try: print(self.eval(code)) except KeyboardInterrupt: break except",
">>> ctx.execute(\"var esprima = require('esprima');\") >>> ctx.execute(\"esprima.parse('var a = 1')\")",
"javascript source file. globals is your globals()\"\"\" with codecs.open(path_as_local(path), \"r\",",
"''' Context must be EvalJS object. Runs given path as",
"\"\"\"executes javascript js in current context During initial execute() the",
"return path # relative to cwd return os.path.join(os.getcwd(), path) def",
"js = get_file_contents(input_path) py_code = translate_js(js) lib_name = os.path.basename(output_path).split('.')[0] head",
"Something like code.InteractiveConsole\"\"\" while True: if six.PY2: code = raw_input('>>>",
"the instance of EvalJs') eval_value = context.eval(get_file_contents(path_or_file)) return eval_value, context",
"amounts of snippets it might increase memory usage. \"\"\" try:",
"behaves like normal python object. If you really want to",
"ctx = EvalJs() >>> ctx.execute('var a = 10;function f(x) {return",
"f: f.write(code) with open(filename, \"r\") as f: pyCode = compile(f.read(),",
"and returns its value as opposed to the (faster) self.execute",
"globals): \"\"\"Imports from javascript source file. globals is your globals()\"\"\"",
"executes and returns python object. js is javascript source code",
"as f: js = f.read() e = EvalJs() e.execute(js) var",
"f.read() e = EvalJs() e.execute(js) var = e.context['var'] globals[lib_name] =",
"at the end so that it is easy to import",
"code = raw_input('>>> ') else: code = input('>>>') try: print(self.eval(code))",
"KeyboardInterrupt: break except Exception as e: import traceback if DEBUG:",
"usage. \"\"\" try: cache = self.__dict__['cache'] except KeyError: cache =",
"return self['PyJsEvalResult'] def eval_js6(self, expression, use_compilation_plan=False): \"\"\"same as eval, except",
"def execute_debug(self, js): \"\"\"executes javascript js in current context as",
"(DEFAULT_HEADER, self._context) self.__dict__['_var'] = self._context['var'].to_python() if enable_require: def _js_require_impl(npm_module_name): from",
"' + str(e) + '\\n') time.sleep(0.01) #print x if __name__",
"e: import traceback if DEBUG: sys.stderr.write(traceback.format_exc()) else: sys.stderr.write('EXCEPTION: ' +",
"#with open('C:\\Users\\Piotrek\\Desktop\\esprima.js', 'rb') as f: # x = f.read() e",
"to actually running the generated python code. Note that the",
"\"\"\"executes javascript js in current context as opposed to the",
"eval_js(js6_to_js5(js)) def translate_js6(js): \"\"\"Just like translate_js but with experimental support",
"console(self): \"\"\"starts to interact (starts interactive console) Something like code.InteractiveConsole\"\"\"",
"\"\"\"Just like eval_js but with experimental support for js6 via",
"'__main__': #with open('C:\\Users\\Piotrek\\Desktop\\esprima.js', 'rb') as f: # x = f.read()",
"\"\"\"evaluates expression in current context and returns its value as",
"\"\"\"Imports from javascript source file. globals is your globals()\"\"\" with",
"to es5 before being executed.\"\"\" es5_expression = js6_to_js5(expression) return self.eval(es5_expression,",
"the generated python code \"\"\" code = 'PyJsEvalResult = eval(%s)'",
"30 You can enable JS require function via enable_require. With",
"code = translate_js( js, '', use_compilation_plan=use_compilation_plan) compiled = cache[hashkey] =",
"EvalJs): raise TypeError('context must be the instance of EvalJs') eval_value",
"var, val) def console(self): \"\"\"starts to interact (starts interactive console)",
"+ py_code + tail write_file_contents(output_path, out) def run_file(path_or_file, context=None): '''",
"translate_js( js, '', use_compilation_plan=use_compilation_plan) compiled = cache[hashkey] = compile(code, '<EvalJS",
"dict): try: context = context.__dict__ except: raise TypeError( 'context has",
"def __setitem__(self, var, val): return setattr(self._var, var, val) def console(self):",
"with: var a = function(x) {return x} translate_file('example.js', 'example.py') Now",
"dicts is updated) but the Js=>Py conversion process is typically",
"var a = function(x) {return x} translate_file('example.js', 'example.py') Now example.py",
"{} exec (DEFAULT_HEADER, self._context) self.__dict__['_var'] = self._context['var'].to_python() if enable_require: def",
"console) Something like code.InteractiveConsole\"\"\" while True: if six.PY2: code =",
"or object that contains python variables that should be available",
"(starts interactive console) Something like code.InteractiveConsole\"\"\" while True: if six.PY2:",
"has no expiration or cleanup so when running this in",
"increase memory usage. \"\"\" try: cache = self.__dict__['cache'] except KeyError:",
"EvalJs() if not isinstance(context, EvalJs): raise TypeError('context must be the",
"with codecs.open(path_as_local(path), \"r\", \"utf-8\") as f: js = f.read() e",
"object. If you really want to convert object to python",
"if enable_require: def _js_require_impl(npm_module_name): from .node_import import require from .base",
"Js=>Py conversion process is typically expensive compared to actually running",
"\"\"\"same as eval, except that the JS code gets translated",
"have a temp folder: filename = 'temp' + os.sep +",
"translate_js but with experimental support for js6 via babel.\"\"\" return",
"to the output path. It appends some convenience code at",
"= js6_to_js5(expression) return self.eval(es5_expression, use_compilation_plan) def execute_debug(self, js): \"\"\"executes javascript",
"of snippets it might increase memory usage. \"\"\" try: cache",
"e = EvalJs() return e.eval(js) def eval_js6(js): \"\"\"Just like eval_js",
".translators import translate_js, DEFAULT_HEADER from .es6 import js6_to_js5 import sys",
"setattr(self._var, var, val) def console(self): \"\"\"starts to interact (starts interactive",
"return os.path.join(os.getcwd(), path) def import_js(path, lib_name, globals): \"\"\"Imports from javascript",
"other base types returns appropriate python BUILTIN type. For Js",
"in automated situations with vast amounts of snippets it might",
"def path_as_local(path): if os.path.isabs(path): return path # relative to cwd",
"30 ''' js = get_file_contents(input_path) py_code = translate_js(js) lib_name =",
"@property def context(self): return self._context def __getattr__(self, var): return getattr(self._var,",
"in six.iteritems(context): setattr(self._var, k, v) def execute(self, js=None, use_compilation_plan=False): \"\"\"executes",
"as f: pyCode = compile(f.read(), filename, 'exec') exec(pyCode, self._context) except",
"] DEBUG = False def disable_pyimport(): import pyjsparser.parser pyjsparser.parser.ENABLE_PYIMPORT =",
"var): return getattr(self._var, var) def __getitem__(self, var): return getattr(self._var, var)",
"\"r\", \"utf-8\") as f: js = f.read() return js def",
"when running this in automated situations with vast amounts of",
"= var.to_python() def get_file_contents(path_or_file): if hasattr(path_or_file, 'read'): js = path_or_file.read()",
"you can use your regular debugger to set breakpoints and",
"in current context and returns its value as opposed to",
"dict or have __dict__ attr') for k, v in six.iteritems(context):",
"python variables that should be available to JavaScript For example:",
"es5 before being executed.\"\"\" es5_expression = js6_to_js5(expression) return self.eval(es5_expression, use_compilation_plan)",
">>> ctx.f(9) 81 >>> ctx.a 10 context is a python",
"'read'): js = path_or_file.read() else: with codecs.open(path_as_local(path_or_file), \"r\", \"utf-8\") as",
"isinstance(context, EvalJs): raise TypeError('context must be the instance of EvalJs')",
"py_code = translate_js(js) lib_name = os.path.basename(output_path).split('.')[0] head = '__all__ =",
".base import to_python return require(to_python(npm_module_name), context=self._context) setattr(self._var, 'require', _js_require_impl) if",
"means next time you run the same javascript snippet you",
"overhead (a cache dicts is updated) but the Js=>Py conversion",
"code \"\"\" code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute_debug(code)",
"path) def import_js(path, lib_name, globals): \"\"\"Imports from javascript source file.",
"object to python dict you can use to_dict method. \"\"\"",
"support for js6 via babel.\"\"\" return translate_js(js6_to_js5(js)) class EvalJs(object): \"\"\"This",
"def disable_pyimport(): import pyjsparser.parser pyjsparser.parser.ENABLE_PYIMPORT = False def path_as_local(path): if",
"python and saves the it to the output path. It",
"Translates javascript to python, executes and returns python object. js",
"def _js_require_impl(npm_module_name): from .node_import import require from .base import to_python",
"EvalJs() >>> ctx.execute('var a = 10;function f(x) {return x*x};') >>>",
"javascript js in current context During initial execute() the converted",
"updated) but the Js=>Py conversion process is typically expensive compared",
"es6 to es5 before being executed.\"\"\" es5_expression = js6_to_js5(expression) return",
"might increase memory usage. \"\"\" try: cache = self.__dict__['cache'] except",
"= EvalJs() if not isinstance(context, EvalJs): raise TypeError('context must be",
"translate_js(js, '') # make sure you have a temp folder:",
"# x = f.read() e = EvalJs() e.execute('square(x)') #e.execute(x) e.console()",
"String, Boolean and other base types returns appropriate python BUILTIN",
"path_or_file.write(contents) else: with open(path_as_local(path_or_file), 'w') as f: f.write(contents) def translate_file(input_path,",
"else: with open(path_as_local(path_or_file), 'w') as f: f.write(contents) def translate_file(input_path, output_path):",
"= self.__dict__['cache'] except KeyError: cache = self.__dict__['cache'] = {} hashkey",
"') else: code = input('>>>') try: print(self.eval(code)) except KeyboardInterrupt: break",
"use_compilation_plan) def execute_debug(self, js): \"\"\"executes javascript js in current context",
"javascript js in current context as opposed to the (faster)",
"traceback if DEBUG: sys.stderr.write(traceback.format_exc()) else: sys.stderr.write('EXCEPTION: ' + str(e) +",
"\"\"\"This class supports continuous execution of javascript under same context.",
"= {} exec (DEFAULT_HEADER, self._context) self.__dict__['_var'] = self._context['var'].to_python() if enable_require:",
"'exec') exec (compiled, self._context) def eval(self, expression, use_compilation_plan=False): \"\"\"evaluates expression",
"like code.InteractiveConsole\"\"\" while True: if six.PY2: code = raw_input('>>> ')",
"can run interactive javascript console with console method!\"\"\" def __init__(self,",
"= compile(code, '<EvalJS snippet>', 'exec') exec (compiled, self._context) def eval(self,",
"add(a, b) {return a + b}') >>> add(1, 2) +",
"repr( lib_name) tail = '\\n\\n# Add lib to the module",
"dict, it has no expiration or cleanup so when running",
"For example: >>> ctx = EvalJs({'a': 30}) >>> ctx.execute('var x",
"easy to import JS objects. For example we have a",
"'eval_js6', 'translate_js6', 'run_file', 'disable_pyimport', 'get_file_contents', 'write_file_contents' ] DEBUG = False",
"as f: # x = f.read() e = EvalJs() e.execute('square(x)')",
"code. This cache causes minor overhead (a cache dicts is",
"= False def disable_pyimport(): import pyjsparser.parser pyjsparser.parser.ENABLE_PYIMPORT = False def",
"scope\\n%s = var.to_python()' % lib_name out = head + py_code",
">>> ctx = EvalJs({'a': 30}) >>> ctx.execute('var x = a')",
"f: pyCode = compile(f.read(), filename, 'exec') exec(pyCode, self._context) except Exception",
"translate_file('example.js', 'example.py') Now example.py can be easily importend and used:",
"js = f.read() e = EvalJs() e.execute(js) var = e.context['var']",
"lib_name out = head + py_code + tail write_file_contents(output_path, out)",
"code EXAMPLE: >>> import js2py >>> add = js2py.eval_js('function add(a,",
"snippet>', 'exec') exec (compiled, self._context) def eval(self, expression, use_compilation_plan=False): \"\"\"evaluates",
"'example.py') Now example.py can be easily importend and used: >>>",
"so that it is easy to import JS objects. For",
"instance of EvalJs') eval_value = context.eval(get_file_contents(path_or_file)) return eval_value, context def",
"object that contains python variables that should be available to",
"getattr(self._var, var) def __getitem__(self, var): return getattr(self._var, var) def __setattr__(self,",
"enable_require: def _js_require_impl(npm_module_name): from .node_import import require from .base import",
"raise err finally: os.remove(filename) try: os.remove(filename + 'c') except: pass",
"os.path.isabs(path): return path # relative to cwd return os.path.join(os.getcwd(), path)",
"b) {return a + b}') >>> add(1, 2) + 3",
"EvalJs({'a': 30}) >>> ctx.execute('var x = a') >>> ctx.x 30",
"js=None, use_compilation_plan=False): \"\"\"executes javascript js in current context During initial",
"except KeyError: code = translate_js( js, '', use_compilation_plan=use_compilation_plan) compiled =",
"to the (faster) self.execute method, you can use your regular",
"minor overhead (a cache dicts is updated) but the Js=>Py",
"add.constructor function Function() { [python code] } NOTE: For Js",
"base types returns appropriate python BUILTIN type. For Js functions",
"its value\"\"\" code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute(code,",
"look below, you will not understand this Python code :)",
"Exception as e: import traceback if DEBUG: sys.stderr.write(traceback.format_exc()) else: sys.stderr.write('EXCEPTION:",
"'disable_pyimport', 'get_file_contents', 'write_file_contents' ] DEBUG = False def disable_pyimport(): import",
"and other base types returns appropriate python BUILTIN type. For",
"'example.js' with: var a = function(x) {return x} translate_file('example.js', 'example.py')",
"like translate_js but with experimental support for js6 via babel.\"\"\"",
"esprima = require('esprima');\") >>> ctx.execute(\"esprima.parse('var a = 1')\") You can",
"but the Js=>Py conversion process is typically expensive compared to",
"''' Translates input JS file to python and saves the",
"translated from es6 to es5 before being executed.\"\"\" es5_expression =",
"import example >>> example.a(30) 30 ''' js = get_file_contents(input_path) py_code",
"js def write_file_contents(path_or_file, contents): if hasattr(path_or_file, 'write'): path_or_file.write(contents) else: with",
"contains python variables that should be available to JavaScript For",
"= var.to_python()' % lib_name out = head + py_code +",
"code] } NOTE: For Js Number, String, Boolean and other",
"object. js is javascript source code EXAMPLE: >>> import js2py",
"codecs.open(path_as_local(path), \"r\", \"utf-8\") as f: js = f.read() e =",
"returns python object. js is javascript source code EXAMPLE: >>>",
"context={}, enable_require=False): self.__dict__['_context'] = {} exec (DEFAULT_HEADER, self._context) self.__dict__['_var'] =",
"__dict__ attr') for k, v in six.iteritems(context): setattr(self._var, k, v)",
"globals[lib_name] = var.to_python() def get_file_contents(path_or_file): if hasattr(path_or_file, 'read'): js =",
"code = translate_js(js, '') # make sure you have a",
"with open(filename, mode='w') as f: f.write(code) with open(filename, \"r\") as",
"converted js is cached for re-use. That means next time",
"path. It appends some convenience code at the end so"
] |
[
"package_dir = { '': 'src' }, packages = find_packages( where='src'",
"setup( package_dir = { '': 'src' }, packages = find_packages(",
"import setup, find_packages setup( package_dir = { '': 'src' },",
"setup, find_packages setup( package_dir = { '': 'src' }, packages",
"#!/usr/bin/python3 from setuptools import setup, find_packages setup( package_dir = {",
"from setuptools import setup, find_packages setup( package_dir = { '':",
"find_packages setup( package_dir = { '': 'src' }, packages =",
"= { '': 'src' }, packages = find_packages( where='src' ),",
"setuptools import setup, find_packages setup( package_dir = { '': 'src'",
"{ '': 'src' }, packages = find_packages( where='src' ), )"
] |
[
"size.\" \\ \" total_blocks: {}\".format(self.partition_size, image.total_blocks) adjusted_size = self.verity_image_builder.CalculateMaxImageSize() assert",
"\"Calculated salt {} doesn't match the one in metadata {}\".format(",
"common.MakeTempDir(suffix=\"_verity_images\") # Get partial image paths. verity_image_path = os.path.join(tempdir_name, \"verity.img\")",
"2.0 (the \"License\"); # you may not use this file",
"# The salt should be always identical, as we use",
"signer_path, signer_key, signer_args, verity_disable): self.version = 1 self.partition_size = partition_size",
"salt\" assert len(table_entries) == 10, \"Unexpected verity table size {}\".format(",
"'', 'verity_signer_cmd': None, } self.verity_image_builder = CreateVerityImageBuilder(prop_dict) self.hashtree_info = HashtreeInfo()",
"verity tree\") return self.hashtree_info def CreateCustomImageBuilder(info_dict, partition_name, partition_size, key_path, algorithm,",
"one in metadata %s\", root_hash, self.hashtree_info.root_hash) return False # Reads",
"Version1VerityImageBuilder( partition_size, prop_dict[\"verity_block_device\"], prop_dict.get(\"verity_fec\") == \"true\", signer_path, prop_dict[\"verity_key\"] + \".pk8\",",
"section to a temp file; and calls the executable #",
"out_file): # No-op as the padding is taken care of",
"\"\"\" try: with open(target, 'ab') as out_file, \\ open(file_to_append, 'rb')",
"'', # We don't need the following properties that are",
"metadata. Args: partition_size: The partition size, which defaults to self.partition_size",
"out_file, verity_image_path, \"Failed to append verity data\") def PadSparseImage(self, out_file):",
"out_file): \"\"\"Creates an image that is verifiable using dm-verity. Args:",
"the full verified image. Append( verity_image_path, verity_metadata_path, \"Failed to append",
"hi = mid else: lo = mid + BLOCK_SIZE logger.info(",
"= pad_size // BLOCK_SIZE logger.info(\"Padding %d blocks (%d bytes)\", blocks,",
"header[0] == 0xb001b001, header[0] table_len = header[3] verity_table = meta_data[META_HEADER_SIZE:",
"assert len(table_entries) == 10, \"Unexpected verity table size {}\".format( len(table_entries))",
"an image. Args: out_file: Path to image to modify. \"\"\"",
"268 header_bin = meta_data[0:META_HEADER_SIZE] header = struct.unpack(\"II256sI\", header_bin) # header:",
"header[3] verity_table = meta_data[META_HEADER_SIZE: META_HEADER_SIZE + table_len] table_entries = verity_table.rstrip().split()",
"builder that generates an image with verity metadata for Verified",
"0: raise BuildVerityImageError( \"Failed to calculate max image size:\\n{}\".format(output)) image_size",
"prop_dict[\"verity_signer_cmd\"] return Version1VerityImageBuilder( partition_size, prop_dict[\"verity_block_device\"], prop_dict.get(\"verity_fec\") == \"true\", signer_path, prop_dict[\"verity_key\"]",
"Generate(self, image): raise NotImplementedError def DecomposeSparseImage(self, image): raise NotImplementedError def",
"determining the partition size for a dynamic partition, which should",
"VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hashtree_footer_args\"]) return None class VerityImageBuilder(object):",
"= self.verity_image_builder.CalculateMaxImageSize() assert adjusted_size % self.block_size == 0 verity_tree_size =",
"bytes of a partition, including the filesystem size, padding size,",
"dm-verity. Args: out_file: the output image. Returns: AssertionError: On invalid",
"the sparse image and input property. Arguments: partition_size: The whole",
"root_hash, salt = BuildVerityTree(adjusted_partition, generated_verity_tree) # The salt should be",
"verity size. block_size: Expected size in bytes of each block",
"(' '.join(signer_args),)) if verity_disable: cmd.append(\"--verity_disable\") common.RunAndCheckOutput(cmd) def Append2Simg(sparse_image_path, unsparse_image_path, error_message):",
"should be always identical, as we use fixed value. assert",
"def GetVerityTreeSize(image_size): cmd = [\"build_verity_tree\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd,",
"will look for verity-related property values. Returns: A VerityImageBuilder instance",
"> image_size: image_ratio = max_image_size / float(lo) lo = int(image_size",
"be implemented. Note that returning the given image size as",
"# limitations under the License. from __future__ import print_function import",
"proc = common.Run(cmd) output, _ = proc.communicate() if proc.returncode !=",
"PadSparseImage(self, out_file): sparse_image_size = GetSimgSize(out_file) if sparse_image_size > self.image_size: raise",
"well as the verity metadata size. Args: image_size: The size",
"hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE v = GetVeritySize(i,",
"META_HEADER_SIZE + table_len] table_entries = verity_table.rstrip().split() # Expected verity table",
"Salt is None because custom images have no fingerprint property",
"\"\"\"A builder that generates an image with verity metadata for",
"total_blocks: {}\".format(self.partition_size, image.total_blocks) adjusted_size = self.verity_image_builder.CalculateMaxImageSize() assert adjusted_size % self.block_size",
"image size of {} is larger than partition size of",
"= meta_data[0:META_HEADER_SIZE] header = struct.unpack(\"II256sI\", header_bin) # header: magic_number, version,",
"License for the specific language governing permissions and # limitations",
"try: common.RunAndCheckOutput(cmd) except: logger.exception(error_message) raise BuildVerityImageError(error_message) def Append(target, file_to_append, error_message):",
"for the sparse image. fec_supported: True if the verity section",
"* BLOCK_SIZE # verity tree and fec sizes depend on",
"\"\"\" image_size = int(self.image_size) tempdir_name = common.MakeTempDir(suffix=\"_verity_images\") # Get partial",
"is_verity_partition: if OPTIONS.verity_signer_path is not None: signer_path = OPTIONS.verity_signer_path else:",
"VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator): \"\"\"A class that parses the metadata of hashtree for",
"out_file): \"\"\"Adds padding to the generated sparse image.\"\"\" raise NotImplementedError",
"hi # Start to binary search. while lo < hi:",
"= partition_size - verity_size result = lo # do a",
"self.salt]) cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output, _ = proc.communicate() if",
"raise NotImplementedError def CalculateDynamicPartitionSize(self, image_size): \"\"\"Calculates and sets the partition",
"table_entries[9].decode() def ValidateHashtree(self): \"\"\"Checks that we can reconstruct the verity",
"= metadata_size self.hashtree_info.filesystem_range = RangeSet( data=[0, adjusted_size // self.block_size]) self.hashtree_info.hashtree_range",
"raise BuildVerityImageError(error_message) def Append(target, file_to_append, error_message): \"\"\"Appends file_to_append to target.",
"Raises: BuildVerityImageError: On error. \"\"\" try: with open(target, 'ab') as",
"metadata. verity_fec_path = os.path.join(tempdir_name, \"verity_fec.img\") BuildVerityFEC( out_file, verity_image_path, verity_fec_path, padding_size)",
"max_image_size / float(hi) hi = int(image_size / image_ratio) // BLOCK_SIZE",
"Version1VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot 1.0.\"\"\" def __init__(self, partition_size,",
"Writes the filesystem section to a temp file; and calls",
"generation can be found at the following link. https://source.android.com/security/verifiedboot/dm-verity#implementation \"\"\"",
"prop_dict[\"avb_add_hash_footer_args\"]) # Image uses hashtree footer. return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size,",
"Generate(self, image): \"\"\"Parses and validates the hashtree info in a",
"the hashtree. Raises: HashtreeInfoGenerationError: If we fail to generate the",
"verity_image_path) # Build the metadata blocks. BuildVerityMetadata( image_size, verity_metadata_path, root_hash,",
"partition size for a dynamic partition.\"\"\" raise NotImplementedError def PadSparseImage(self,",
"else: hi = i self.image_size = result self.verity_size = verity_size",
"\"verity.img\") verity_metadata_path = os.path.join(tempdir_name, \"verity_metadata.img\") # Build the verity tree",
"Start to binary search. while lo < hi: mid =",
"hashtree info in a sparse image. Returns: hashtree_info: The information",
"avbtool self.algorithm = algorithm self.key_path = key_path self.salt = salt",
"None because custom images have no fingerprint property to be",
"with open(target, 'ab') as out_file, \\ open(file_to_append, 'rb') as input_file:",
"/ image_ratio) // BLOCK_SIZE * BLOCK_SIZE - delta delta *=",
"Boot 2.0; or None if the given build doesn't support",
"0 verity_tree_size = GetVerityTreeSize(adjusted_size) assert verity_tree_size % self.block_size == 0",
"= b''.join(self.image.ReadRangeSet(metadata_range)) # More info about the metadata structure available",
"= [\"append2simg\", sparse_image_path, unsparse_image_path] try: common.RunAndCheckOutput(cmd) except: logger.exception(error_message) raise BuildVerityImageError(error_message)",
"Verified Boot 1.0 or Verified Boot 2.0; or None if",
"block_device, signer_path, key, signer_args, verity_disable): cmd = [\"build_verity_metadata\", \"build\", str(image_size),",
"if partition_size: partition_size = int(partition_size) # Verified Boot 1.0 verity_supported",
"i: result = i verity_size = v lo = i",
"exact same bytes # as the one in the sparse",
"verity metadata. \"\"\" if partition_size is None: partition_size = self.partition_size",
"the verity tree\") return self.hashtree_info def CreateCustomImageBuilder(info_dict, partition_name, partition_size, key_path,",
"padding size, and verity size. block_size: Expected size in bytes",
"Build(self, out_file): \"\"\"Creates an image that is verifiable using dm-verity.",
"verity table format: \"1 block_device block_device block_size # block_size data_blocks",
"sparse image. Returns: hashtree_info: The information needed to reconstruct the",
"max_image_size = size_calculator(lo) hi = lo + BLOCK_SIZE # Ensure",
"a verity-enabled # partition. 'verity_block_device': '', # We don't need",
"Build FEC for the entire partition, including metadata. verity_fec_path =",
"in bytes of a partition, including the filesystem size, padding",
"and # limitations under the License. from __future__ import print_function",
"* BLOCK_SIZE v = GetVeritySize(i, self.fec_supported) if i + v",
"CalculateDynamicPartitionSize(self, image_size): # This needs to be implemented. Note that",
"small enough: max_image_size should <= image_size. delta = BLOCK_SIZE max_image_size",
"# Ensure hi is large enough: max_image_size should >= image_size.",
"lo < hi: mid = ((lo + hi) // (2",
"Build(self, out_file): \"\"\"Adds dm-verity hashtree and AVB metadata to an",
"message) class HashtreeInfo(object): def __init__(self): self.hashtree_range = None self.filesystem_range =",
"def Build(self, out_file): \"\"\"Builds the verity image and writes it",
"\"\"\"A VerityImageBuilder for Verified Boot 1.0.\"\"\" def __init__(self, partition_size, block_dev,",
"Raises: HashtreeInfoGenerationError: If we fail to generate the exact bytes",
"common interface between Verified Boot 1.0 and Verified Boot 2.0.",
"OF ANY KIND, either express or implied. # See the",
"self.fec_supported) lo = partition_size - verity_size result = lo #",
"metadata size. Args: image_size: The size of the image in",
"See the License for the specific language governing permissions and",
"path to the (sparse) image unsparse_image_path: the path to the",
"def __init__(self, partition_name, partition_size, footer_type, avbtool, key_path, algorithm, salt, signing_args):",
"def PadSparseImage(self, out_file): sparse_image_size = GetSimgSize(out_file) if sparse_image_size > self.image_size:",
"know the structure of a verity enabled image to be:",
"image size for verity: partition_size %d, image_size %d, \" \"verity_size",
"common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVeritySize(image_size, fec_supported): verity_tree_size = GetVerityTreeSize(image_size)",
"image. Returns: hashtree_info: The information needed to reconstruct the hashtree.",
"to in writing, software # distributed under the License is",
"instance handles the works for building an image with verity",
"[filesystem, verity_hashtree, verity_metadata, fec_data]. We can then calculate the size",
"of hashtree for a given partition.\"\"\" def __init__(self, partition_size, block_size,",
"More info about the metadata structure available in: # system/extras/verity/build_verity_metadata.py",
"needed to reconstruct the hashtree. Raises: HashtreeInfoGenerationError: If we fail",
"the generated sparse image.\"\"\" raise NotImplementedError def Build(self, out_file): \"\"\"Builds",
"def CalculateDynamicPartitionSize(self, image_size): self.partition_size = self.CalculateMinPartitionSize(image_size) return self.partition_size def CalculateMaxImageSize(self,",
"or agreed to in writing, software # distributed under the",
"partition_name, partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get(\"avb_avbtool\"), key_path, algorithm, # Salt is None",
"Returns: AssertionError: On invalid partition sizes. BuildVerityImageError: On other errors.",
"BLOCK_SIZE # Ensure lo is small enough: max_image_size should <=",
"== self.filesystem_size) self.hashtree_info.hash_algorithm = table_entries[7].decode() self.hashtree_info.root_hash = table_entries[8].decode() self.hashtree_info.salt =",
"lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE -",
"self.filesystem_size) self.hashtree_info.hash_algorithm = table_entries[7].decode() self.hashtree_info.root_hash = table_entries[8].decode() self.hashtree_info.salt = table_entries[9].decode()",
"BLOCK_SIZE v = GetVeritySize(i, self.fec_supported) if i + v <=",
"version, signature, table_len assert header[0] == 0xb001b001, header[0] table_len =",
"info generation.\"\"\" def __init__(self, message): Exception.__init__(self, message) class HashtreeInfo(object): def",
"(info_dict.get(\"verity\") == \"true\" and info_dict.get(\"{}_verity_block_device\".format(partition_name))): partition_size = info_dict[\"{}_size\".format(partition_name)] fec_supported =",
"to be unnecessarily small verity_size = GetVeritySize(hi, self.fec_supported) lo =",
"+ delta delta *= 2 max_image_size = size_calculator(hi) partition_size =",
"root_hash, salt from the metadata block.\"\"\" metadata_start = self.filesystem_size +",
"return int(output) def GetVerityMetadataSize(image_size): cmd = [\"build_verity_metadata\", \"size\", str(image_size)] output",
"compliance with the License. # You may obtain a copy",
"doesn't match with the calculated image size.\" \\ \" total_blocks:",
"class BuildVerityImageError(Exception): \"\"\"An Exception raised during verity image building.\"\"\" def",
"verity_metadata_path, root_hash, salt, self.block_device, self.signer_path, self.signer_key, self.signer_args, self.verity_disable) padding_size =",
"to an image. Args: out_file: Path to image to modify.",
"self.image_size: raise BuildVerityImageError( \"Error: image size of {} is larger",
"size of the image in question. size_calculator: The function to",
"self.block_device, self.signer_path, self.signer_key, self.signer_args, self.verity_disable) padding_size = self.partition_size - self.image_size",
"Append2Simg( out_file, verity_image_path, \"Failed to append verity data\") def PadSparseImage(self,",
"Source Project # # Licensed under the Apache License, Version",
"to calculate max image size for a given partition size.",
"partial image paths. verity_image_path = os.path.join(tempdir_name, \"verity.img\") verity_metadata_path = os.path.join(tempdir_name,",
"image_ratio) // BLOCK_SIZE * BLOCK_SIZE - delta delta *= 2",
"= prop_dict.get(\"avb_key_path\") algorithm = prop_dict.get(\"avb_algorithm\") # Image uses hash footer.",
"We can then calculate the size and offset of each",
"and int(table_entries[6]) * self.block_size == self.filesystem_size) self.hashtree_info.hash_algorithm = table_entries[7].decode() self.hashtree_info.root_hash",
"Use image size as partition size to approximate final partition",
"hashtree and AVB metadata to an image. Args: out_file: Path",
"\"--partition_size\", str(self.partition_size), \"--partition_name\", self.partition_name, \"--image\", out_file] if self.key_path and self.algorithm:",
"key_path, algorithm, signing_args): builder = None if info_dict.get(\"avb_enable\") == \"true\":",
"block_device, signer_path, key] if signer_args: cmd.append(\"--signer_args=\\\"%s\\\"\" % (' '.join(signer_args),)) if",
"if a smaller partition size is found partition_size = mid",
"dm-verity hashtree and AVB metadata to an image. Args: out_file:",
"image.total_blocks) adjusted_size = self.verity_image_builder.CalculateMaxImageSize() assert adjusted_size % self.block_size == 0",
"not use this file except in compliance with the License.",
"partition_size, prop_dict[\"verity_block_device\"], prop_dict.get(\"verity_fec\") == \"true\", signer_path, prop_dict[\"verity_key\"] + \".pk8\", OPTIONS.verity_signer_args,",
"self.partition_size assert partition_size > 0, \\ \"Invalid partition size: {}\".format(partition_size)",
"exact bytes of the hashtree. \"\"\" self.DecomposeSparseImage(image) self._ParseHashtreeMetadata() if not",
"of each block for the sparse image. fec_supported: True if",
"as out_file, \\ open(file_to_append, 'rb') as input_file: for line in",
"the sparse image. with open(generated_verity_tree, 'rb') as fd: return fd.read()",
"with the calculated image size.\" \\ \" total_blocks: {}\".format(self.partition_size, image.total_blocks)",
"accounting for the verity metadata. Args: partition_size: The partition size,",
"section contains fec data. \"\"\" self.block_size = block_size self.partition_size =",
"you may not use this file except in compliance with",
"simg = sparse_img.SparseImage(image_file, mode=\"r+b\", build_map=False) simg.AppendFillChunk(0, blocks) def BuildVerityFEC(sparse_image_path, verity_path,",
"meta_data = b''.join(self.image.ReadRangeSet(metadata_range)) # More info about the metadata structure",
"import RangeSet logger = logging.getLogger(__name__) OPTIONS = common.OPTIONS BLOCK_SIZE =",
"the given file.\"\"\" raise NotImplementedError class Version1VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for",
"verity_tree_size) // self.block_size]) def _ParseHashtreeMetadata(self): \"\"\"Parses the hash_algorithm, root_hash, salt",
"self.image = image assert self.block_size == image.blocksize assert self.partition_size ==",
"cmd = [\"append2simg\", sparse_image_path, unsparse_image_path] try: common.RunAndCheckOutput(cmd) except: logger.exception(error_message) raise",
"in a sparse image. Returns: hashtree_info: The information needed to",
"partition_size self.block_device = block_dev self.fec_supported = fec_supported self.signer_path = signer_path",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"== \"true\": return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm,",
"Exception raised during hashtree info generation.\"\"\" def __init__(self, message): Exception.__init__(self,",
"\"\"\" self.block_size = block_size self.partition_size = partition_size self.fec_supported = fec_supported",
"None if (info_dict.get(\"verity\") == \"true\" and info_dict.get(\"{}_verity_block_device\".format(partition_name))): partition_size = info_dict[\"{}_size\".format(partition_name)]",
"verity_fec_path, padding_size) Append(verity_image_path, verity_fec_path, \"Failed to append FEC\") Append2Simg( out_file,",
"image in question. size_calculator: The function to calculate max image",
"\"Calculated image size for verity: partition_size %d, image_size %d, \"",
"hi: mid = ((lo + hi) // (2 * BLOCK_SIZE))",
"delta *= 2 max_image_size = size_calculator(hi) partition_size = hi #",
"size for a given image size. This is used when",
"self.metadata_size = metadata_size self.hashtree_info.filesystem_range = RangeSet( data=[0, adjusted_size // self.block_size])",
"+ hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE v =",
"the generated hash tree and checks if it has the",
"max_image_size > image_size: image_ratio = max_image_size / float(lo) lo =",
"\"true\" is_verity_partition = \"verity_block_device\" in prop_dict if verity_supported and is_verity_partition:",
"the filesystem size, padding size, and verity size. block_size: Expected",
"== image.blocksize assert self.partition_size == image.total_blocks * self.block_size, \\ \"partition",
"[\"build_verity_metadata\", \"build\", str(image_size), verity_metadata_path, root_hash, salt, block_device, signer_path, key] if",
"size as # the partition size doesn't make sense, as",
"as the verity metadata size. Args: image_size: The size of",
"* self.block_size == self.filesystem_size and int(table_entries[6]) * self.block_size == self.filesystem_size)",
"{} doesn't match the one in metadata {}\".format( salt, self.hashtree_info.salt)",
"block_size, info_dict): generator = None if (info_dict.get(\"verity\") == \"true\" and",
"we already know the structure of a verity enabled image",
"handles the works for building an image with verity metadata",
"\\ \"Invalid partition size: {}\".format(partition_size) hi = partition_size if hi",
"image size for a given partition size. Returns: The minimum",
"prop_dict.get(\"avb_key_path\") algorithm = prop_dict.get(\"avb_algorithm\") # Image uses hash footer. if",
"{}\".format(partition_size) hi = partition_size if hi % BLOCK_SIZE != 0:",
"file; and calls the executable # build_verity_tree to construct the",
"= GetVeritySize(i, self.fec_supported) if i + v <= partition_size: if",
"result def Build(self, out_file): \"\"\"Creates an image that is verifiable",
"key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hash_footer_args\"]) # Image uses hashtree footer. return",
"partition is used. key_path = prop_dict.get(\"avb_key_path\") algorithm = prop_dict.get(\"avb_algorithm\") #",
"Image uses hashtree footer. return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict[\"avb_avbtool\"],",
"accommodate the image size. \"\"\" if size_calculator is None: size_calculator",
"hi: i = ((lo + hi) // (2 * BLOCK_SIZE))",
"max_image_size should >= image_size. delta = BLOCK_SIZE max_image_size = size_calculator(hi)",
"partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get(\"avb_avbtool\"), key_path, algorithm, # Salt is None because",
"# Use image size as partition size to approximate final",
"blocks = pad_size // BLOCK_SIZE logger.info(\"Padding %d blocks (%d bytes)\",",
"contains fec data. \"\"\" self.block_size = block_size self.partition_size = partition_size",
"each block for the sparse image. fec_supported: True if the",
"self.signer_path = signer_path self.signer_key = signer_key self.signer_args = signer_args self.verity_disable",
"is used when determining the partition size for a dynamic",
"raise BuildVerityImageError( \"Failed to calculate max image size:\\n{}\".format(output)) image_size =",
"no fingerprint property to be # used as the salt.",
"= prop_dict.get(\"partition_size\") # partition_size could be None at this point,",
"message) def GetVerityFECSize(image_size): cmd = [\"fec\", \"-s\", str(image_size)] output =",
"// BLOCK_SIZE * BLOCK_SIZE - delta delta *= 2 max_image_size",
"max_image_size should <= image_size. delta = BLOCK_SIZE max_image_size = size_calculator(lo)",
"hash tree.\"\"\" # Writes the filesystem section to a temp",
"to construct the hash tree. adjusted_partition = common.MakeTempFile(prefix=\"adjusted_partition\") with open(adjusted_partition,",
"1.0 or Verified Boot 2.0; or None if the given",
"image. Args: out_file: Path to image to modify. \"\"\" add_footer",
"int(output) def GetVeritySize(image_size, fec_supported): verity_tree_size = GetVerityTreeSize(image_size) verity_metadata_size = GetVerityMetadataSize(image_size)",
"while lo < hi: mid = ((lo + hi) //",
"sparse image and input property. Arguments: partition_size: The whole size",
"self.version = 1 self.partition_size = partition_size self.block_device = block_dev self.fec_supported",
"defaults to self.partition_size if unspecified. Returns: The maximum image size.",
"the verity metadata size. Args: image_size: The size of the",
"verity_hashtree, verity_metadata, fec_data]. We can then calculate the size and",
"if fec_supported: fec_size = GetVerityFECSize(image_size + verity_size) return verity_size +",
"if unspecified. Returns: The maximum image size. Raises: BuildVerityImageError: On",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"property values. Returns: A VerityImageBuilder instance for Verified Boot 1.0",
"= RangeSet( data=[adjusted_size // self.block_size, (adjusted_size + verity_tree_size) // self.block_size])",
"def Generate(self, image): raise NotImplementedError def DecomposeSparseImage(self, image): raise NotImplementedError",
"the metadata structure available in: # system/extras/verity/build_verity_metadata.py META_HEADER_SIZE = 268",
"= 2 def __init__(self, partition_name, partition_size, footer_type, avbtool, key_path, algorithm,",
"self.algorithm: cmd.extend([\"--key\", self.key_path, \"--algorithm\", self.algorithm]) if self.salt: cmd.extend([\"--salt\", self.salt]) cmd.extend(shlex.split(self.signing_args))",
"META_HEADER_SIZE = 268 header_bin = meta_data[0:META_HEADER_SIZE] header = struct.unpack(\"II256sI\", header_bin)",
"of a verity enabled image to be: [filesystem, verity_hashtree, verity_metadata,",
"the image in question. size_calculator: The function to calculate max",
"def ZeroPadSimg(image_file, pad_size): blocks = pad_size // BLOCK_SIZE logger.info(\"Padding %d",
"Args: partition_size: The partition size, which defaults to self.partition_size if",
"salt, block_device, signer_path, key] if signer_args: cmd.append(\"--signer_args=\\\"%s\\\"\" % (' '.join(signer_args),))",
"More info on the verity image generation can be found",
"self.block_device = block_dev self.fec_supported = fec_supported self.signer_path = signer_path self.signer_key",
"already know the structure of a verity enabled image to",
"other errors. \"\"\" image_size = int(self.image_size) tempdir_name = common.MakeTempDir(suffix=\"_verity_images\") #",
"that we can reconstruct the verity hash tree.\"\"\" # Writes",
"= header[3] verity_table = meta_data[META_HEADER_SIZE: META_HEADER_SIZE + table_len] table_entries =",
"# Ensure lo is small enough: max_image_size should <= image_size.",
"Note that returning the given image size as # the",
"= fec_supported self.signer_path = signer_path self.signer_key = signer_key self.signer_args =",
"self.image_size)) ZeroPadSimg(out_file, self.image_size - sparse_image_size) class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for",
"CalculateMaxImageSize(self, partition_size): \"\"\"Calculates the filesystem image size for the given",
"cmd = [\"build_verity_metadata\", \"size\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return",
"< hi: i = ((lo + hi) // (2 *",
"def __init__(self): self.hashtree_range = None self.filesystem_range = None self.hash_algorithm =",
"file except in compliance with the License. # You may",
"if the verity section contains fec data. \"\"\" self.block_size =",
"In particular, it will look for verity-related property values. Returns:",
"self.hashtree_info.salt) if root_hash != self.hashtree_info.root_hash: logger.warning( \"Calculated root hash %s",
"+ BLOCK_SIZE # Ensure hi is large enough: max_image_size should",
"GetSimgSize(image_file): simg = sparse_img.SparseImage(image_file, build_map=False) return simg.blocksize * simg.total_blocks def",
"generated sparse image.\"\"\" raise NotImplementedError def Build(self, out_file): \"\"\"Builds the",
"a verity image builder based on the given build properties.",
"Boot 2.0. A matching builder will be returned based on",
"algorithm, signing_args): builder = None if info_dict.get(\"avb_enable\") == \"true\": builder",
"search. while lo < hi: mid = ((lo + hi)",
"FIXED_SALT = \"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\" class BuildVerityImageError(Exception): \"\"\"An Exception raised during verity",
"unsparse_image_path, error_message): \"\"\"Appends the unsparse image to the given sparse",
"output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVeritySize(image_size, fec_supported): verity_tree_size",
"= None if (info_dict.get(\"verity\") == \"true\" and info_dict.get(\"{}_verity_block_device\".format(partition_name))): partition_size =",
"partition_size could be None at this point, if using dynamic",
"calculated image size.\" \\ \" total_blocks: {}\".format(self.partition_size, image.total_blocks) adjusted_size =",
"tree and checks if it has the exact same bytes",
"from __future__ import print_function import logging import os.path import shlex",
"the metadata block.\"\"\" metadata_start = self.filesystem_size + self.hashtree_size metadata_range =",
"\"\"\"An Exception raised during hashtree info generation.\"\"\" def __init__(self, message):",
"ZeroPadSimg(image_file, pad_size): blocks = pad_size // BLOCK_SIZE logger.info(\"Padding %d blocks",
"= sparse_img.SparseImage(image_file, mode=\"r+b\", build_map=False) simg.AppendFillChunk(0, blocks) def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path,",
"or getting invalid image size. \"\"\" if partition_size is None:",
"as we use fixed value. assert salt == self.hashtree_info.salt, \\",
"has the exact same bytes # as the one in",
"if verity_supported and is_verity_partition: if OPTIONS.verity_signer_path is not None: signer_path",
"(adjusted_size + verity_tree_size) // self.block_size]) def _ParseHashtreeMetadata(self): \"\"\"Parses the hash_algorithm,",
"// BLOCK_SIZE * BLOCK_SIZE + delta delta *= 2 max_image_size",
"Args: sparse_image_path: the path to the (sparse) image unsparse_image_path: the",
"pad_size // BLOCK_SIZE logger.info(\"Padding %d blocks (%d bytes)\", blocks, pad_size)",
"def BuildVerityTree(sparse_image_path, verity_image_path): cmd = [\"build_verity_tree\", \"-A\", FIXED_SALT, sparse_image_path, verity_image_path]",
"the verity tree and get the root hash and salt.",
"KIND, either express or implied. # See the License for",
"partition_size = self.partition_size assert partition_size > 0, \\ \"Invalid partition",
"out_file): sparse_image_size = GetSimgSize(out_file) if sparse_image_size > self.image_size: raise BuildVerityImageError(",
"size:\\n{}\".format(output)) image_size = int(output) if image_size <= 0: raise BuildVerityImageError(",
"is verifiable using dm-verity. Args: out_file: the output image. Returns:",
"info_dict.get(\"{}_verity_block_device\".format(partition_name))): partition_size = info_dict[\"{}_size\".format(partition_name)] fec_supported = info_dict.get(\"verity_fec\") == \"true\" generator",
"or prop_dict.get(\"avb_hashtree_enable\") == \"true\"): # key_path and algorithm are only",
"if self.salt: cmd.extend([\"--salt\", self.salt]) cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output, _",
"should >= image_size. delta = BLOCK_SIZE max_image_size = size_calculator(hi) while",
"the given image size (for filesystem files) as well as",
"/ image_ratio) // BLOCK_SIZE * BLOCK_SIZE + delta delta *=",
"OPTIONS.verity_signer_path else: signer_path = prop_dict[\"verity_signer_cmd\"] return Version1VerityImageBuilder( partition_size, prop_dict[\"verity_block_device\"], prop_dict.get(\"verity_fec\")",
"fd: self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd) generated_verity_tree = common.MakeTempFile(prefix=\"verity\") root_hash, salt = BuildVerityTree(adjusted_partition,",
"image_size): # This needs to be implemented. Note that returning",
"is None: partition_size = self.partition_size assert partition_size > 0, \\",
"algorithm self.key_path = key_path self.salt = salt self.signing_args = signing_args",
"input_file: for line in input_file: out_file.write(line) except IOError: logger.exception(error_message) raise",
"partition_size if hi % BLOCK_SIZE != 0: hi = (hi",
"partition_size - verity_size result = lo # do a binary",
"entire partition, including metadata. verity_fec_path = os.path.join(tempdir_name, \"verity_fec.img\") BuildVerityFEC( out_file,",
"// self.block_size, (metadata_start + self.metadata_size) // self.block_size]) meta_data = b''.join(self.image.ReadRangeSet(metadata_range))",
"(the \"License\"); # you may not use this file except",
"generator class HashtreeInfoGenerator(object): def Generate(self, image): raise NotImplementedError def DecomposeSparseImage(self,",
"raise NotImplementedError class Version1VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot 1.0.\"\"\"",
"= GetSimgSize(out_file) if sparse_image_size > self.image_size: raise BuildVerityImageError( \"Error: image",
"partition_size > 0, \\ \"Invalid partition size: {}\".format(partition_size) hi =",
"+ fec_size return verity_size def GetSimgSize(image_file): simg = sparse_img.SparseImage(image_file, build_map=False)",
"enabled image to be: [filesystem, verity_hashtree, verity_metadata, fec_data]. We can",
"2.0; or None if the given build doesn't support Verified",
"BLOCK_SIZE # Ensure hi is large enough: max_image_size should >=",
"HashtreeInfoGenerator(object): def Generate(self, image): raise NotImplementedError def DecomposeSparseImage(self, image): raise",
"if mid can accommodate image_size if mid < partition_size: #",
"{}\".format(output)) class HashtreeInfoGenerationError(Exception): \"\"\"An Exception raised during hashtree info generation.\"\"\"",
"\"\"\" if size_calculator is None: size_calculator = self.CalculateMaxImageSize # Use",
"= algorithm self.key_path = key_path self.salt = salt self.signing_args =",
"def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path, padding_size): cmd = [\"fec\", \"-e\", \"-p\",",
"= signer_key self.signer_args = signer_args self.verity_disable = verity_disable self.image_size =",
"\" total_blocks: {}\".format(self.partition_size, image.total_blocks) adjusted_size = self.verity_image_builder.CalculateMaxImageSize() assert adjusted_size %",
"in the sparse image. with open(generated_verity_tree, 'rb') as fd: return",
"\"1 block_device block_device block_size # block_size data_blocks data_blocks hash_algorithm root_hash",
"key_path self.salt = salt self.signing_args = signing_args self.image_size = None",
"and int(table_entries[4]) == self.block_size) assert (int(table_entries[5]) * self.block_size == self.filesystem_size",
"str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityTreeSize(image_size): cmd",
"BLOCK_SIZE * BLOCK_SIZE - delta delta *= 2 max_image_size =",
"# # Unless required by applicable law or agreed to",
"partition_size, result, verity_size) return result def Build(self, out_file): \"\"\"Creates an",
"given partition.\"\"\" def __init__(self, partition_size, block_size, fec_supported): \"\"\"Initialize VerityTreeInfo with",
"validates the hashtree info in a sparse image. Returns: hashtree_info:",
"implemented. Note that returning the given image size as #",
"signer_key self.signer_args = signer_args self.verity_disable = verity_disable self.image_size = None",
"size_calculator(image_size) / float(image_size) # Prepare a binary search for the",
"= output.split() return root, salt def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,",
"and offset of each section. \"\"\" self.image = image assert",
"\"Invalid partition size: {}\".format(partition_size) hi = partition_size if hi %",
"image): \"\"\"Calculate the verity size based on the size of",
"tree.\"\"\" # Writes the filesystem section to a temp file;",
"\"\"\"Creates an image that is verifiable using dm-verity. Args: out_file:",
"properties that are needed for signing the # verity metadata.",
"self.partition_name = partition_name self.partition_size = partition_size self.footer_type = footer_type self.avbtool",
"do a binary search for the optimal size while lo",
"GetVerityMetadataSize(image_size) verity_size = verity_tree_size + verity_metadata_size if fec_supported: fec_size =",
"i verity_size = v lo = i + BLOCK_SIZE else:",
"self.partition_size if unspecified. Returns: The maximum image size. Raises: BuildVerityImageError:",
"\"--algorithm\", self.algorithm]) if self.salt: cmd.extend([\"--salt\", self.salt]) cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd)",
"def GetSimgSize(image_file): simg = sparse_img.SparseImage(image_file, build_map=False) return simg.blocksize * simg.total_blocks",
"padding to the generated sparse image.\"\"\" raise NotImplementedError def Build(self,",
"implied. # See the License for the specific language governing",
"CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates the max image size by accounting for",
"CreateCustomImageBuilder(info_dict, partition_name, partition_size, key_path, algorithm, signing_args): builder = None if",
"as partition size to approximate final partition size. image_ratio =",
"as # the partition size doesn't make sense, as it",
"image_size, size_calculator=None): \"\"\"Calculates min partition size for a given image",
"int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE + delta delta",
"signing the # verity metadata. 'verity_key': '', 'verity_signer_cmd': None, }",
"None self.verity_size = None def CalculateDynamicPartitionSize(self, image_size): # This needs",
"= 2 self.partition_name = partition_name self.partition_size = partition_size self.footer_type =",
"fail later. raise NotImplementedError def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates the max",
"self.fec_supported: # Build FEC for the entire partition, including metadata.",
"'.join(signer_args),)) if verity_disable: cmd.append(\"--verity_disable\") common.RunAndCheckOutput(cmd) def Append2Simg(sparse_image_path, unsparse_image_path, error_message): \"\"\"Appends",
"checks if it has the exact same bytes # as",
"if OPTIONS.verity_signer_path is not None: signer_path = OPTIONS.verity_signer_path else: signer_path",
"append verity metadata\") if self.fec_supported: # Build FEC for the",
"= prop_dict.get(\"avb_algorithm\") # Image uses hash footer. if prop_dict.get(\"avb_hash_enable\") ==",
"blocks. BuildVerityMetadata( image_size, verity_metadata_path, root_hash, salt, self.block_device, self.signer_path, self.signer_key, self.signer_args,",
"import logging import os.path import shlex import struct import common",
"\"Unexpected verity table size {}\".format( len(table_entries)) assert (int(table_entries[3]) == self.block_size",
"Arguments: partition_size: The whole size in bytes of a partition,",
"size in bytes of a partition, including the filesystem size,",
"BLOCK_SIZE else: hi = i self.image_size = result self.verity_size =",
"Open Source Project # # Licensed under the Apache License,",
"in: # system/extras/verity/build_verity_metadata.py META_HEADER_SIZE = 268 header_bin = meta_data[0:META_HEADER_SIZE] header",
"self.verity_image_builder.CalculateMaxImageSize() assert adjusted_size % self.block_size == 0 verity_tree_size = GetVerityTreeSize(adjusted_size)",
"- verity_size result = lo # do a binary search",
"self.block_size]) meta_data = b''.join(self.image.ReadRangeSet(metadata_range)) # More info about the metadata",
"= 1 AVB_HASHTREE_FOOTER = 2 def __init__(self, partition_name, partition_size, footer_type,",
"not self.ValidateHashtree(): raise HashtreeInfoGenerationError(\"Failed to reconstruct the verity tree\") return",
"reconstruct the hashtree. Raises: HashtreeInfoGenerationError: If we fail to generate",
"Build the verity tree and get the root hash and",
"= None self.filesystem_size = None self.hashtree_size = None self.metadata_size =",
"Expected size in bytes of each block for the sparse",
"= GetVerityTreeSize(image_size) verity_metadata_size = GetVerityMetadataSize(image_size) verity_size = verity_tree_size + verity_metadata_size",
"image and writes it to the given file.\"\"\" raise NotImplementedError",
"is taken care of by avbtool. pass def Build(self, out_file):",
"class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator): \"\"\"A class that parses the metadata of hashtree",
"This needs to be implemented. Note that returning the given",
"simg.total_blocks def ZeroPadSimg(image_file, pad_size): blocks = pad_size // BLOCK_SIZE logger.info(\"Padding",
"self.key_path, \"--algorithm\", self.algorithm]) if self.salt: cmd.extend([\"--salt\", self.salt]) cmd.extend(shlex.split(self.signing_args)) proc =",
"# verity tree and fec sizes depend on the partition",
"BuildVerityFEC( out_file, verity_image_path, verity_fec_path, padding_size) Append(verity_image_path, verity_fec_path, \"Failed to append",
"cmd.append(\"--signer_args=\\\"%s\\\"\" % (' '.join(signer_args),)) if verity_disable: cmd.append(\"--verity_disable\") common.RunAndCheckOutput(cmd) def Append2Simg(sparse_image_path,",
"signing_args): self.version = 2 self.partition_name = partition_name self.partition_size = partition_size",
"partition, including metadata. verity_fec_path = os.path.join(tempdir_name, \"verity_fec.img\") BuildVerityFEC( out_file, verity_image_path,",
"structure available in: # system/extras/verity/build_verity_metadata.py META_HEADER_SIZE = 268 header_bin =",
"self.CalculateMinPartitionSize(image_size) return self.partition_size def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates max image size",
"#!/usr/bin/env python # # Copyright (C) 2018 The Android Open",
"for the verity metadata. Args: partition_size: The partition size, which",
"is always going to be unnecessarily small verity_size = GetVeritySize(hi,",
"image): \"\"\"Parses and validates the hashtree info in a sparse",
"VerityImageBuilder instance for Verified Boot 1.0 or Verified Boot 2.0;",
"Unless required by applicable law or agreed to in writing,",
"= prop_dict[\"verity_signer_cmd\"] return Version1VerityImageBuilder( partition_size, prop_dict[\"verity_block_device\"], prop_dict.get(\"verity_fec\") == \"true\", signer_path,",
"return generator class HashtreeInfoGenerator(object): def Generate(self, image): raise NotImplementedError def",
"The whole size in bytes of a partition, including the",
"get the root hash and salt. root_hash, salt = BuildVerityTree(out_file,",
"as the padding is taken care of by avbtool. pass",
"self.hashtree_info.root_hash: logger.warning( \"Calculated root hash %s doesn't match the one",
"the specific language governing permissions and # limitations under the",
"if (prop_dict.get(\"avb_hash_enable\") == \"true\" or prop_dict.get(\"avb_hashtree_enable\") == \"true\"): # key_path",
"\"true\" or prop_dict.get(\"avb_hashtree_enable\") == \"true\"): # key_path and algorithm are",
"verity_path, verity_fec_path, padding_size): cmd = [\"fec\", \"-e\", \"-p\", str(padding_size), sparse_image_path,",
"self.block_size == 0 verity_tree_size = GetVerityTreeSize(adjusted_size) assert verity_tree_size % self.block_size",
"size by accounting for the verity metadata. Args: partition_size: The",
"to modify. \"\"\" add_footer = (\"add_hash_footer\" if self.footer_type == self.AVB_HASH_FOOTER",
"\"\"\"Calculates the max image size by accounting for the verity",
"partition_size: The partition size, which defaults to self.partition_size if unspecified.",
"metadata block.\"\"\" metadata_start = self.filesystem_size + self.hashtree_size metadata_range = RangeSet(",
"[self.avbtool, add_footer, \"--partition_size\", str(partition_size), \"--calc_max_image_size\"] cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output,",
"Verified Boot 1.0 and Verified Boot 2.0. A matching builder",
"Boot 1.0 verity_supported = prop_dict.get(\"verity\") == \"true\" is_verity_partition = \"verity_block_device\"",
"\"partition size {} doesn't match with the calculated image size.\"",
"License. from __future__ import print_function import logging import os.path import",
"image_size): \"\"\"Calculates and sets the partition size for a dynamic",
"= i verity_size = v lo = i + BLOCK_SIZE",
"* simg.total_blocks def ZeroPadSimg(image_file, pad_size): blocks = pad_size // BLOCK_SIZE",
"don't need the following properties that are needed for signing",
"header = struct.unpack(\"II256sI\", header_bin) # header: magic_number, version, signature, table_len",
"need the following properties that are needed for signing the",
"else: lo = mid + BLOCK_SIZE logger.info( \"CalculateMinPartitionSize(%d): partition_size %d.\",",
"for a dynamic partition, which should be cover the given",
"[self.avbtool, add_footer, \"--partition_size\", str(self.partition_size), \"--partition_name\", self.partition_name, \"--image\", out_file] if self.key_path",
"BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt, block_device, signer_path, key, signer_args, verity_disable): cmd",
"block_size: Expected size in bytes of each block for the",
"make sense, as it will fail later. raise NotImplementedError def",
"shlex import struct import common import sparse_img from rangelib import",
"hashtree. Raises: HashtreeInfoGenerationError: If we fail to generate the exact",
"the verity image and writes it to the given file.\"\"\"",
"required to accommodate the image size. \"\"\" if size_calculator is",
"which defaults to self.partition_size if unspecified. Returns: The maximum image",
"common.Run(cmd) output, _ = proc.communicate() if proc.returncode != 0: raise",
"self.block_size, (adjusted_size + verity_tree_size) // self.block_size]) def _ParseHashtreeMetadata(self): \"\"\"Parses the",
"verity table size {}\".format( len(table_entries)) assert (int(table_entries[3]) == self.block_size and",
"found at the following link. https://source.android.com/security/verifiedboot/dm-verity#implementation \"\"\" def CalculateMaxImageSize(self, partition_size):",
"self.root_hash = None def CreateHashtreeInfoGenerator(partition_name, block_size, info_dict): generator = None",
"VerityImageBuilder for Verified Boot 2.0.\"\"\" AVB_HASH_FOOTER = 1 AVB_HASHTREE_FOOTER =",
"BLOCK_SIZE # verity tree and fec sizes depend on the",
"hash_algorithm root_hash salt\" assert len(table_entries) == 10, \"Unexpected verity table",
"for a dynamic partition.\"\"\" raise NotImplementedError def PadSparseImage(self, out_file): \"\"\"Adds",
"Boot 1.0 and Verified Boot 2.0. A matching builder will",
"image_size. delta = BLOCK_SIZE max_image_size = size_calculator(lo) while max_image_size >",
"\"size\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVeritySize(image_size,",
"+ BLOCK_SIZE else: hi = i self.image_size = result self.verity_size",
"if verity_disable: cmd.append(\"--verity_disable\") common.RunAndCheckOutput(cmd) def Append2Simg(sparse_image_path, unsparse_image_path, error_message): \"\"\"Appends the",
"'verity_key': '', 'verity_signer_cmd': None, } self.verity_image_builder = CreateVerityImageBuilder(prop_dict) self.hashtree_info =",
"adjusted_partition = common.MakeTempFile(prefix=\"adjusted_partition\") with open(adjusted_partition, \"wb\") as fd: self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd)",
"fec_data]. We can then calculate the size and offset of",
"= 268 header_bin = meta_data[0:META_HEADER_SIZE] header = struct.unpack(\"II256sI\", header_bin) #",
"partition_name self.partition_size = partition_size self.footer_type = footer_type self.avbtool = avbtool",
"None def CreateHashtreeInfoGenerator(partition_name, block_size, info_dict): generator = None if (info_dict.get(\"verity\")",
"hi % BLOCK_SIZE != 0: hi = (hi // BLOCK_SIZE)",
"AVB footer: {}\".format(output)) class HashtreeInfoGenerationError(Exception): \"\"\"An Exception raised during hashtree",
"the following properties that are needed for signing the #",
"return root, salt def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt, block_device, signer_path,",
"the hashtree. \"\"\" self.DecomposeSparseImage(image) self._ParseHashtreeMetadata() if not self.ValidateHashtree(): raise HashtreeInfoGenerationError(\"Failed",
"= size_calculator(mid) if max_image_size >= image_size: # if mid can",
"the metadata blocks. BuildVerityMetadata( image_size, verity_metadata_path, root_hash, salt, self.block_device, self.signer_path,",
"contains the build properties. In particular, it will look for",
"= None self.hashtree_size = None self.metadata_size = None prop_dict =",
"error_message): \"\"\"Appends the unsparse image to the given sparse image.",
"generation.\"\"\" def __init__(self, message): Exception.__init__(self, message) class HashtreeInfo(object): def __init__(self):",
"the hash tree. adjusted_partition = common.MakeTempFile(prefix=\"adjusted_partition\") with open(adjusted_partition, \"wb\") as",
"hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE max_image_size = size_calculator(mid)",
"def CalculateMaxImageSize(self, partition_size): \"\"\"Calculates the filesystem image size for the",
"Returns: The minimum partition size required to accommodate the image",
"= common.BLOCK_SIZE FIXED_SALT = \"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\" class BuildVerityImageError(Exception): \"\"\"An Exception raised",
"size. block_size: Expected size in bytes of each block for",
"in input_file: out_file.write(line) except IOError: logger.exception(error_message) raise BuildVerityImageError(error_message) def CreateVerityImageBuilder(prop_dict):",
"builder = VerifiedBootVersion2VerityImageBuilder( partition_name, partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get(\"avb_avbtool\"), key_path, algorithm, #",
"\"\"\"A VerityImageBuilder for Verified Boot 2.0.\"\"\" AVB_HASH_FOOTER = 1 AVB_HASHTREE_FOOTER",
"(int(table_entries[5]) * self.block_size == self.filesystem_size and int(table_entries[6]) * self.block_size ==",
"out_file): \"\"\"Builds the verity image and writes it to the",
"# Image uses hash footer. if prop_dict.get(\"avb_hash_enable\") == \"true\": return",
"output, _ = proc.communicate() if proc.returncode != 0: raise BuildVerityImageError(",
"if self.footer_type == self.AVB_HASH_FOOTER else \"add_hashtree_footer\") cmd = [self.avbtool, add_footer,",
"adjusted_size // self.block_size]) self.hashtree_info.hashtree_range = RangeSet( data=[adjusted_size // self.block_size, (adjusted_size",
"following properties that are needed for signing the # verity",
"delta *= 2 max_image_size = size_calculator(lo) hi = lo +",
"to target. Raises: BuildVerityImageError: On error. \"\"\" try: with open(target,",
"the unsparse image to the given sparse image. Args: sparse_image_path:",
"size while lo < hi: i = ((lo + hi)",
"the filesystem section to a temp file; and calls the",
"data_blocks data_blocks hash_algorithm root_hash salt\" assert len(table_entries) == 10, \"Unexpected",
"# Copyright (C) 2018 The Android Open Source Project #",
"filesystem image size for the given partition size.\"\"\" raise NotImplementedError",
"salt = BuildVerityTree(adjusted_partition, generated_verity_tree) # The salt should be always",
"!= 0: raise BuildVerityImageError( \"Failed to calculate max image size:\\n{}\".format(output))",
"partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hashtree_footer_args\"]) return None class",
"Returns: The maximum image size. Raises: BuildVerityImageError: On error or",
"= max_image_size / float(hi) hi = int(image_size / image_ratio) //",
"raise NotImplementedError class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator): \"\"\"A class that parses the metadata",
"verity tree and get the root hash and salt. root_hash,",
"\"true\"): # key_path and algorithm are only available when chain",
"self.block_size, \\ \"partition size {} doesn't match with the calculated",
"size. Returns: The minimum partition size required to accommodate the",
"append FEC\") Append2Simg( out_file, verity_image_path, \"Failed to append verity data\")",
"BLOCK_SIZE + delta delta *= 2 max_image_size = size_calculator(hi) partition_size",
"and checks if it has the exact same bytes #",
"\"\"\"Adds dm-verity hashtree and AVB metadata to an image. Args:",
"= (\"add_hash_footer\" if self.footer_type == self.AVB_HASH_FOOTER else \"add_hashtree_footer\") cmd =",
"large enough: max_image_size should >= image_size. delta = BLOCK_SIZE max_image_size",
"= GetVerityFECSize(image_size + verity_size) return verity_size + fec_size return verity_size",
"size of the image adjusted for verity metadata. \"\"\" if",
"BuildVerityImageError(\"Failed to add AVB footer: {}\".format(output)) class HashtreeInfoGenerationError(Exception): \"\"\"An Exception",
"hash_algorithm, root_hash, salt from the metadata block.\"\"\" metadata_start = self.filesystem_size",
"for the entire partition, including metadata. verity_fec_path = os.path.join(tempdir_name, \"verity_fec.img\")",
"self.hash_algorithm = None self.salt = None self.root_hash = None def",
"hash %s doesn't match the one in metadata %s\", root_hash,",
"rangelib import RangeSet logger = logging.getLogger(__name__) OPTIONS = common.OPTIONS BLOCK_SIZE",
"algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hashtree_footer_args\"]) return None class VerityImageBuilder(object): \"\"\"A builder that",
"# if a smaller partition size is found partition_size =",
"self.partition_name, \"--image\", out_file] if self.key_path and self.algorithm: cmd.extend([\"--key\", self.key_path, \"--algorithm\",",
"%d.\", image_size, partition_size) return partition_size def CalculateDynamicPartitionSize(self, image_size): self.partition_size =",
"\"Failed to append verity metadata\") if self.fec_supported: # Build FEC",
"the given build properties. Args: prop_dict: A dict that contains",
"fec_supported self.image = None self.filesystem_size = None self.hashtree_size = None",
"You may obtain a copy of the License at #",
"if mid < partition_size: # if a smaller partition size",
"None, } self.verity_image_builder = CreateVerityImageBuilder(prop_dict) self.hashtree_info = HashtreeInfo() def DecomposeSparseImage(self,",
"metadata\") if self.fec_supported: # Build FEC for the entire partition,",
"image size: {}\".format(output)) self.image_size = image_size return image_size def PadSparseImage(self,",
"\"\"\"Returns a verity image builder based on the given build",
"verity hash tree.\"\"\" # Writes the filesystem section to a",
"# Salt is None because custom images have no fingerprint",
"def ValidateHashtree(self): \"\"\"Checks that we can reconstruct the verity hash",
"RangeSet( data=[metadata_start // self.block_size, (metadata_start + self.metadata_size) // self.block_size]) meta_data",
"to append verity metadata\") if self.fec_supported: # Build FEC for",
"size. Raises: BuildVerityImageError: On error or getting invalid image size.",
"property to be # used as the salt. None, signing_args)",
"block_dev self.fec_supported = fec_supported self.signer_path = signer_path self.signer_key = signer_key",
"The salt should be always identical, as we use fixed",
"\".pk8\", OPTIONS.verity_signer_args, \"verity_disable\" in prop_dict) # Verified Boot 2.0 if",
"== \"true\" is_verity_partition = \"verity_block_device\" in prop_dict if verity_supported and",
"self.signer_args = signer_args self.verity_disable = verity_disable self.image_size = None self.verity_size",
"root, salt = output.split() return root, salt def BuildVerityMetadata(image_size, verity_metadata_path,",
"= common.MakeTempFile(prefix=\"verity\") root_hash, salt = BuildVerityTree(adjusted_partition, generated_verity_tree) # The salt",
"partition_size %d, image_size %d, \" \"verity_size %d\", partition_size, result, verity_size)",
"partition_size, footer_type, avbtool, key_path, algorithm, salt, signing_args): self.version = 2",
"= int(output) if image_size <= 0: raise BuildVerityImageError( \"Invalid max",
"self.partition_size = self.CalculateMinPartitionSize(image_size) return self.partition_size def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates max",
"that contains the build properties. In particular, it will look",
"to accommodate the image size. \"\"\" if size_calculator is None:",
"fec_size return verity_size def GetSimgSize(image_file): simg = sparse_img.SparseImage(image_file, build_map=False) return",
"self.signer_key = signer_key self.signer_args = signer_args self.verity_disable = verity_disable self.image_size",
"estimate is always going to be unnecessarily small verity_size =",
"raise NotImplementedError def ValidateHashtree(self): raise NotImplementedError class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator): \"\"\"A class",
"fail to generate the exact bytes of the hashtree. \"\"\"",
"NotImplementedError def Build(self, out_file): \"\"\"Builds the verity image and writes",
"\"\"\" if partition_size is None: partition_size = self.partition_size assert partition_size",
"(\"add_hash_footer\" if self.footer_type == self.AVB_HASH_FOOTER else \"add_hashtree_footer\") cmd = [self.avbtool,",
"max image size:\\n{}\".format(output)) image_size = int(output) if image_size <= 0:",
"raise BuildVerityImageError( \"Error: image size of {} is larger than",
"partition_size, block_size, fec_supported): \"\"\"Initialize VerityTreeInfo with the sparse image and",
"def __init__(self, message): Exception.__init__(self, message) def GetVerityFECSize(image_size): cmd = [\"fec\",",
"which should be cover the given image size (for filesystem",
"return None class VerityImageBuilder(object): \"\"\"A builder that generates an image",
"prop_dict) # Verified Boot 2.0 if (prop_dict.get(\"avb_hash_enable\") == \"true\" or",
"footer: {}\".format(output)) class HashtreeInfoGenerationError(Exception): \"\"\"An Exception raised during hashtree info",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"with the sparse image and input property. Arguments: partition_size: The",
"== self.filesystem_size and int(table_entries[6]) * self.block_size == self.filesystem_size) self.hashtree_info.hash_algorithm =",
"fec_supported else None, # 'verity_block_device' needs to be present to",
"_ = proc.communicate() if proc.returncode != 0: raise BuildVerityImageError( \"Failed",
"Append2Simg(sparse_image_path, unsparse_image_path, error_message): \"\"\"Appends the unsparse image to the given",
"size of \" \"{}\".format(sparse_image_size, self.image_size)) ZeroPadSimg(out_file, self.image_size - sparse_image_size) class",
"value. assert salt == self.hashtree_info.salt, \\ \"Calculated salt {} doesn't",
"bytes # as the one in the sparse image. with",
"len(table_entries) == 10, \"Unexpected verity table size {}\".format( len(table_entries)) assert",
"size: {}\".format(output)) self.image_size = image_size return image_size def PadSparseImage(self, out_file):",
"hi = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE +",
"common import sparse_img from rangelib import RangeSet logger = logging.getLogger(__name__)",
"= common.OPTIONS BLOCK_SIZE = common.BLOCK_SIZE FIXED_SALT = \"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\" class BuildVerityImageError(Exception):",
"metadata of hashtree for a given partition.\"\"\" def __init__(self, partition_size,",
"except: logger.exception(error_message) raise BuildVerityImageError(error_message) def Append(target, file_to_append, error_message): \"\"\"Appends file_to_append",
"sparse_image_path, unsparse_image_path] try: common.RunAndCheckOutput(cmd) except: logger.exception(error_message) raise BuildVerityImageError(error_message) def Append(target,",
"metadata_size % self.block_size == 0 self.filesystem_size = adjusted_size self.hashtree_size =",
"limitations under the License. from __future__ import print_function import logging",
"verity_size + fec_size return verity_size def GetSimgSize(image_file): simg = sparse_img.SparseImage(image_file,",
"result = i verity_size = v lo = i +",
"prop_dict: A dict that contains the build properties. In particular,",
"https://source.android.com/security/verifiedboot/dm-verity#implementation \"\"\" def CalculateMaxImageSize(self, partition_size): \"\"\"Calculates the filesystem image size",
"Exception.__init__(self, message) def GetVerityFECSize(image_size): cmd = [\"fec\", \"-s\", str(image_size)] output",
"\"\"\" self.DecomposeSparseImage(image) self._ParseHashtreeMetadata() if not self.ValidateHashtree(): raise HashtreeInfoGenerationError(\"Failed to reconstruct",
"\"Failed to calculate max image size:\\n{}\".format(output)) image_size = int(output) if",
"language governing permissions and # limitations under the License. from",
"= image assert self.block_size == image.blocksize assert self.partition_size == image.total_blocks",
"be # used as the salt. None, signing_args) return builder",
"the max image size by accounting for the verity metadata.",
"offset of each section. \"\"\" self.image = image assert self.block_size",
"OPTIONS.verity_signer_args, \"verity_disable\" in prop_dict) # Verified Boot 2.0 if (prop_dict.get(\"avb_hash_enable\")",
"enough: max_image_size should <= image_size. delta = BLOCK_SIZE max_image_size =",
"= table_entries[9].decode() def ValidateHashtree(self): \"\"\"Checks that we can reconstruct the",
"simg = sparse_img.SparseImage(image_file, build_map=False) return simg.blocksize * simg.total_blocks def ZeroPadSimg(image_file,",
"minimum partition size required to accommodate the image size. \"\"\"",
"class HashtreeInfoGenerationError(Exception): \"\"\"An Exception raised during hashtree info generation.\"\"\" def",
"salt should be always identical, as we use fixed value.",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"NotImplementedError def CalculateDynamicPartitionSize(self, image_size): \"\"\"Calculates and sets the partition size",
"build doesn't support Verified Boot. \"\"\" partition_size = prop_dict.get(\"partition_size\") #",
"metadata to an image. Args: out_file: Path to image to",
"return self.partition_size def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates max image size for",
"License. # You may obtain a copy of the License",
"open(adjusted_partition, \"wb\") as fd: self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd) generated_verity_tree = common.MakeTempFile(prefix=\"verity\") root_hash,",
"verity_disable self.image_size = None self.verity_size = None def CalculateDynamicPartitionSize(self, image_size):",
"= common.RunAndCheckOutput(cmd) root, salt = output.split() return root, salt def",
"[\"fec\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def",
"lo < hi: i = ((lo + hi) // (2",
"input property. Arguments: partition_size: The whole size in bytes of",
"prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hash_footer_args\"]) # Image uses hashtree footer. return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"],",
"< partition_size: # if a smaller partition size is found",
"the optimal size while lo < hi: i = ((lo",
"root_hash, salt, block_device, signer_path, key] if signer_args: cmd.append(\"--signer_args=\\\"%s\\\"\" % ('",
"b''.join(self.image.ReadRangeSet(metadata_range)) # More info about the metadata structure available in:",
"# means this estimate is always going to be unnecessarily",
"file.\"\"\" raise NotImplementedError class Version1VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot",
"* BLOCK_SIZE - BLOCK_SIZE # Ensure lo is small enough:",
"self.CalculateMaxImageSize # Use image size as partition size to approximate",
"'verity_block_device': '', # We don't need the following properties that",
"metadata. \"\"\" if partition_size is None: partition_size = self.partition_size assert",
"A VerityImageBuilder instance for Verified Boot 1.0 or Verified Boot",
"for Verified Boot. A VerityImageBuilder instance handles the works for",
"partition size required to accommodate the image size. \"\"\" if",
"image_size): self.partition_size = self.CalculateMinPartitionSize(image_size) return self.partition_size def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates",
"os.path.join(tempdir_name, \"verity.img\") verity_metadata_path = os.path.join(tempdir_name, \"verity_metadata.img\") # Build the verity",
"verified image. Append( verity_image_path, verity_metadata_path, \"Failed to append verity metadata\")",
"NotImplementedError def DecomposeSparseImage(self, image): raise NotImplementedError def ValidateHashtree(self): raise NotImplementedError",
"int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE #",
"self.metadata_size = None prop_dict = { 'partition_size': str(partition_size), 'verity': 'true',",
"tree and fec sizes depend on the partition size, which",
"the structure of a verity enabled image to be: [filesystem,",
"can then calculate the size and offset of each section.",
"self.image_size = image_size return image_size def PadSparseImage(self, out_file): # No-op",
"'ab') as out_file, \\ open(file_to_append, 'rb') as input_file: for line",
"calculate max image size:\\n{}\".format(output)) image_size = int(output) if image_size <=",
"== 10, \"Unexpected verity table size {}\".format( len(table_entries)) assert (int(table_entries[3])",
"# system/extras/verity/build_verity_metadata.py META_HEADER_SIZE = 268 header_bin = meta_data[0:META_HEADER_SIZE] header =",
"v lo = i + BLOCK_SIZE else: hi = i",
"match with the calculated image size.\" \\ \" total_blocks: {}\".format(self.partition_size,",
"self.image_size = None def CalculateMinPartitionSize(self, image_size, size_calculator=None): \"\"\"Calculates min partition",
"the verity image generation can be found at the following",
"else: signer_path = prop_dict[\"verity_signer_cmd\"] return Version1VerityImageBuilder( partition_size, prop_dict[\"verity_block_device\"], prop_dict.get(\"verity_fec\") ==",
"table_len] table_entries = verity_table.rstrip().split() # Expected verity table format: \"1",
"be present to indicate a verity-enabled # partition. 'verity_block_device': '',",
"cmd = [\"build_verity_metadata\", \"build\", str(image_size), verity_metadata_path, root_hash, salt, block_device, signer_path,",
"the one in the sparse image. with open(generated_verity_tree, 'rb') as",
"is large enough: max_image_size should >= image_size. delta = BLOCK_SIZE",
"verity_metadata_size if fec_supported: fec_size = GetVerityFECSize(image_size + verity_size) return verity_size",
"'verity_signer_cmd': None, } self.verity_image_builder = CreateVerityImageBuilder(prop_dict) self.hashtree_info = HashtreeInfo() def",
"verity_image_path): cmd = [\"build_verity_tree\", \"-A\", FIXED_SALT, sparse_image_path, verity_image_path] output =",
"image size (for filesystem files) as well as the verity",
"Build(self, out_file): \"\"\"Builds the verity image and writes it to",
"BuildVerityImageError( \"Error: image size of {} is larger than partition",
"on the verity image generation can be found at the",
"mid hi = mid else: lo = mid + BLOCK_SIZE",
"0xb001b001, header[0] table_len = header[3] verity_table = meta_data[META_HEADER_SIZE: META_HEADER_SIZE +",
"OPTIONS.verity_signer_path is not None: signer_path = OPTIONS.verity_signer_path else: signer_path =",
"doesn't match the one in metadata {}\".format( salt, self.hashtree_info.salt) if",
"of {} is larger than partition size of \" \"{}\".format(sparse_image_size,",
"None if the given build doesn't support Verified Boot. \"\"\"",
"verity tree and fec sizes depend on the partition size,",
"# do a binary search for the optimal size while",
"VerityTreeInfo with the sparse image and input property. Arguments: partition_size:",
"None self.metadata_size = None prop_dict = { 'partition_size': str(partition_size), 'verity':",
"signature, table_len assert header[0] == 0xb001b001, header[0] table_len = header[3]",
"verity_path, verity_fec_path] common.RunAndCheckOutput(cmd) def BuildVerityTree(sparse_image_path, verity_image_path): cmd = [\"build_verity_tree\", \"-A\",",
"BuildVerityImageError: On error. \"\"\" cmd = [\"append2simg\", sparse_image_path, unsparse_image_path] try:",
"No-op as the padding is taken care of by avbtool.",
"VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hashtree_footer_args\"]) return",
"partition_size is None: partition_size = self.partition_size assert partition_size > 0,",
"prop_dict = { 'partition_size': str(partition_size), 'verity': 'true', 'verity_fec': 'true' if",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"size. Args: image_size: The size of the image in question.",
"the given partition size.\"\"\" raise NotImplementedError def CalculateDynamicPartitionSize(self, image_size): \"\"\"Calculates",
"executable # build_verity_tree to construct the hash tree. adjusted_partition =",
"the (sparse) image unsparse_image_path: the path to the (unsparse) image",
"Boot 2.0 if (prop_dict.get(\"avb_hash_enable\") == \"true\" or prop_dict.get(\"avb_hashtree_enable\") == \"true\"):",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"verity image generation can be found at the following link.",
"if image_size <= 0: raise BuildVerityImageError( \"Invalid max image size:",
"match the one in metadata %s\", root_hash, self.hashtree_info.root_hash) return False",
"\"verity_size %d\", partition_size, result, verity_size) return result def Build(self, out_file):",
"size for a dynamic partition, which should be cover the",
"required by applicable law or agreed to in writing, software",
"False # Reads the generated hash tree and checks if",
"builder = None if info_dict.get(\"avb_enable\") == \"true\": builder = VerifiedBootVersion2VerityImageBuilder(",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"optimal size while lo < hi: i = ((lo +",
"pad_size) simg = sparse_img.SparseImage(image_file, mode=\"r+b\", build_map=False) simg.AppendFillChunk(0, blocks) def BuildVerityFEC(sparse_image_path,",
"salt, block_device, signer_path, key, signer_args, verity_disable): cmd = [\"build_verity_metadata\", \"build\",",
"image. Args: sparse_image_path: the path to the (sparse) image unsparse_image_path:",
"partition_size self.footer_type = footer_type self.avbtool = avbtool self.algorithm = algorithm",
"self.hashtree_info.hash_algorithm = table_entries[7].decode() self.hashtree_info.root_hash = table_entries[8].decode() self.hashtree_info.salt = table_entries[9].decode() def",
"padding is taken care of by avbtool. pass def Build(self,",
"temp file; and calls the executable # build_verity_tree to construct",
"to the given file.\"\"\" raise NotImplementedError class Version1VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder",
"to the generated sparse image.\"\"\" raise NotImplementedError def Build(self, out_file):",
"fixed value. assert salt == self.hashtree_info.salt, \\ \"Calculated salt {}",
"info on the verity image generation can be found at",
"a dynamic partition, which should be cover the given image",
"agreed to in writing, software # distributed under the License",
"image size as partition size to approximate final partition size.",
"return fd.read() == b''.join(self.image.ReadRangeSet( self.hashtree_info.hashtree_range)) def Generate(self, image): \"\"\"Parses and",
"size doesn't make sense, as it will fail later. raise",
"def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates max image size for a given",
"distributed under the License is distributed on an \"AS IS\"",
"\" \"verity_size %d\", partition_size, result, verity_size) return result def Build(self,",
"image. with open(generated_verity_tree, 'rb') as fd: return fd.read() == b''.join(self.image.ReadRangeSet(",
"used when determining the partition size for a dynamic partition,",
"filesystem size, padding size, and verity size. block_size: Expected size",
"a given partition size. Args: partition_size: The partition size, which",
"fec_supported: fec_size = GetVerityFECSize(image_size + verity_size) return verity_size + fec_size",
"NotImplementedError def PadSparseImage(self, out_file): \"\"\"Adds padding to the generated sparse",
"BuildVerityTree(sparse_image_path, verity_image_path): cmd = [\"build_verity_tree\", \"-A\", FIXED_SALT, sparse_image_path, verity_image_path] output",
"None self.salt = None self.root_hash = None def CreateHashtreeInfoGenerator(partition_name, block_size,",
"'verity_fec': 'true' if fec_supported else None, # 'verity_block_device' needs to",
"to binary search. while lo < hi: mid = ((lo",
"open(file_to_append, 'rb') as input_file: for line in input_file: out_file.write(line) except",
"format: \"1 block_device block_device block_size # block_size data_blocks data_blocks hash_algorithm",
"Since we already know the structure of a verity enabled",
"uses hash footer. if prop_dict.get(\"avb_hash_enable\") == \"true\": return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"],",
"file_to_append, error_message): \"\"\"Appends file_to_append to target. Raises: BuildVerityImageError: On error.",
"- self.verity_size assert padding_size >= 0 # Build the full",
"size of {} is larger than partition size of \"",
"of \" \"{}\".format(sparse_image_size, self.image_size)) ZeroPadSimg(out_file, self.image_size - sparse_image_size) class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder):",
"image): raise NotImplementedError def ValidateHashtree(self): raise NotImplementedError class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator): \"\"\"A",
"// self.block_size]) def _ParseHashtreeMetadata(self): \"\"\"Parses the hash_algorithm, root_hash, salt from",
"self.filesystem_size and int(table_entries[6]) * self.block_size == self.filesystem_size) self.hashtree_info.hash_algorithm = table_entries[7].decode()",
"during hashtree info generation.\"\"\" def __init__(self, message): Exception.__init__(self, message) class",
"verbose=False) return int(output) def GetVeritySize(image_size, fec_supported): verity_tree_size = GetVerityTreeSize(image_size) verity_metadata_size",
"salt from the metadata block.\"\"\" metadata_start = self.filesystem_size + self.hashtree_size",
"hi = lo + BLOCK_SIZE # Ensure hi is large",
"{ 'partition_size': str(partition_size), 'verity': 'true', 'verity_fec': 'true' if fec_supported else",
"self.block_size == image.blocksize assert self.partition_size == image.total_blocks * self.block_size, \\",
"size for the given partition size.\"\"\" raise NotImplementedError def CalculateDynamicPartitionSize(self,",
"lo + BLOCK_SIZE # Ensure hi is large enough: max_image_size",
"info_dict): generator = None if (info_dict.get(\"verity\") == \"true\" and info_dict.get(\"{}_verity_block_device\".format(partition_name))):",
"VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get(\"avb_avbtool\"), key_path, algorithm, # Salt is None because custom",
"verity_table.rstrip().split() # Expected verity table format: \"1 block_device block_device block_size",
"partition_size: The whole size in bytes of a partition, including",
"= hi # Start to binary search. while lo <",
"image with verity metadata for supporting Android Verified Boot. This",
"Exception raised during verity image building.\"\"\" def __init__(self, message): Exception.__init__(self,",
"= verity_disable self.image_size = None self.verity_size = None def CalculateDynamicPartitionSize(self,",
"salt = BuildVerityTree(out_file, verity_image_path) # Build the metadata blocks. BuildVerityMetadata(",
"On error. \"\"\" cmd = [\"append2simg\", sparse_image_path, unsparse_image_path] try: common.RunAndCheckOutput(cmd)",
"% self.block_size == 0 verity_tree_size = GetVerityTreeSize(adjusted_size) assert verity_tree_size %",
"unnecessarily small verity_size = GetVeritySize(hi, self.fec_supported) lo = partition_size -",
"[\"build_verity_metadata\", \"size\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def",
"build_map=False) return simg.blocksize * simg.total_blocks def ZeroPadSimg(image_file, pad_size): blocks =",
"None self.hashtree_size = None self.metadata_size = None prop_dict = {",
"= OPTIONS.verity_signer_path else: signer_path = prop_dict[\"verity_signer_cmd\"] return Version1VerityImageBuilder( partition_size, prop_dict[\"verity_block_device\"],",
"signer_args self.verity_disable = verity_disable self.image_size = None self.verity_size = None",
"key_path and algorithm are only available when chain partition is",
"add AVB footer: {}\".format(output)) class HashtreeInfoGenerationError(Exception): \"\"\"An Exception raised during",
"self.AVB_HASH_FOOTER else \"add_hashtree_footer\") cmd = [self.avbtool, add_footer, \"--partition_size\", str(self.partition_size), \"--partition_name\",",
"output = common.RunAndCheckOutput(cmd) root, salt = output.split() return root, salt",
"'true' if fec_supported else None, # 'verity_block_device' needs to be",
"Android Open Source Project # # Licensed under the Apache",
"info about the metadata structure available in: # system/extras/verity/build_verity_metadata.py META_HEADER_SIZE",
"size as partition size to approximate final partition size. image_ratio",
"reconstruct the verity hash tree.\"\"\" # Writes the filesystem section",
"0: raise BuildVerityImageError(\"Failed to add AVB footer: {}\".format(output)) class HashtreeInfoGenerationError(Exception):",
"return False # Reads the generated hash tree and checks",
"True if the verity section contains fec data. \"\"\" self.block_size",
"IOError: logger.exception(error_message) raise BuildVerityImageError(error_message) def CreateVerityImageBuilder(prop_dict): \"\"\"Returns a verity image",
"We don't need the following properties that are needed for",
"verity-related property values. Returns: A VerityImageBuilder instance for Verified Boot",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"self.block_size == 0 self.filesystem_size = adjusted_size self.hashtree_size = verity_tree_size self.metadata_size",
"= self.filesystem_size + self.hashtree_size metadata_range = RangeSet( data=[metadata_start // self.block_size,",
"key] if signer_args: cmd.append(\"--signer_args=\\\"%s\\\"\" % (' '.join(signer_args),)) if verity_disable: cmd.append(\"--verity_disable\")",
"it has the exact same bytes # as the one",
"the License is distributed on an \"AS IS\" BASIS, #",
"common.BLOCK_SIZE FIXED_SALT = \"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\" class BuildVerityImageError(Exception): \"\"\"An Exception raised during",
"image.total_blocks * self.block_size, \\ \"partition size {} doesn't match with",
"max_image_size / float(lo) lo = int(image_size / image_ratio) // BLOCK_SIZE",
"// (2 * BLOCK_SIZE)) * BLOCK_SIZE max_image_size = size_calculator(mid) if",
"verity_tree_size % self.block_size == 0 metadata_size = GetVerityMetadataSize(adjusted_size) assert metadata_size",
"Returns: hashtree_info: The information needed to reconstruct the hashtree. Raises:",
"+ verity_size) return verity_size + fec_size return verity_size def GetSimgSize(image_file):",
"def Generate(self, image): \"\"\"Parses and validates the hashtree info in",
"// BLOCK_SIZE logger.info(\"Padding %d blocks (%d bytes)\", blocks, pad_size) simg",
"small verity_size = GetVeritySize(hi, self.fec_supported) lo = partition_size - verity_size",
"about the metadata structure available in: # system/extras/verity/build_verity_metadata.py META_HEADER_SIZE =",
"\"\"\"Parses and validates the hashtree info in a sparse image.",
"return verity_size + fec_size return verity_size def GetSimgSize(image_file): simg =",
"except IOError: logger.exception(error_message) raise BuildVerityImageError(error_message) def CreateVerityImageBuilder(prop_dict): \"\"\"Returns a verity",
"for Verified Boot 1.0 or Verified Boot 2.0; or None",
"approximate final partition size. image_ratio = size_calculator(image_size) / float(image_size) #",
"tree and get the root hash and salt. root_hash, salt",
"BLOCK_SIZE max_image_size = size_calculator(mid) if max_image_size >= image_size: # if",
"law or agreed to in writing, software # distributed under",
"Boot. \"\"\" partition_size = prop_dict.get(\"partition_size\") # partition_size could be None",
"self.block_size]) self.hashtree_info.hashtree_range = RangeSet( data=[adjusted_size // self.block_size, (adjusted_size + verity_tree_size)",
"following link. https://source.android.com/security/verifiedboot/dm-verity#implementation \"\"\" def CalculateMaxImageSize(self, partition_size): \"\"\"Calculates the filesystem",
"GetVerityTreeSize(image_size) verity_metadata_size = GetVerityMetadataSize(image_size) verity_size = verity_tree_size + verity_metadata_size if",
"verity_size) return verity_size + fec_size return verity_size def GetSimgSize(image_file): simg",
"verity: partition_size %d, image_size %d, \" \"verity_size %d\", partition_size, result,",
"Boot 1.0 or Verified Boot 2.0; or None if the",
"prop_dict.get(\"avb_hashtree_enable\") == \"true\"): # key_path and algorithm are only available",
"based on the given build properties. More info on the",
"\"true\" generator = VerifiedBootVersion1HashtreeInfoGenerator( partition_size, block_size, fec_supported) return generator class",
"to the given sparse image. Args: sparse_image_path: the path to",
"info_dict.get(\"avb_enable\") == \"true\": builder = VerifiedBootVersion2VerityImageBuilder( partition_name, partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get(\"avb_avbtool\"),",
"= 1 self.partition_size = partition_size self.block_device = block_dev self.fec_supported =",
"algorithm = prop_dict.get(\"avb_algorithm\") # Image uses hash footer. if prop_dict.get(\"avb_hash_enable\")",
"= GetVerityMetadataSize(adjusted_size) assert metadata_size % self.block_size == 0 self.filesystem_size =",
"may obtain a copy of the License at # #",
"self.block_size) assert (int(table_entries[5]) * self.block_size == self.filesystem_size and int(table_entries[6]) *",
"the padding is taken care of by avbtool. pass def",
"Build the full verified image. Append( verity_image_path, verity_metadata_path, \"Failed to",
"[\"fec\", \"-e\", \"-p\", str(padding_size), sparse_image_path, verity_path, verity_fec_path] common.RunAndCheckOutput(cmd) def BuildVerityTree(sparse_image_path,",
"be returned based on the given build properties. More info",
"sparse_img.SparseImage(image_file, mode=\"r+b\", build_map=False) simg.AppendFillChunk(0, blocks) def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path, padding_size):",
"= verity_tree_size self.metadata_size = metadata_size self.hashtree_info.filesystem_range = RangeSet( data=[0, adjusted_size",
"be cover the given image size (for filesystem files) as",
"self.verity_image_builder = CreateVerityImageBuilder(prop_dict) self.hashtree_info = HashtreeInfo() def DecomposeSparseImage(self, image): \"\"\"Calculate",
"# Prepare a binary search for the optimal partition size.",
"may not use this file except in compliance with the",
"key_path = prop_dict.get(\"avb_key_path\") algorithm = prop_dict.get(\"avb_algorithm\") # Image uses hash",
"def PadSparseImage(self, out_file): \"\"\"Adds padding to the generated sparse image.\"\"\"",
"(for filesystem files) as well as the verity metadata size.",
"} self.verity_image_builder = CreateVerityImageBuilder(prop_dict) self.hashtree_info = HashtreeInfo() def DecomposeSparseImage(self, image):",
"image size for a given partition size. Args: partition_size: The",
"(prop_dict.get(\"avb_hash_enable\") == \"true\" or prop_dict.get(\"avb_hashtree_enable\") == \"true\"): # key_path and",
"partition size: {}\".format(partition_size) hi = partition_size if hi % BLOCK_SIZE",
"self.version = 2 self.partition_name = partition_name self.partition_size = partition_size self.footer_type",
"assert metadata_size % self.block_size == 0 self.filesystem_size = adjusted_size self.hashtree_size",
"this file except in compliance with the License. # You",
"CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates max image size for a given partition",
"image paths. verity_image_path = os.path.join(tempdir_name, \"verity.img\") verity_metadata_path = os.path.join(tempdir_name, \"verity_metadata.img\")",
"VerityImageBuilder instance handles the works for building an image with",
"+ hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE max_image_size =",
"%d blocks (%d bytes)\", blocks, pad_size) simg = sparse_img.SparseImage(image_file, mode=\"r+b\",",
"values. Returns: A VerityImageBuilder instance for Verified Boot 1.0 or",
"# # Licensed under the Apache License, Version 2.0 (the",
"int(partition_size) # Verified Boot 1.0 verity_supported = prop_dict.get(\"verity\") == \"true\"",
"float(image_size) # Prepare a binary search for the optimal partition",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"verity_size = v lo = i + BLOCK_SIZE else: hi",
"image size.\" \\ \" total_blocks: {}\".format(self.partition_size, image.total_blocks) adjusted_size = self.verity_image_builder.CalculateMaxImageSize()",
"FEC for the entire partition, including metadata. verity_fec_path = os.path.join(tempdir_name,",
"max image size by accounting for the verity metadata. Args:",
"None: size_calculator = self.CalculateMaxImageSize # Use image size as partition",
"verity_fec_path] common.RunAndCheckOutput(cmd) def BuildVerityTree(sparse_image_path, verity_image_path): cmd = [\"build_verity_tree\", \"-A\", FIXED_SALT,",
"partition_size: # if a smaller partition size is found partition_size",
"assert (int(table_entries[5]) * self.block_size == self.filesystem_size and int(table_entries[6]) * self.block_size",
"- sparse_image_size) class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot 2.0.\"\"\"",
"image building.\"\"\" def __init__(self, message): Exception.__init__(self, message) def GetVerityFECSize(image_size): cmd",
"the metadata of hashtree for a given partition.\"\"\" def __init__(self,",
"The Android Open Source Project # # Licensed under the",
"blocks (%d bytes)\", blocks, pad_size) simg = sparse_img.SparseImage(image_file, mode=\"r+b\", build_map=False)",
"lo = i + BLOCK_SIZE else: hi = i self.image_size",
"class defines the common interface between Verified Boot 1.0 and",
"\"build\", str(image_size), verity_metadata_path, root_hash, salt, block_device, signer_path, key] if signer_args:",
"Returns: The size of the image adjusted for verity metadata.",
"assert partition_size > 0, \\ \"Invalid partition size: {}\".format(partition_size) add_footer",
"the given build properties. More info on the verity image",
"{}\".format(output)) self.image_size = image_size return image_size def PadSparseImage(self, out_file): #",
"\"\"\" add_footer = (\"add_hash_footer\" if self.footer_type == self.AVB_HASH_FOOTER else \"add_hashtree_footer\")",
"delta delta *= 2 max_image_size = size_calculator(hi) partition_size = hi",
"sparse_image_path, verity_image_path] output = common.RunAndCheckOutput(cmd) root, salt = output.split() return",
"BLOCK_SIZE max_image_size = size_calculator(lo) while max_image_size > image_size: image_ratio =",
"instance for Verified Boot 1.0 or Verified Boot 2.0; or",
"size_calculator is None: size_calculator = self.CalculateMaxImageSize # Use image size",
"header_bin) # header: magic_number, version, signature, table_len assert header[0] ==",
"raise BuildVerityImageError( \"Invalid max image size: {}\".format(output)) self.image_size = image_size",
"for a given partition.\"\"\" def __init__(self, partition_size, block_size, fec_supported): \"\"\"Initialize",
"given sparse image. Args: sparse_image_path: the path to the (sparse)",
"metadata blocks. BuildVerityMetadata( image_size, verity_metadata_path, root_hash, salt, self.block_device, self.signer_path, self.signer_key,",
"verity_size def GetSimgSize(image_file): simg = sparse_img.SparseImage(image_file, build_map=False) return simg.blocksize *",
"BLOCK_SIZE logger.info(\"Padding %d blocks (%d bytes)\", blocks, pad_size) simg =",
"or implied. # See the License for the specific language",
"= os.path.join(tempdir_name, \"verity.img\") verity_metadata_path = os.path.join(tempdir_name, \"verity_metadata.img\") # Build the",
"meta_data[0:META_HEADER_SIZE] header = struct.unpack(\"II256sI\", header_bin) # header: magic_number, version, signature,",
"metadata {}\".format( salt, self.hashtree_info.salt) if root_hash != self.hashtree_info.root_hash: logger.warning( \"Calculated",
"signer_args, verity_disable): self.version = 1 self.partition_size = partition_size self.block_device =",
"to reconstruct the verity tree\") return self.hashtree_info def CreateCustomImageBuilder(info_dict, partition_name,",
"def GetVerityMetadataSize(image_size): cmd = [\"build_verity_metadata\", \"size\", str(image_size)] output = common.RunAndCheckOutput(cmd,",
"A VerityImageBuilder instance handles the works for building an image",
"hi is large enough: max_image_size should >= image_size. delta =",
"to approximate final partition size. image_ratio = size_calculator(image_size) / float(image_size)",
"# build_verity_tree to construct the hash tree. adjusted_partition = common.MakeTempFile(prefix=\"adjusted_partition\")",
"== \"true\"): # key_path and algorithm are only available when",
"add_footer, \"--partition_size\", str(partition_size), \"--calc_max_image_size\"] cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output, _",
"= int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE + delta",
"partition sizes. BuildVerityImageError: On other errors. \"\"\" image_size = int(self.image_size)",
"\"Error: image size of {} is larger than partition size",
"%d, \" \"verity_size %d\", partition_size, result, verity_size) return result def",
"= VerifiedBootVersion2VerityImageBuilder( partition_name, partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get(\"avb_avbtool\"), key_path, algorithm, # Salt",
"partition_size def CalculateDynamicPartitionSize(self, image_size): self.partition_size = self.CalculateMinPartitionSize(image_size) return self.partition_size def",
"0: hi = (hi // BLOCK_SIZE) * BLOCK_SIZE # verity",
"to self.partition_size if unspecified. Returns: The maximum image size. Raises:",
"when determining the partition size for a dynamic partition, which",
"size and offset of each section. \"\"\" self.image = image",
"* BLOCK_SIZE - delta delta *= 2 max_image_size = size_calculator(lo)",
"(sparse) image unsparse_image_path: the path to the (unsparse) image Raises:",
"= i + BLOCK_SIZE else: hi = i self.image_size =",
"len(table_entries)) assert (int(table_entries[3]) == self.block_size and int(table_entries[4]) == self.block_size) assert",
"\"\"\"Checks that we can reconstruct the verity hash tree.\"\"\" #",
"permissions and # limitations under the License. from __future__ import",
"generator = VerifiedBootVersion1HashtreeInfoGenerator( partition_size, block_size, fec_supported) return generator class HashtreeInfoGenerator(object):",
"the verity section contains fec data. \"\"\" self.block_size = block_size",
"can reconstruct the verity hash tree.\"\"\" # Writes the filesystem",
"__init__(self, message): Exception.__init__(self, message) class HashtreeInfo(object): def __init__(self): self.hashtree_range =",
"have no fingerprint property to be # used as the",
"# Writes the filesystem section to a temp file; and",
"raise BuildVerityImageError(\"Failed to add AVB footer: {}\".format(output)) class HashtreeInfoGenerationError(Exception): \"\"\"An",
"\"\"\"Initialize VerityTreeInfo with the sparse image and input property. Arguments:",
"path to the (unsparse) image Raises: BuildVerityImageError: On error. \"\"\"",
"self.fec_supported) if i + v <= partition_size: if result <",
"result self.verity_size = verity_size logger.info( \"Calculated image size for verity:",
"enough: max_image_size should >= image_size. delta = BLOCK_SIZE max_image_size =",
"size_calculator(hi) while max_image_size < image_size: image_ratio = max_image_size / float(hi)",
"return partition_size def CalculateDynamicPartitionSize(self, image_size): self.partition_size = self.CalculateMinPartitionSize(image_size) return self.partition_size",
"def ValidateHashtree(self): raise NotImplementedError class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator): \"\"\"A class that parses",
"size. image_ratio = size_calculator(image_size) / float(image_size) # Prepare a binary",
"\"\"\"Adds padding to the generated sparse image.\"\"\" raise NotImplementedError def",
"verity-enabled # partition. 'verity_block_device': '', # We don't need the",
"= [\"build_verity_tree\", \"-A\", FIXED_SALT, sparse_image_path, verity_image_path] output = common.RunAndCheckOutput(cmd) root,",
"verity metadata\") if self.fec_supported: # Build FEC for the entire",
"self.hashtree_info = HashtreeInfo() def DecomposeSparseImage(self, image): \"\"\"Calculate the verity size",
"(unsparse) image Raises: BuildVerityImageError: On error. \"\"\" cmd = [\"append2simg\",",
"output image. Returns: AssertionError: On invalid partition sizes. BuildVerityImageError: On",
"metadata_size self.hashtree_info.filesystem_range = RangeSet( data=[0, adjusted_size // self.block_size]) self.hashtree_info.hashtree_range =",
"generated_verity_tree) # The salt should be always identical, as we",
"a binary search for the optimal size while lo <",
"0 # Build the full verified image. Append( verity_image_path, verity_metadata_path,",
"is small enough: max_image_size should <= image_size. delta = BLOCK_SIZE",
"\"add_hashtree_footer\") cmd = [self.avbtool, add_footer, \"--partition_size\", str(partition_size), \"--calc_max_image_size\"] cmd.extend(shlex.split(self.signing_args)) proc",
"= None self.filesystem_range = None self.hash_algorithm = None self.salt =",
"str(partition_size), 'verity': 'true', 'verity_fec': 'true' if fec_supported else None, #",
"= mid else: lo = mid + BLOCK_SIZE logger.info( \"CalculateMinPartitionSize(%d):",
"common.RunAndCheckOutput(cmd) def Append2Simg(sparse_image_path, unsparse_image_path, error_message): \"\"\"Appends the unsparse image to",
"\"Invalid max image size: {}\".format(output)) self.image_size = image_size return image_size",
"of the image adjusted for verity metadata. \"\"\" if partition_size",
"# Start to binary search. while lo < hi: mid",
"prop_dict.get(\"avb_algorithm\") # Image uses hash footer. if prop_dict.get(\"avb_hash_enable\") == \"true\":",
"CalculateDynamicPartitionSize(self, image_size): \"\"\"Calculates and sets the partition size for a",
"A matching builder will be returned based on the given",
"sparse_image_path: the path to the (sparse) image unsparse_image_path: the path",
"sparse_img from rangelib import RangeSet logger = logging.getLogger(__name__) OPTIONS =",
"Expected verity table format: \"1 block_device block_device block_size # block_size",
"size_calculator(lo) hi = lo + BLOCK_SIZE # Ensure hi is",
"output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityMetadataSize(image_size): cmd =",
"= footer_type self.avbtool = avbtool self.algorithm = algorithm self.key_path =",
"/ image_ratio) // BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE # Ensure",
"invalid image size. \"\"\" if partition_size is None: partition_size =",
"== 0 metadata_size = GetVerityMetadataSize(adjusted_size) assert metadata_size % self.block_size ==",
"verity metadata for Verified Boot. A VerityImageBuilder instance handles the",
"self.partition_size = partition_size self.fec_supported = fec_supported self.image = None self.filesystem_size",
"= size_calculator(hi) while max_image_size < image_size: image_ratio = max_image_size /",
"for line in input_file: out_file.write(line) except IOError: logger.exception(error_message) raise BuildVerityImageError(error_message)",
"the one in metadata %s\", root_hash, self.hashtree_info.root_hash) return False #",
"BuildVerityImageError( \"Invalid max image size: {}\".format(output)) self.image_size = image_size return",
"BLOCK_SIZE = common.BLOCK_SIZE FIXED_SALT = \"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\" class BuildVerityImageError(Exception): \"\"\"An Exception",
"image_size, verity_metadata_path, root_hash, salt, self.block_device, self.signer_path, self.signer_key, self.signer_args, self.verity_disable) padding_size",
"class that parses the metadata of hashtree for a given",
"sparse_img.SparseImage(image_file, build_map=False) return simg.blocksize * simg.total_blocks def ZeroPadSimg(image_file, pad_size): blocks",
"information needed to reconstruct the hashtree. Raises: HashtreeInfoGenerationError: If we",
"def CreateCustomImageBuilder(info_dict, partition_name, partition_size, key_path, algorithm, signing_args): builder = None",
"self.hashtree_info.salt = table_entries[9].decode() def ValidateHashtree(self): \"\"\"Checks that we can reconstruct",
"prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hashtree_footer_args\"]) return None class VerityImageBuilder(object): \"\"\"A",
"error or getting invalid image size. \"\"\" if partition_size is",
"self.salt = None self.root_hash = None def CreateHashtreeInfoGenerator(partition_name, block_size, info_dict):",
"simg.blocksize * simg.total_blocks def ZeroPadSimg(image_file, pad_size): blocks = pad_size //",
"size for a dynamic partition.\"\"\" raise NotImplementedError def PadSparseImage(self, out_file):",
"Args: image_size: The size of the image in question. size_calculator:",
"prop_dict.get(\"verity_fec\") == \"true\", signer_path, prop_dict[\"verity_key\"] + \".pk8\", OPTIONS.verity_signer_args, \"verity_disable\" in",
"data=[0, adjusted_size // self.block_size]) self.hashtree_info.hashtree_range = RangeSet( data=[adjusted_size // self.block_size,",
"int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - delta delta",
"GetVeritySize(hi, self.fec_supported) lo = partition_size - verity_size result = lo",
"match the one in metadata {}\".format( salt, self.hashtree_info.salt) if root_hash",
"\"\"\"Calculate the verity size based on the size of the",
"GetVerityFECSize(image_size): cmd = [\"fec\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False)",
"+ \".pk8\", OPTIONS.verity_signer_args, \"verity_disable\" in prop_dict) # Verified Boot 2.0",
"VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hash_footer_args\"]) #",
"BuildVerityImageError: On error. \"\"\" try: with open(target, 'ab') as out_file,",
"signer_args, verity_disable): cmd = [\"build_verity_metadata\", \"build\", str(image_size), verity_metadata_path, root_hash, salt,",
"prop_dict.get(\"partition_size\") # partition_size could be None at this point, if",
"image): raise NotImplementedError def DecomposeSparseImage(self, image): raise NotImplementedError def ValidateHashtree(self):",
"(int(table_entries[3]) == self.block_size and int(table_entries[4]) == self.block_size) assert (int(table_entries[5]) *",
"given file.\"\"\" raise NotImplementedError class Version1VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified",
"means this estimate is always going to be unnecessarily small",
"delta = BLOCK_SIZE max_image_size = size_calculator(lo) while max_image_size > image_size:",
"max_image_size = size_calculator(mid) if max_image_size >= image_size: # if mid",
"\"Invalid partition size: {}\".format(partition_size) add_footer = (\"add_hash_footer\" if self.footer_type ==",
"salt = output.split() return root, salt def BuildVerityMetadata(image_size, verity_metadata_path, root_hash,",
"\"\"\" self.image = image assert self.block_size == image.blocksize assert self.partition_size",
"and self.algorithm: cmd.extend([\"--key\", self.key_path, \"--algorithm\", self.algorithm]) if self.salt: cmd.extend([\"--salt\", self.salt])",
"metadata %s\", root_hash, self.hashtree_info.root_hash) return False # Reads the generated",
"str(self.partition_size), \"--partition_name\", self.partition_name, \"--image\", out_file] if self.key_path and self.algorithm: cmd.extend([\"--key\",",
"logger.exception(error_message) raise BuildVerityImageError(error_message) def Append(target, file_to_append, error_message): \"\"\"Appends file_to_append to",
"size_calculator(hi) partition_size = hi # Start to binary search. while",
"building.\"\"\" def __init__(self, message): Exception.__init__(self, message) def GetVerityFECSize(image_size): cmd =",
"logger.info( \"Calculated image size for verity: partition_size %d, image_size %d,",
"if the given build doesn't support Verified Boot. \"\"\" partition_size",
"the output image. Returns: AssertionError: On invalid partition sizes. BuildVerityImageError:",
"and Verified Boot 2.0. A matching builder will be returned",
"with verity metadata for Verified Boot. A VerityImageBuilder instance handles",
"in writing, software # distributed under the License is distributed",
"def CalculateMinPartitionSize(self, image_size, size_calculator=None): \"\"\"Calculates min partition size for a",
"builder based on the given build properties. Args: prop_dict: A",
"== 0 verity_tree_size = GetVerityTreeSize(adjusted_size) assert verity_tree_size % self.block_size ==",
"ValidateHashtree(self): \"\"\"Checks that we can reconstruct the verity hash tree.\"\"\"",
"The maximum image size. Raises: BuildVerityImageError: On error or getting",
"VerityImageBuilder for Verified Boot 1.0.\"\"\" def __init__(self, partition_size, block_dev, fec_supported,",
"NotImplementedError def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates the max image size by",
"dynamic partition, which should be cover the given image size",
"verity image builder based on the given build properties. Args:",
"# No-op as the padding is taken care of by",
"verity metadata. 'verity_key': '', 'verity_signer_cmd': None, } self.verity_image_builder = CreateVerityImageBuilder(prop_dict)",
"\"Failed to append FEC\") Append2Simg( out_file, verity_image_path, \"Failed to append",
"for verity-related property values. Returns: A VerityImageBuilder instance for Verified",
"assert self.partition_size == image.total_blocks * self.block_size, \\ \"partition size {}",
"# We don't need the following properties that are needed",
"0, \\ \"Invalid partition size: {}\".format(partition_size) add_footer = (\"add_hash_footer\" if",
"partition size.\"\"\" raise NotImplementedError def CalculateDynamicPartitionSize(self, image_size): \"\"\"Calculates and sets",
"self.block_size = block_size self.partition_size = partition_size self.fec_supported = fec_supported self.image",
"HashtreeInfoGenerationError: If we fail to generate the exact bytes of",
"header[0] table_len = header[3] verity_table = meta_data[META_HEADER_SIZE: META_HEADER_SIZE + table_len]",
"\"\"\"Calculates and sets the partition size for a dynamic partition.\"\"\"",
"BLOCK_SIZE - delta delta *= 2 max_image_size = size_calculator(lo) hi",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"image builder based on the given build properties. Args: prop_dict:",
"License, Version 2.0 (the \"License\"); # you may not use",
"we fail to generate the exact bytes of the hashtree.",
"== \"true\" generator = VerifiedBootVersion1HashtreeInfoGenerator( partition_size, block_size, fec_supported) return generator",
"be unnecessarily small verity_size = GetVeritySize(hi, self.fec_supported) lo = partition_size",
"verity_size = verity_tree_size + verity_metadata_size if fec_supported: fec_size = GetVerityFECSize(image_size",
"self.key_path and self.algorithm: cmd.extend([\"--key\", self.key_path, \"--algorithm\", self.algorithm]) if self.salt: cmd.extend([\"--salt\",",
"BuildVerityImageError( \"Failed to calculate max image size:\\n{}\".format(output)) image_size = int(output)",
"if signer_args: cmd.append(\"--signer_args=\\\"%s\\\"\" % (' '.join(signer_args),)) if verity_disable: cmd.append(\"--verity_disable\") common.RunAndCheckOutput(cmd)",
"# the partition size doesn't make sense, as it will",
"prop_dict[\"verity_key\"] + \".pk8\", OPTIONS.verity_signer_args, \"verity_disable\" in prop_dict) # Verified Boot",
"Append( verity_image_path, verity_metadata_path, \"Failed to append verity metadata\") if self.fec_supported:",
"Raises: BuildVerityImageError: On error. \"\"\" cmd = [\"append2simg\", sparse_image_path, unsparse_image_path]",
"VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot 2.0.\"\"\" AVB_HASH_FOOTER = 1",
"image assert self.block_size == image.blocksize assert self.partition_size == image.total_blocks *",
"\"\"\"An Exception raised during verity image building.\"\"\" def __init__(self, message):",
"salt, self.hashtree_info.salt) if root_hash != self.hashtree_info.root_hash: logger.warning( \"Calculated root hash",
"that is verifiable using dm-verity. Args: out_file: the output image.",
"the License for the specific language governing permissions and #",
"the partition size doesn't make sense, as it will fail",
"assert (int(table_entries[3]) == self.block_size and int(table_entries[4]) == self.block_size) assert (int(table_entries[5])",
"None self.root_hash = None def CreateHashtreeInfoGenerator(partition_name, block_size, info_dict): generator =",
"is None because custom images have no fingerprint property to",
"= verity_size logger.info( \"Calculated image size for verity: partition_size %d,",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"system/extras/verity/build_verity_metadata.py META_HEADER_SIZE = 268 header_bin = meta_data[0:META_HEADER_SIZE] header = struct.unpack(\"II256sI\",",
"self.hashtree_info.salt, \\ \"Calculated salt {} doesn't match the one in",
"GetVerityMetadataSize(adjusted_size) assert metadata_size % self.block_size == 0 self.filesystem_size = adjusted_size",
"sparse image. fec_supported: True if the verity section contains fec",
"- self.image_size - self.verity_size assert padding_size >= 0 # Build",
"sparse_image_path, verity_path, verity_fec_path] common.RunAndCheckOutput(cmd) def BuildVerityTree(sparse_image_path, verity_image_path): cmd = [\"build_verity_tree\",",
"max_image_size = size_calculator(hi) partition_size = hi # Start to binary",
"size for a given partition size. Returns: The minimum partition",
"+ self.hashtree_size metadata_range = RangeSet( data=[metadata_start // self.block_size, (metadata_start +",
"defines the common interface between Verified Boot 1.0 and Verified",
"care of by avbtool. pass def Build(self, out_file): \"\"\"Adds dm-verity",
"common.RunAndCheckOutput(cmd) root, salt = output.split() return root, salt def BuildVerityMetadata(image_size,",
"\"\"\"Builds the verity image and writes it to the given",
"else \"add_hashtree_footer\") cmd = [self.avbtool, add_footer, \"--partition_size\", str(partition_size), \"--calc_max_image_size\"] cmd.extend(shlex.split(self.signing_args))",
"assert verity_tree_size % self.block_size == 0 metadata_size = GetVerityMetadataSize(adjusted_size) assert",
"partition size for a dynamic partition, which should be cover",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"\"--partition_size\", str(partition_size), \"--calc_max_image_size\"] cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output, _ =",
"binary search. while lo < hi: mid = ((lo +",
"__init__(self, partition_size, block_size, fec_supported): \"\"\"Initialize VerityTreeInfo with the sparse image",
"image_size: # if mid can accommodate image_size if mid <",
"the hash_algorithm, root_hash, salt from the metadata block.\"\"\" metadata_start =",
"property. Arguments: partition_size: The whole size in bytes of a",
"fec sizes depend on the partition size, which # means",
"max_image_size = size_calculator(hi) while max_image_size < image_size: image_ratio = max_image_size",
"PadSparseImage(self, out_file): # No-op as the padding is taken care",
"\"--image\", out_file] if self.key_path and self.algorithm: cmd.extend([\"--key\", self.key_path, \"--algorithm\", self.algorithm])",
"\"\"\"Appends the unsparse image to the given sparse image. Args:",
"= sparse_img.SparseImage(image_file, build_map=False) return simg.blocksize * simg.total_blocks def ZeroPadSimg(image_file, pad_size):",
"common.RunAndCheckOutput(cmd) def BuildVerityTree(sparse_image_path, verity_image_path): cmd = [\"build_verity_tree\", \"-A\", FIXED_SALT, sparse_image_path,",
"raise NotImplementedError def PadSparseImage(self, out_file): \"\"\"Adds padding to the generated",
"hash tree and checks if it has the exact same",
"0, \\ \"Invalid partition size: {}\".format(partition_size) hi = partition_size if",
"calls the executable # build_verity_tree to construct the hash tree.",
"fec_supported, signer_path, signer_key, signer_args, verity_disable): self.version = 1 self.partition_size =",
"PadSparseImage(self, out_file): \"\"\"Adds padding to the generated sparse image.\"\"\" raise",
"block.\"\"\" metadata_start = self.filesystem_size + self.hashtree_size metadata_range = RangeSet( data=[metadata_start",
"self.signer_args, self.verity_disable) padding_size = self.partition_size - self.image_size - self.verity_size assert",
"None: partition_size = self.partition_size assert partition_size > 0, \\ \"Invalid",
"bytes of each block for the sparse image. fec_supported: True",
"# distributed under the License is distributed on an \"AS",
"build properties. In particular, it will look for verity-related property",
"Raises: BuildVerityImageError: On error or getting invalid image size. \"\"\"",
"# Unless required by applicable law or agreed to in",
"Android Verified Boot. This class defines the common interface between",
"salt def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt, block_device, signer_path, key, signer_args,",
"the (unsparse) image Raises: BuildVerityImageError: On error. \"\"\" cmd =",
"salt, signing_args): self.version = 2 self.partition_name = partition_name self.partition_size =",
"= partition_name self.partition_size = partition_size self.footer_type = footer_type self.avbtool =",
"cmd = [self.avbtool, add_footer, \"--partition_size\", str(self.partition_size), \"--partition_name\", self.partition_name, \"--image\", out_file]",
"= info_dict[\"{}_size\".format(partition_name)] fec_supported = info_dict.get(\"verity_fec\") == \"true\" generator = VerifiedBootVersion1HashtreeInfoGenerator(",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"= signing_args self.image_size = None def CalculateMinPartitionSize(self, image_size, size_calculator=None): \"\"\"Calculates",
"# Verified Boot 1.0 verity_supported = prop_dict.get(\"verity\") == \"true\" is_verity_partition",
"the common interface between Verified Boot 1.0 and Verified Boot",
"the verity size based on the size of the input",
"while max_image_size < image_size: image_ratio = max_image_size / float(hi) hi",
"and salt. root_hash, salt = BuildVerityTree(out_file, verity_image_path) # Build the",
"of each section. \"\"\" self.image = image assert self.block_size ==",
"adjusted_size self.hashtree_size = verity_tree_size self.metadata_size = metadata_size self.hashtree_info.filesystem_range = RangeSet(",
"a verity enabled image to be: [filesystem, verity_hashtree, verity_metadata, fec_data].",
"header: magic_number, version, signature, table_len assert header[0] == 0xb001b001, header[0]",
"one in the sparse image. with open(generated_verity_tree, 'rb') as fd:",
"return self.hashtree_info def CreateCustomImageBuilder(info_dict, partition_name, partition_size, key_path, algorithm, signing_args): builder",
"Verified Boot. \"\"\" partition_size = prop_dict.get(\"partition_size\") # partition_size could be",
"FIXED_SALT, sparse_image_path, verity_image_path] output = common.RunAndCheckOutput(cmd) root, salt = output.split()",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"== self.hashtree_info.salt, \\ \"Calculated salt {} doesn't match the one",
"partition_size: if result < i: result = i verity_size =",
"self.footer_type == self.AVB_HASH_FOOTER else \"add_hashtree_footer\") cmd = [self.avbtool, add_footer, \"--partition_size\",",
"partition_name, partition_size, footer_type, avbtool, key_path, algorithm, salt, signing_args): self.version =",
"< i: result = i verity_size = v lo =",
"verbose=False) return int(output) def GetVerityTreeSize(image_size): cmd = [\"build_verity_tree\", \"-s\", str(image_size)]",
"image_ratio = max_image_size / float(lo) lo = int(image_size / image_ratio)",
"writes it to the given file.\"\"\" raise NotImplementedError class Version1VerityImageBuilder(VerityImageBuilder):",
"the verity metadata. Args: partition_size: The partition size, which defaults",
"cmd.append(\"--verity_disable\") common.RunAndCheckOutput(cmd) def Append2Simg(sparse_image_path, unsparse_image_path, error_message): \"\"\"Appends the unsparse image",
"On error. \"\"\" try: with open(target, 'ab') as out_file, \\",
"image to be: [filesystem, verity_hashtree, verity_metadata, fec_data]. We can then",
"10, \"Unexpected verity table size {}\".format( len(table_entries)) assert (int(table_entries[3]) ==",
"if hi % BLOCK_SIZE != 0: hi = (hi //",
"BuildVerityImageError: On error or getting invalid image size. \"\"\" if",
"sense, as it will fail later. raise NotImplementedError def CalculateMaxImageSize(self,",
"\"\"\"Calculates min partition size for a given image size. This",
"self.hashtree_info.root_hash) return False # Reads the generated hash tree and",
"= BLOCK_SIZE max_image_size = size_calculator(lo) while max_image_size > image_size: image_ratio",
"defaults to self.partition_size if unspecified. Returns: The size of the",
"# # Copyright (C) 2018 The Android Open Source Project",
"CalculateMinPartitionSize(self, image_size, size_calculator=None): \"\"\"Calculates min partition size for a given",
"build properties. Args: prop_dict: A dict that contains the build",
"Boot. A VerityImageBuilder instance handles the works for building an",
"= partition_size self.block_device = block_dev self.fec_supported = fec_supported self.signer_path =",
"is found partition_size = mid hi = mid else: lo",
"the given sparse image. Args: sparse_image_path: the path to the",
"OPTIONS = common.OPTIONS BLOCK_SIZE = common.BLOCK_SIZE FIXED_SALT = \"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\" class",
"generates an image with verity metadata for Verified Boot. A",
"self.salt = salt self.signing_args = signing_args self.image_size = None def",
"image.blocksize assert self.partition_size == image.total_blocks * self.block_size, \\ \"partition size",
"hashtree_info: The information needed to reconstruct the hashtree. Raises: HashtreeInfoGenerationError:",
"be found at the following link. https://source.android.com/security/verifiedboot/dm-verity#implementation \"\"\" def CalculateMaxImageSize(self,",
"verbose=False) return int(output) def GetVerityMetadataSize(image_size): cmd = [\"build_verity_metadata\", \"size\", str(image_size)]",
"lo is small enough: max_image_size should <= image_size. delta =",
"\"--calc_max_image_size\"] cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output, _ = proc.communicate() if",
"= key_path self.salt = salt self.signing_args = signing_args self.image_size =",
"self.hashtree_info.filesystem_range = RangeSet( data=[0, adjusted_size // self.block_size]) self.hashtree_info.hashtree_range = RangeSet(",
"= [\"build_verity_metadata\", \"size\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output)",
"partition_size %d.\", image_size, partition_size) return partition_size def CalculateDynamicPartitionSize(self, image_size): self.partition_size",
"size. \"\"\" if partition_size is None: partition_size = self.partition_size assert",
"signer_path, prop_dict[\"verity_key\"] + \".pk8\", OPTIONS.verity_signer_args, \"verity_disable\" in prop_dict) # Verified",
"structure of a verity enabled image to be: [filesystem, verity_hashtree,",
"to be present to indicate a verity-enabled # partition. 'verity_block_device':",
"partition_size = mid hi = mid else: lo = mid",
"if self.key_path and self.algorithm: cmd.extend([\"--key\", self.key_path, \"--algorithm\", self.algorithm]) if self.salt:",
"GetVerityMetadataSize(image_size): cmd = [\"build_verity_metadata\", \"size\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False)",
"[\"append2simg\", sparse_image_path, unsparse_image_path] try: common.RunAndCheckOutput(cmd) except: logger.exception(error_message) raise BuildVerityImageError(error_message) def",
"verity_supported and is_verity_partition: if OPTIONS.verity_signer_path is not None: signer_path =",
"Verified Boot 1.0.\"\"\" def __init__(self, partition_size, block_dev, fec_supported, signer_path, signer_key,",
"getting invalid image size. \"\"\" if partition_size is None: partition_size",
"under the License is distributed on an \"AS IS\" BASIS,",
"verity_metadata_size = GetVerityMetadataSize(image_size) verity_size = verity_tree_size + verity_metadata_size if fec_supported:",
"\"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityMetadataSize(image_size):",
"padding_size): cmd = [\"fec\", \"-e\", \"-p\", str(padding_size), sparse_image_path, verity_path, verity_fec_path]",
"\"verity_disable\" in prop_dict) # Verified Boot 2.0 if (prop_dict.get(\"avb_hash_enable\") ==",
"try: with open(target, 'ab') as out_file, \\ open(file_to_append, 'rb') as",
"\"true\", signer_path, prop_dict[\"verity_key\"] + \".pk8\", OPTIONS.verity_signer_args, \"verity_disable\" in prop_dict) #",
"\"\"\"Calculates max image size for a given partition size. Args:",
"root, salt def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt, block_device, signer_path, key,",
"the exact bytes of the hashtree. \"\"\" self.DecomposeSparseImage(image) self._ParseHashtreeMetadata() if",
"verity image building.\"\"\" def __init__(self, message): Exception.__init__(self, message) def GetVerityFECSize(image_size):",
"if result < i: result = i verity_size = v",
"GetVerityFECSize(image_size + verity_size) return verity_size + fec_size return verity_size def",
"- delta delta *= 2 max_image_size = size_calculator(lo) hi =",
"an image that is verifiable using dm-verity. Args: out_file: the",
"for the given partition size.\"\"\" raise NotImplementedError def CalculateDynamicPartitionSize(self, image_size):",
"to generate the exact bytes of the hashtree. \"\"\" self.DecomposeSparseImage(image)",
"message): Exception.__init__(self, message) class HashtreeInfo(object): def __init__(self): self.hashtree_range = None",
"if root_hash != self.hashtree_info.root_hash: logger.warning( \"Calculated root hash %s doesn't",
"sizes depend on the partition size, which # means this",
"data=[adjusted_size // self.block_size, (adjusted_size + verity_tree_size) // self.block_size]) def _ParseHashtreeMetadata(self):",
"size: {}\".format(partition_size) hi = partition_size if hi % BLOCK_SIZE !=",
"VerifiedBootVersion1HashtreeInfoGenerator( partition_size, block_size, fec_supported) return generator class HashtreeInfoGenerator(object): def Generate(self,",
"if not self.ValidateHashtree(): raise HashtreeInfoGenerationError(\"Failed to reconstruct the verity tree\")",
"== self.block_size) assert (int(table_entries[5]) * self.block_size == self.filesystem_size and int(table_entries[6])",
"to append FEC\") Append2Simg( out_file, verity_image_path, \"Failed to append verity",
"needs to be implemented. Note that returning the given image",
"result = lo # do a binary search for the",
"None def CalculateMinPartitionSize(self, image_size, size_calculator=None): \"\"\"Calculates min partition size for",
"while max_image_size > image_size: image_ratio = max_image_size / float(lo) lo",
"self.block_size == 0 metadata_size = GetVerityMetadataSize(adjusted_size) assert metadata_size % self.block_size",
"of the hashtree. \"\"\" self.DecomposeSparseImage(image) self._ParseHashtreeMetadata() if not self.ValidateHashtree(): raise",
"unspecified. Returns: The size of the image adjusted for verity",
"from the metadata block.\"\"\" metadata_start = self.filesystem_size + self.hashtree_size metadata_range",
"partition_size = int(partition_size) # Verified Boot 1.0 verity_supported = prop_dict.get(\"verity\")",
"= adjusted_size self.hashtree_size = verity_tree_size self.metadata_size = metadata_size self.hashtree_info.filesystem_range =",
"\"-A\", FIXED_SALT, sparse_image_path, verity_image_path] output = common.RunAndCheckOutput(cmd) root, salt =",
"bytes of the hashtree. \"\"\" self.DecomposeSparseImage(image) self._ParseHashtreeMetadata() if not self.ValidateHashtree():",
"file_to_append to target. Raises: BuildVerityImageError: On error. \"\"\" try: with",
"is_verity_partition = \"verity_block_device\" in prop_dict if verity_supported and is_verity_partition: if",
"verity_size = GetVeritySize(hi, self.fec_supported) lo = partition_size - verity_size result",
"whole size in bytes of a partition, including the filesystem",
"self.image_size - sparse_image_size) class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot",
"partition size to approximate final partition size. image_ratio = size_calculator(image_size)",
"image. Since we already know the structure of a verity",
"use fixed value. assert salt == self.hashtree_info.salt, \\ \"Calculated salt",
"max image size for a given partition size. Args: partition_size:",
"partition size for a given image size. This is used",
"size (for filesystem files) as well as the verity metadata",
"\"verity_block_device\" in prop_dict if verity_supported and is_verity_partition: if OPTIONS.verity_signer_path is",
"return image_size def PadSparseImage(self, out_file): # No-op as the padding",
"if using dynamic partitions. if partition_size: partition_size = int(partition_size) #",
"block_size data_blocks data_blocks hash_algorithm root_hash salt\" assert len(table_entries) == 10,",
"ANY KIND, either express or implied. # See the License",
"the License. # You may obtain a copy of the",
"block_size # block_size data_blocks data_blocks hash_algorithm root_hash salt\" assert len(table_entries)",
"partition size. Args: partition_size: The partition size, which defaults to",
"!= 0: hi = (hi // BLOCK_SIZE) * BLOCK_SIZE #",
"cmd.extend([\"--salt\", self.salt]) cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output, _ = proc.communicate()",
"# header: magic_number, version, signature, table_len assert header[0] == 0xb001b001,",
"b''.join(self.image.ReadRangeSet( self.hashtree_info.hashtree_range)) def Generate(self, image): \"\"\"Parses and validates the hashtree",
"Returns: A VerityImageBuilder instance for Verified Boot 1.0 or Verified",
"if (info_dict.get(\"verity\") == \"true\" and info_dict.get(\"{}_verity_block_device\".format(partition_name))): partition_size = info_dict[\"{}_size\".format(partition_name)] fec_supported",
"# See the License for the specific language governing permissions",
"given build doesn't support Verified Boot. \"\"\" partition_size = prop_dict.get(\"partition_size\")",
"\"true\": return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"),",
"logger = logging.getLogger(__name__) OPTIONS = common.OPTIONS BLOCK_SIZE = common.BLOCK_SIZE FIXED_SALT",
"could be None at this point, if using dynamic partitions.",
"prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hashtree_footer_args\"]) return None",
"2.0 if (prop_dict.get(\"avb_hash_enable\") == \"true\" or prop_dict.get(\"avb_hashtree_enable\") == \"true\"): #",
"= None def CalculateMinPartitionSize(self, image_size, size_calculator=None): \"\"\"Calculates min partition size",
"prop_dict[\"avb_add_hashtree_footer_args\"]) return None class VerityImageBuilder(object): \"\"\"A builder that generates an",
"sparse_image_size) class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot 2.0.\"\"\" AVB_HASH_FOOTER",
"to the (unsparse) image Raises: BuildVerityImageError: On error. \"\"\" cmd",
"images have no fingerprint property to be # used as",
"self.signer_path, self.signer_key, self.signer_args, self.verity_disable) padding_size = self.partition_size - self.image_size -",
"of the image in question. size_calculator: The function to calculate",
"on the partition size, which # means this estimate is",
"as fd: self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd) generated_verity_tree = common.MakeTempFile(prefix=\"verity\") root_hash, salt =",
"<= 0: raise BuildVerityImageError( \"Invalid max image size: {}\".format(output)) self.image_size",
"image_size def PadSparseImage(self, out_file): # No-op as the padding is",
"table_len assert header[0] == 0xb001b001, header[0] table_len = header[3] verity_table",
"cmd = [\"build_verity_tree\", \"-A\", FIXED_SALT, sparse_image_path, verity_image_path] output = common.RunAndCheckOutput(cmd)",
"metadata_start = self.filesystem_size + self.hashtree_size metadata_range = RangeSet( data=[metadata_start //",
"1.0 and Verified Boot 2.0. A matching builder will be",
"block_size self.partition_size = partition_size self.fec_supported = fec_supported self.image = None",
"parses the metadata of hashtree for a given partition.\"\"\" def",
"partition_size): \"\"\"Calculates the filesystem image size for the given partition",
"is larger than partition size of \" \"{}\".format(sparse_image_size, self.image_size)) ZeroPadSimg(out_file,",
"verity image and writes it to the given file.\"\"\" raise",
"to calculate max image size:\\n{}\".format(output)) image_size = int(output) if image_size",
"that returning the given image size as # the partition",
"fd.read() == b''.join(self.image.ReadRangeSet( self.hashtree_info.hashtree_range)) def Generate(self, image): \"\"\"Parses and validates",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"= \"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\" class BuildVerityImageError(Exception): \"\"\"An Exception raised during verity image",
"On error or getting invalid image size. \"\"\" if partition_size",
"def GetVerityFECSize(image_size): cmd = [\"fec\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd,",
"= partition_size self.footer_type = footer_type self.avbtool = avbtool self.algorithm =",
"= BuildVerityTree(out_file, verity_image_path) # Build the metadata blocks. BuildVerityMetadata( image_size,",
"using dm-verity. Args: out_file: the output image. Returns: AssertionError: On",
"writing, software # distributed under the License is distributed on",
"verity_disable): cmd = [\"build_verity_metadata\", \"build\", str(image_size), verity_metadata_path, root_hash, salt, block_device,",
"for supporting Android Verified Boot. This class defines the common",
"def Append2Simg(sparse_image_path, unsparse_image_path, error_message): \"\"\"Appends the unsparse image to the",
"add_footer = (\"add_hash_footer\" if self.footer_type == self.AVB_HASH_FOOTER else \"add_hashtree_footer\") cmd",
"calculate the size and offset of each section. \"\"\" self.image",
"common.RunAndCheckOutput(cmd) except: logger.exception(error_message) raise BuildVerityImageError(error_message) def Append(target, file_to_append, error_message): \"\"\"Appends",
"function to calculate max image size for a given partition",
"1.0.\"\"\" def __init__(self, partition_size, block_dev, fec_supported, signer_path, signer_key, signer_args, verity_disable):",
"pad_size): blocks = pad_size // BLOCK_SIZE logger.info(\"Padding %d blocks (%d",
"generated_verity_tree = common.MakeTempFile(prefix=\"verity\") root_hash, salt = BuildVerityTree(adjusted_partition, generated_verity_tree) # The",
"\"-p\", str(padding_size), sparse_image_path, verity_path, verity_fec_path] common.RunAndCheckOutput(cmd) def BuildVerityTree(sparse_image_path, verity_image_path): cmd",
"max_image_size = size_calculator(lo) while max_image_size > image_size: image_ratio = max_image_size",
"[\"build_verity_tree\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def",
"partition.\"\"\" raise NotImplementedError def PadSparseImage(self, out_file): \"\"\"Adds padding to the",
"chain partition is used. key_path = prop_dict.get(\"avb_key_path\") algorithm = prop_dict.get(\"avb_algorithm\")",
"for a given partition size. Args: partition_size: The partition size,",
"available when chain partition is used. key_path = prop_dict.get(\"avb_key_path\") algorithm",
"AssertionError: On invalid partition sizes. BuildVerityImageError: On other errors. \"\"\"",
"if size_calculator is None: size_calculator = self.CalculateMaxImageSize # Use image",
"build properties. More info on the verity image generation can",
"image_size: image_ratio = max_image_size / float(lo) lo = int(image_size /",
"VerifiedBootVersion2VerityImageBuilder( partition_name, partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get(\"avb_avbtool\"), key_path, algorithm, # Salt is",
"fec_supported = info_dict.get(\"verity_fec\") == \"true\" generator = VerifiedBootVersion1HashtreeInfoGenerator( partition_size, block_size,",
"partition size is found partition_size = mid hi = mid",
"float(lo) lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE",
"and sets the partition size for a dynamic partition.\"\"\" raise",
"salt. root_hash, salt = BuildVerityTree(out_file, verity_image_path) # Build the metadata",
"error. \"\"\" cmd = [\"append2simg\", sparse_image_path, unsparse_image_path] try: common.RunAndCheckOutput(cmd) except:",
"verity_image_path] output = common.RunAndCheckOutput(cmd) root, salt = output.split() return root,",
"optimal partition size. lo = int(image_size / image_ratio) // BLOCK_SIZE",
"self.hashtree_info def CreateCustomImageBuilder(info_dict, partition_name, partition_size, key_path, algorithm, signing_args): builder =",
"def CreateVerityImageBuilder(prop_dict): \"\"\"Returns a verity image builder based on the",
"max image size: {}\".format(output)) self.image_size = image_size return image_size def",
"for verity: partition_size %d, image_size %d, \" \"verity_size %d\", partition_size,",
"found partition_size = mid hi = mid else: lo =",
"or Verified Boot 2.0; or None if the given build",
"python # # Copyright (C) 2018 The Android Open Source",
"we can reconstruct the verity hash tree.\"\"\" # Writes the",
"if prop_dict.get(\"avb_hash_enable\") == \"true\": return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict[\"avb_avbtool\"],",
"common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityTreeSize(image_size): cmd = [\"build_verity_tree\", \"-s\",",
"os.path.join(tempdir_name, \"verity_metadata.img\") # Build the verity tree and get the",
"def DecomposeSparseImage(self, image): \"\"\"Calculate the verity size based on the",
"in bytes of each block for the sparse image. fec_supported:",
"HashtreeInfoGenerationError(Exception): \"\"\"An Exception raised during hashtree info generation.\"\"\" def __init__(self,",
"proc.returncode != 0: raise BuildVerityImageError(\"Failed to add AVB footer: {}\".format(output))",
"def __init__(self, partition_size, block_size, fec_supported): \"\"\"Initialize VerityTreeInfo with the sparse",
"+ verity_tree_size) // self.block_size]) def _ParseHashtreeMetadata(self): \"\"\"Parses the hash_algorithm, root_hash,",
"size, padding size, and verity size. block_size: Expected size in",
"output.split() return root, salt def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt, block_device,",
"# Reads the generated hash tree and checks if it",
"self.hashtree_info.root_hash = table_entries[8].decode() self.hashtree_info.salt = table_entries[9].decode() def ValidateHashtree(self): \"\"\"Checks that",
"self.verity_size = verity_size logger.info( \"Calculated image size for verity: partition_size",
"(2 * BLOCK_SIZE)) * BLOCK_SIZE v = GetVeritySize(i, self.fec_supported) if",
"verity_table = meta_data[META_HEADER_SIZE: META_HEADER_SIZE + table_len] table_entries = verity_table.rstrip().split() #",
"self.image_size = result self.verity_size = verity_size logger.info( \"Calculated image size",
"return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hashtree_footer_args\"])",
"will fail later. raise NotImplementedError def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates the",
"by accounting for the verity metadata. Args: partition_size: The partition",
"for a given image size. This is used when determining",
"line in input_file: out_file.write(line) except IOError: logger.exception(error_message) raise BuildVerityImageError(error_message) def",
"def Build(self, out_file): \"\"\"Creates an image that is verifiable using",
"the partition size for a dynamic partition, which should be",
"verity_metadata_path, root_hash, salt, block_device, signer_path, key, signer_args, verity_disable): cmd =",
"return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hash_footer_args\"])",
"block for the sparse image. fec_supported: True if the verity",
"= avbtool self.algorithm = algorithm self.key_path = key_path self.salt =",
"image_size, partition_size) return partition_size def CalculateDynamicPartitionSize(self, image_size): self.partition_size = self.CalculateMinPartitionSize(image_size)",
"2 max_image_size = size_calculator(lo) hi = lo + BLOCK_SIZE #",
"error. \"\"\" try: with open(target, 'ab') as out_file, \\ open(file_to_append,",
"salt, self.block_device, self.signer_path, self.signer_key, self.signer_args, self.verity_disable) padding_size = self.partition_size -",
"fd) generated_verity_tree = common.MakeTempFile(prefix=\"verity\") root_hash, salt = BuildVerityTree(adjusted_partition, generated_verity_tree) #",
"info_dict.get(\"verity_fec\") == \"true\" generator = VerifiedBootVersion1HashtreeInfoGenerator( partition_size, block_size, fec_supported) return",
"# key_path and algorithm are only available when chain partition",
"it to the given file.\"\"\" raise NotImplementedError class Version1VerityImageBuilder(VerityImageBuilder): \"\"\"A",
"out_file] if self.key_path and self.algorithm: cmd.extend([\"--key\", self.key_path, \"--algorithm\", self.algorithm]) if",
"that parses the metadata of hashtree for a given partition.\"\"\"",
"a partition, including the filesystem size, padding size, and verity",
"if fec_supported else None, # 'verity_block_device' needs to be present",
"# Build FEC for the entire partition, including metadata. verity_fec_path",
"This class defines the common interface between Verified Boot 1.0",
"salt self.signing_args = signing_args self.image_size = None def CalculateMinPartitionSize(self, image_size,",
"None self.hash_algorithm = None self.salt = None self.root_hash = None",
"assert header[0] == 0xb001b001, header[0] table_len = header[3] verity_table =",
"delta delta *= 2 max_image_size = size_calculator(lo) hi = lo",
"verity section contains fec data. \"\"\" self.block_size = block_size self.partition_size",
"# Build the metadata blocks. BuildVerityMetadata( image_size, verity_metadata_path, root_hash, salt,",
"logging.getLogger(__name__) OPTIONS = common.OPTIONS BLOCK_SIZE = common.BLOCK_SIZE FIXED_SALT = \"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\"",
"Append(verity_image_path, verity_fec_path, \"Failed to append FEC\") Append2Simg( out_file, verity_image_path, \"Failed",
"cover the given image size (for filesystem files) as well",
"self.block_size == self.filesystem_size and int(table_entries[6]) * self.block_size == self.filesystem_size) self.hashtree_info.hash_algorithm",
"the following link. https://source.android.com/security/verifiedboot/dm-verity#implementation \"\"\" def CalculateMaxImageSize(self, partition_size): \"\"\"Calculates the",
"partition_size self.fec_supported = fec_supported self.image = None self.filesystem_size = None",
"= VerifiedBootVersion1HashtreeInfoGenerator( partition_size, block_size, fec_supported) return generator class HashtreeInfoGenerator(object): def",
"lo # do a binary search for the optimal size",
"= struct.unpack(\"II256sI\", header_bin) # header: magic_number, version, signature, table_len assert",
"// self.block_size, (adjusted_size + verity_tree_size) // self.block_size]) def _ParseHashtreeMetadata(self): \"\"\"Parses",
"verity data\") def PadSparseImage(self, out_file): sparse_image_size = GetSimgSize(out_file) if sparse_image_size",
"to self.partition_size if unspecified. Returns: The size of the image",
"the filesystem image size for the given partition size.\"\"\" raise",
"1.0 verity_supported = prop_dict.get(\"verity\") == \"true\" is_verity_partition = \"verity_block_device\" in",
"= None self.verity_size = None def CalculateDynamicPartitionSize(self, image_size): # This",
"error_message): \"\"\"Appends file_to_append to target. Raises: BuildVerityImageError: On error. \"\"\"",
"image generation can be found at the following link. https://source.android.com/security/verifiedboot/dm-verity#implementation",
"'partition_size': str(partition_size), 'verity': 'true', 'verity_fec': 'true' if fec_supported else None,",
"self.image = None self.filesystem_size = None self.hashtree_size = None self.metadata_size",
"CalculateDynamicPartitionSize(self, image_size): self.partition_size = self.CalculateMinPartitionSize(image_size) return self.partition_size def CalculateMaxImageSize(self, partition_size=None):",
"hi = (hi // BLOCK_SIZE) * BLOCK_SIZE # verity tree",
"self.partition_size == image.total_blocks * self.block_size, \\ \"partition size {} doesn't",
"(metadata_start + self.metadata_size) // self.block_size]) meta_data = b''.join(self.image.ReadRangeSet(metadata_range)) # More",
"BLOCK_SIZE != 0: hi = (hi // BLOCK_SIZE) * BLOCK_SIZE",
"to the (sparse) image unsparse_image_path: the path to the (unsparse)",
"// (2 * BLOCK_SIZE)) * BLOCK_SIZE v = GetVeritySize(i, self.fec_supported)",
"a sparse image. Returns: hashtree_info: The information needed to reconstruct",
"image_size = int(output) if image_size <= 0: raise BuildVerityImageError( \"Invalid",
"cmd.extend([\"--key\", self.key_path, \"--algorithm\", self.algorithm]) if self.salt: cmd.extend([\"--salt\", self.salt]) cmd.extend(shlex.split(self.signing_args)) proc",
"_ = proc.communicate() if proc.returncode != 0: raise BuildVerityImageError(\"Failed to",
"padding_size) Append(verity_image_path, verity_fec_path, \"Failed to append FEC\") Append2Simg( out_file, verity_image_path,",
"\"\"\" partition_size = prop_dict.get(\"partition_size\") # partition_size could be None at",
"GetSimgSize(out_file) if sparse_image_size > self.image_size: raise BuildVerityImageError( \"Error: image size",
"works for building an image with verity metadata for supporting",
"matching builder will be returned based on the given build",
"*= 2 max_image_size = size_calculator(lo) hi = lo + BLOCK_SIZE",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"{}\".format( salt, self.hashtree_info.salt) if root_hash != self.hashtree_info.root_hash: logger.warning( \"Calculated root",
"with verity metadata for supporting Android Verified Boot. This class",
"image_size = int(self.image_size) tempdir_name = common.MakeTempDir(suffix=\"_verity_images\") # Get partial image",
"table_len = header[3] verity_table = meta_data[META_HEADER_SIZE: META_HEADER_SIZE + table_len] table_entries",
"BuildVerityImageError(error_message) def Append(target, file_to_append, error_message): \"\"\"Appends file_to_append to target. Raises:",
"building an image with verity metadata for supporting Android Verified",
"verity_size) return result def Build(self, out_file): \"\"\"Creates an image that",
"interface between Verified Boot 1.0 and Verified Boot 2.0. A",
"def CreateHashtreeInfoGenerator(partition_name, block_size, info_dict): generator = None if (info_dict.get(\"verity\") ==",
"adjusted for verity metadata. \"\"\" if partition_size is None: partition_size",
"= self.CalculateMaxImageSize # Use image size as partition size to",
"generator = None if (info_dict.get(\"verity\") == \"true\" and info_dict.get(\"{}_verity_block_device\".format(partition_name))): partition_size",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"info_dict[\"{}_size\".format(partition_name)] fec_supported = info_dict.get(\"verity_fec\") == \"true\" generator = VerifiedBootVersion1HashtreeInfoGenerator( partition_size,",
"data. \"\"\" self.block_size = block_size self.partition_size = partition_size self.fec_supported =",
"# Build the verity tree and get the root hash",
"the calculated image size.\" \\ \" total_blocks: {}\".format(self.partition_size, image.total_blocks) adjusted_size",
"image size. \"\"\" if partition_size is None: partition_size = self.partition_size",
"Verified Boot 1.0 verity_supported = prop_dict.get(\"verity\") == \"true\" is_verity_partition =",
"self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd) generated_verity_tree = common.MakeTempFile(prefix=\"verity\") root_hash, salt = BuildVerityTree(adjusted_partition, generated_verity_tree)",
"self.AVB_HASH_FOOTER else \"add_hashtree_footer\") cmd = [self.avbtool, add_footer, \"--partition_size\", str(partition_size), \"--calc_max_image_size\"]",
"hash footer. if prop_dict.get(\"avb_hash_enable\") == \"true\": return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size,",
"partition_size, key_path, algorithm, signing_args): builder = None if info_dict.get(\"avb_enable\") ==",
"class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot 2.0.\"\"\" AVB_HASH_FOOTER =",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"open(target, 'ab') as out_file, \\ open(file_to_append, 'rb') as input_file: for",
"fec_supported): \"\"\"Initialize VerityTreeInfo with the sparse image and input property.",
"self.metadata_size) // self.block_size]) meta_data = b''.join(self.image.ReadRangeSet(metadata_range)) # More info about",
"assert partition_size > 0, \\ \"Invalid partition size: {}\".format(partition_size) hi",
"!= self.hashtree_info.root_hash: logger.warning( \"Calculated root hash %s doesn't match the",
"BLOCK_SIZE) * BLOCK_SIZE # verity tree and fec sizes depend",
"out_file: the output image. Returns: AssertionError: On invalid partition sizes.",
"to indicate a verity-enabled # partition. 'verity_block_device': '', # We",
"with open(adjusted_partition, \"wb\") as fd: self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd) generated_verity_tree = common.MakeTempFile(prefix=\"verity\")",
"result < i: result = i verity_size = v lo",
"0 self.filesystem_size = adjusted_size self.hashtree_size = verity_tree_size self.metadata_size = metadata_size",
"HashtreeInfo() def DecomposeSparseImage(self, image): \"\"\"Calculate the verity size based on",
"\"\"\" def CalculateMaxImageSize(self, partition_size): \"\"\"Calculates the filesystem image size for",
"depend on the partition size, which # means this estimate",
"hi = partition_size if hi % BLOCK_SIZE != 0: hi",
"in question. size_calculator: The function to calculate max image size",
"for verity metadata. \"\"\" if partition_size is None: partition_size =",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"root_hash != self.hashtree_info.root_hash: logger.warning( \"Calculated root hash %s doesn't match",
"pass def Build(self, out_file): \"\"\"Adds dm-verity hashtree and AVB metadata",
"at the following link. https://source.android.com/security/verifiedboot/dm-verity#implementation \"\"\" def CalculateMaxImageSize(self, partition_size): \"\"\"Calculates",
"verity_fec_path = os.path.join(tempdir_name, \"verity_fec.img\") BuildVerityFEC( out_file, verity_image_path, verity_fec_path, padding_size) Append(verity_image_path,",
"== \"true\", signer_path, prop_dict[\"verity_key\"] + \".pk8\", OPTIONS.verity_signer_args, \"verity_disable\" in prop_dict)",
"available in: # system/extras/verity/build_verity_metadata.py META_HEADER_SIZE = 268 header_bin = meta_data[0:META_HEADER_SIZE]",
"= common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityMetadataSize(image_size): cmd = [\"build_verity_metadata\",",
"generate the exact bytes of the hashtree. \"\"\" self.DecomposeSparseImage(image) self._ParseHashtreeMetadata()",
"maximum image size. Raises: BuildVerityImageError: On error or getting invalid",
"sparse_image_size > self.image_size: raise BuildVerityImageError( \"Error: image size of {}",
"+ BLOCK_SIZE logger.info( \"CalculateMinPartitionSize(%d): partition_size %d.\", image_size, partition_size) return partition_size",
"signing_args): builder = None if info_dict.get(\"avb_enable\") == \"true\": builder =",
"delta = BLOCK_SIZE max_image_size = size_calculator(hi) while max_image_size < image_size:",
"and fec sizes depend on the partition size, which #",
"size in bytes of each block for the sparse image.",
"specific language governing permissions and # limitations under the License.",
">= 0 # Build the full verified image. Append( verity_image_path,",
"the exact same bytes # as the one in the",
"one in metadata {}\".format( salt, self.hashtree_info.salt) if root_hash != self.hashtree_info.root_hash:",
"partition size: {}\".format(partition_size) add_footer = (\"add_hash_footer\" if self.footer_type == self.AVB_HASH_FOOTER",
"__init__(self, partition_name, partition_size, footer_type, avbtool, key_path, algorithm, salt, signing_args): self.version",
"'rb') as fd: return fd.read() == b''.join(self.image.ReadRangeSet( self.hashtree_info.hashtree_range)) def Generate(self,",
"= [self.avbtool, add_footer, \"--partition_size\", str(self.partition_size), \"--partition_name\", self.partition_name, \"--image\", out_file] if",
"if proc.returncode != 0: raise BuildVerityImageError(\"Failed to add AVB footer:",
"partition, which should be cover the given image size (for",
"< hi: mid = ((lo + hi) // (2 *",
"GetVerityTreeSize(image_size): cmd = [\"build_verity_tree\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False)",
"full verified image. Append( verity_image_path, verity_metadata_path, \"Failed to append verity",
"in metadata %s\", root_hash, self.hashtree_info.root_hash) return False # Reads the",
"and validates the hashtree info in a sparse image. Returns:",
"= [\"fec\", \"-e\", \"-p\", str(padding_size), sparse_image_path, verity_path, verity_fec_path] common.RunAndCheckOutput(cmd) def",
"larger than partition size of \" \"{}\".format(sparse_image_size, self.image_size)) ZeroPadSimg(out_file, self.image_size",
"size. lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE",
"= CreateVerityImageBuilder(prop_dict) self.hashtree_info = HashtreeInfo() def DecomposeSparseImage(self, image): \"\"\"Calculate the",
"VerityImageBuilder(object): \"\"\"A builder that generates an image with verity metadata",
"== 0 self.filesystem_size = adjusted_size self.hashtree_size = verity_tree_size self.metadata_size =",
"# you may not use this file except in compliance",
"Path to image to modify. \"\"\" add_footer = (\"add_hash_footer\" if",
"out_file, \\ open(file_to_append, 'rb') as input_file: for line in input_file:",
"returned based on the given build properties. More info on",
"filesystem files) as well as the verity metadata size. Args:",
"the one in metadata {}\".format( salt, self.hashtree_info.salt) if root_hash !=",
"verity_tree_size = GetVerityTreeSize(adjusted_size) assert verity_tree_size % self.block_size == 0 metadata_size",
"magic_number, version, signature, table_len assert header[0] == 0xb001b001, header[0] table_len",
"size, which defaults to self.partition_size if unspecified. Returns: The maximum",
"partition_size = hi # Start to binary search. while lo",
"\\ \"partition size {} doesn't match with the calculated image",
"Verified Boot 2.0. A matching builder will be returned based",
"question. size_calculator: The function to calculate max image size for",
"the verity hash tree.\"\"\" # Writes the filesystem section to",
"// self.block_size]) meta_data = b''.join(self.image.ReadRangeSet(metadata_range)) # More info about the",
"common.MakeTempFile(prefix=\"adjusted_partition\") with open(adjusted_partition, \"wb\") as fd: self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd) generated_verity_tree =",
"as well as the verity metadata size. Args: image_size: The",
"= verity_tree_size + verity_metadata_size if fec_supported: fec_size = GetVerityFECSize(image_size +",
"indicate a verity-enabled # partition. 'verity_block_device': '', # We don't",
"= logging.getLogger(__name__) OPTIONS = common.OPTIONS BLOCK_SIZE = common.BLOCK_SIZE FIXED_SALT =",
"between Verified Boot 1.0 and Verified Boot 2.0. A matching",
"data_blocks hash_algorithm root_hash salt\" assert len(table_entries) == 10, \"Unexpected verity",
"= common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityTreeSize(image_size): cmd = [\"build_verity_tree\",",
"verity_disable): self.version = 1 self.partition_size = partition_size self.block_device = block_dev",
"Args: prop_dict: A dict that contains the build properties. In",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"size_calculator(mid) if max_image_size >= image_size: # if mid can accommodate",
"prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hashtree_footer_args\"]) return None class VerityImageBuilder(object): \"\"\"A builder that generates",
"return verity_size def GetSimgSize(image_file): simg = sparse_img.SparseImage(image_file, build_map=False) return simg.blocksize",
"(%d bytes)\", blocks, pad_size) simg = sparse_img.SparseImage(image_file, mode=\"r+b\", build_map=False) simg.AppendFillChunk(0,",
"each section. \"\"\" self.image = image assert self.block_size == image.blocksize",
"and writes it to the given file.\"\"\" raise NotImplementedError class",
"= RangeSet( data=[0, adjusted_size // self.block_size]) self.hashtree_info.hashtree_range = RangeSet( data=[adjusted_size",
"raised during hashtree info generation.\"\"\" def __init__(self, message): Exception.__init__(self, message)",
"is used. key_path = prop_dict.get(\"avb_key_path\") algorithm = prop_dict.get(\"avb_algorithm\") # Image",
"the partition size, which # means this estimate is always",
"append verity data\") def PadSparseImage(self, out_file): sparse_image_size = GetSimgSize(out_file) if",
"= table_entries[8].decode() self.hashtree_info.salt = table_entries[9].decode() def ValidateHashtree(self): \"\"\"Checks that we",
"int(output) def GetVerityTreeSize(image_size): cmd = [\"build_verity_tree\", \"-s\", str(image_size)] output =",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"verity_tree_size = GetVerityTreeSize(image_size) verity_metadata_size = GetVerityMetadataSize(image_size) verity_size = verity_tree_size +",
"root hash %s doesn't match the one in metadata %s\",",
"A dict that contains the build properties. In particular, it",
"key_path, algorithm, salt, signing_args): self.version = 2 self.partition_name = partition_name",
"a binary search for the optimal partition size. lo =",
"FEC\") Append2Simg( out_file, verity_image_path, \"Failed to append verity data\") def",
"avbtool, key_path, algorithm, salt, signing_args): self.version = 2 self.partition_name =",
"Append(target, file_to_append, error_message): \"\"\"Appends file_to_append to target. Raises: BuildVerityImageError: On",
"else None, # 'verity_block_device' needs to be present to indicate",
"on the size of the input image. Since we already",
"will be returned based on the given build properties. More",
"= mid hi = mid else: lo = mid +",
"fec_supported) return generator class HashtreeInfoGenerator(object): def Generate(self, image): raise NotImplementedError",
"image_size: The size of the image in question. size_calculator: The",
"# as the one in the sparse image. with open(generated_verity_tree,",
"= ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE",
"logger.exception(error_message) raise BuildVerityImageError(error_message) def CreateVerityImageBuilder(prop_dict): \"\"\"Returns a verity image builder",
"with open(generated_verity_tree, 'rb') as fd: return fd.read() == b''.join(self.image.ReadRangeSet( self.hashtree_info.hashtree_range))",
"at this point, if using dynamic partitions. if partition_size: partition_size",
"Get partial image paths. verity_image_path = os.path.join(tempdir_name, \"verity.img\") verity_metadata_path =",
"partition size. image_ratio = size_calculator(image_size) / float(image_size) # Prepare a",
"partition, including the filesystem size, padding size, and verity size.",
"= os.path.join(tempdir_name, \"verity_fec.img\") BuildVerityFEC( out_file, verity_image_path, verity_fec_path, padding_size) Append(verity_image_path, verity_fec_path,",
"size.\"\"\" raise NotImplementedError def CalculateDynamicPartitionSize(self, image_size): \"\"\"Calculates and sets the",
"bytes)\", blocks, pad_size) simg = sparse_img.SparseImage(image_file, mode=\"r+b\", build_map=False) simg.AppendFillChunk(0, blocks)",
"verity_image_path, verity_metadata_path, \"Failed to append verity metadata\") if self.fec_supported: #",
"__init__(self, partition_size, block_dev, fec_supported, signer_path, signer_key, signer_args, verity_disable): self.version =",
"support Verified Boot. \"\"\" partition_size = prop_dict.get(\"partition_size\") # partition_size could",
"\"verity_fec.img\") BuildVerityFEC( out_file, verity_image_path, verity_fec_path, padding_size) Append(verity_image_path, verity_fec_path, \"Failed to",
"= meta_data[META_HEADER_SIZE: META_HEADER_SIZE + table_len] table_entries = verity_table.rstrip().split() # Expected",
"as it will fail later. raise NotImplementedError def CalculateMaxImageSize(self, partition_size=None):",
"that generates an image with verity metadata for Verified Boot.",
"algorithm are only available when chain partition is used. key_path",
"# 'verity_block_device' needs to be present to indicate a verity-enabled",
"= common.Run(cmd) output, _ = proc.communicate() if proc.returncode != 0:",
"verity_disable: cmd.append(\"--verity_disable\") common.RunAndCheckOutput(cmd) def Append2Simg(sparse_image_path, unsparse_image_path, error_message): \"\"\"Appends the unsparse",
"target. Raises: BuildVerityImageError: On error. \"\"\" try: with open(target, 'ab')",
"sets the partition size for a dynamic partition.\"\"\" raise NotImplementedError",
"None def CalculateDynamicPartitionSize(self, image_size): # This needs to be implemented.",
"size. This is used when determining the partition size for",
"if proc.returncode != 0: raise BuildVerityImageError( \"Failed to calculate max",
"return simg.blocksize * simg.total_blocks def ZeroPadSimg(image_file, pad_size): blocks = pad_size",
"= int(partition_size) # Verified Boot 1.0 verity_supported = prop_dict.get(\"verity\") ==",
"cmd = [\"fec\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return",
"BuildVerityImageError(Exception): \"\"\"An Exception raised during verity image building.\"\"\" def __init__(self,",
"properties. Args: prop_dict: A dict that contains the build properties.",
"\"true\": builder = VerifiedBootVersion2VerityImageBuilder( partition_name, partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get(\"avb_avbtool\"), key_path, algorithm,",
"partition.\"\"\" def __init__(self, partition_size, block_size, fec_supported): \"\"\"Initialize VerityTreeInfo with the",
"footer_type self.avbtool = avbtool self.algorithm = algorithm self.key_path = key_path",
"%s doesn't match the one in metadata %s\", root_hash, self.hashtree_info.root_hash)",
"size required to accommodate the image size. \"\"\" if size_calculator",
"self.key_path = key_path self.salt = salt self.signing_args = signing_args self.image_size",
"size_calculator=None): \"\"\"Calculates min partition size for a given image size.",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"== 0xb001b001, header[0] table_len = header[3] verity_table = meta_data[META_HEADER_SIZE: META_HEADER_SIZE",
"# More info about the metadata structure available in: #",
"self.partition_size def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates max image size for a",
"= i self.image_size = result self.verity_size = verity_size logger.info( \"Calculated",
"BuildVerityTree(out_file, verity_image_path) # Build the metadata blocks. BuildVerityMetadata( image_size, verity_metadata_path,",
"taken care of by avbtool. pass def Build(self, out_file): \"\"\"Adds",
"else \"add_hashtree_footer\") cmd = [self.avbtool, add_footer, \"--partition_size\", str(self.partition_size), \"--partition_name\", self.partition_name,",
"metadata structure available in: # system/extras/verity/build_verity_metadata.py META_HEADER_SIZE = 268 header_bin",
"self.hashtree_size = verity_tree_size self.metadata_size = metadata_size self.hashtree_info.filesystem_range = RangeSet( data=[0,",
"can accommodate image_size if mid < partition_size: # if a",
"image with verity metadata for Verified Boot. A VerityImageBuilder instance",
"self.partition_size = partition_size self.footer_type = footer_type self.avbtool = avbtool self.algorithm",
"# Image uses hashtree footer. return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER,",
"% (' '.join(signer_args),)) if verity_disable: cmd.append(\"--verity_disable\") common.RunAndCheckOutput(cmd) def Append2Simg(sparse_image_path, unsparse_image_path,",
"table format: \"1 block_device block_device block_size # block_size data_blocks data_blocks",
"and is_verity_partition: if OPTIONS.verity_signer_path is not None: signer_path = OPTIONS.verity_signer_path",
"meta_data[META_HEADER_SIZE: META_HEADER_SIZE + table_len] table_entries = verity_table.rstrip().split() # Expected verity",
"if it has the exact same bytes # as the",
"in prop_dict if verity_supported and is_verity_partition: if OPTIONS.verity_signer_path is not",
"/ float(lo) lo = int(image_size / image_ratio) // BLOCK_SIZE *",
"image.\"\"\" raise NotImplementedError def Build(self, out_file): \"\"\"Builds the verity image",
"\"-e\", \"-p\", str(padding_size), sparse_image_path, verity_path, verity_fec_path] common.RunAndCheckOutput(cmd) def BuildVerityTree(sparse_image_path, verity_image_path):",
"BLOCK_SIZE)) * BLOCK_SIZE max_image_size = size_calculator(mid) if max_image_size >= image_size:",
"the partition size for a dynamic partition.\"\"\" raise NotImplementedError def",
"import shlex import struct import common import sparse_img from rangelib",
"size of the input image. Since we already know the",
"self.DecomposeSparseImage(image) self._ParseHashtreeMetadata() if not self.ValidateHashtree(): raise HashtreeInfoGenerationError(\"Failed to reconstruct the",
"given image size. This is used when determining the partition",
"and calls the executable # build_verity_tree to construct the hash",
"GetVerityTreeSize(adjusted_size) assert verity_tree_size % self.block_size == 0 metadata_size = GetVerityMetadataSize(adjusted_size)",
"* BLOCK_SIZE max_image_size = size_calculator(mid) if max_image_size >= image_size: #",
"* BLOCK_SIZE)) * BLOCK_SIZE max_image_size = size_calculator(mid) if max_image_size >=",
"image size. \"\"\" if size_calculator is None: size_calculator = self.CalculateMaxImageSize",
"given build properties. Args: prop_dict: A dict that contains the",
"custom images have no fingerprint property to be # used",
"image size by accounting for the verity metadata. Args: partition_size:",
"given partition size. Args: partition_size: The partition size, which defaults",
"fd: return fd.read() == b''.join(self.image.ReadRangeSet( self.hashtree_info.hashtree_range)) def Generate(self, image): \"\"\"Parses",
"mid can accommodate image_size if mid < partition_size: # if",
"= GetVeritySize(hi, self.fec_supported) lo = partition_size - verity_size result =",
"signer_path, key] if signer_args: cmd.append(\"--signer_args=\\\"%s\\\"\" % (' '.join(signer_args),)) if verity_disable:",
"v = GetVeritySize(i, self.fec_supported) if i + v <= partition_size:",
"verity enabled image to be: [filesystem, verity_hashtree, verity_metadata, fec_data]. We",
"signer_path = prop_dict[\"verity_signer_cmd\"] return Version1VerityImageBuilder( partition_size, prop_dict[\"verity_block_device\"], prop_dict.get(\"verity_fec\") == \"true\",",
"\"wb\") as fd: self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd) generated_verity_tree = common.MakeTempFile(prefix=\"verity\") root_hash, salt",
"message): Exception.__init__(self, message) def GetVerityFECSize(image_size): cmd = [\"fec\", \"-s\", str(image_size)]",
"hashtree footer. return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm,",
"def DecomposeSparseImage(self, image): raise NotImplementedError def ValidateHashtree(self): raise NotImplementedError class",
"on the given build properties. Args: prop_dict: A dict that",
"NotImplementedError class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator): \"\"\"A class that parses the metadata of",
"size, and verity size. block_size: Expected size in bytes of",
"def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt, block_device, signer_path, key, signer_args, verity_disable):",
"the image adjusted for verity metadata. \"\"\" if partition_size is",
"i + v <= partition_size: if result < i: result",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE # Ensure lo is small",
"a smaller partition size is found partition_size = mid hi",
"a temp file; and calls the executable # build_verity_tree to",
"# if mid can accommodate image_size if mid < partition_size:",
"{}\".format(self.partition_size, image.total_blocks) adjusted_size = self.verity_image_builder.CalculateMaxImageSize() assert adjusted_size % self.block_size ==",
"If we fail to generate the exact bytes of the",
"= self.partition_size assert partition_size > 0, \\ \"Invalid partition size:",
"hi = i self.image_size = result self.verity_size = verity_size logger.info(",
"self.verity_disable) padding_size = self.partition_size - self.image_size - self.verity_size assert padding_size",
"metadata. 'verity_key': '', 'verity_signer_cmd': None, } self.verity_image_builder = CreateVerityImageBuilder(prop_dict) self.hashtree_info",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"= result self.verity_size = verity_size logger.info( \"Calculated image size for",
"either express or implied. # See the License for the",
"None: signer_path = OPTIONS.verity_signer_path else: signer_path = prop_dict[\"verity_signer_cmd\"] return Version1VerityImageBuilder(",
"present to indicate a verity-enabled # partition. 'verity_block_device': '', #",
"always going to be unnecessarily small verity_size = GetVeritySize(hi, self.fec_supported)",
"footer. return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"),",
"The function to calculate max image size for a given",
"2 self.partition_name = partition_name self.partition_size = partition_size self.footer_type = footer_type",
"str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityMetadataSize(image_size): cmd",
"self.signing_args = signing_args self.image_size = None def CalculateMinPartitionSize(self, image_size, size_calculator=None):",
"algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hash_footer_args\"]) # Image uses hashtree footer. return VerifiedBootVersion2VerityImageBuilder(",
"= size_calculator(hi) partition_size = hi # Start to binary search.",
"partition_size = info_dict[\"{}_size\".format(partition_name)] fec_supported = info_dict.get(\"verity_fec\") == \"true\" generator =",
"// self.block_size]) self.hashtree_info.hashtree_range = RangeSet( data=[adjusted_size // self.block_size, (adjusted_size +",
"CreateVerityImageBuilder(prop_dict): \"\"\"Returns a verity image builder based on the given",
"if i + v <= partition_size: if result < i:",
"= self.CalculateMinPartitionSize(image_size) return self.partition_size def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates max image",
"= common.MakeTempFile(prefix=\"adjusted_partition\") with open(adjusted_partition, \"wb\") as fd: self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range, fd) generated_verity_tree",
"partition_size > 0, \\ \"Invalid partition size: {}\".format(partition_size) add_footer =",
"self.filesystem_size = None self.hashtree_size = None self.metadata_size = None prop_dict",
"verity_supported = prop_dict.get(\"verity\") == \"true\" is_verity_partition = \"verity_block_device\" in prop_dict",
"prop_dict.get(\"avb_hash_enable\") == \"true\": return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict[\"avb_avbtool\"], key_path,",
"*= 2 max_image_size = size_calculator(hi) partition_size = hi # Start",
"= None if info_dict.get(\"avb_enable\") == \"true\": builder = VerifiedBootVersion2VerityImageBuilder( partition_name,",
"padding_size >= 0 # Build the full verified image. Append(",
"= info_dict.get(\"verity_fec\") == \"true\" generator = VerifiedBootVersion1HashtreeInfoGenerator( partition_size, block_size, fec_supported)",
"partitions. if partition_size: partition_size = int(partition_size) # Verified Boot 1.0",
"footer. if prop_dict.get(\"avb_hash_enable\") == \"true\": return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER,",
"input image. Since we already know the structure of a",
"mid = ((lo + hi) // (2 * BLOCK_SIZE)) *",
"mode=\"r+b\", build_map=False) simg.AppendFillChunk(0, blocks) def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path, padding_size): cmd",
"unsparse_image_path] try: common.RunAndCheckOutput(cmd) except: logger.exception(error_message) raise BuildVerityImageError(error_message) def Append(target, file_to_append,",
"Verified Boot. A VerityImageBuilder instance handles the works for building",
"modify. \"\"\" add_footer = (\"add_hash_footer\" if self.footer_type == self.AVB_HASH_FOOTER else",
"key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hashtree_footer_args\"]) return None class VerityImageBuilder(object): \"\"\"A builder",
"of the input image. Since we already know the structure",
"max image size for a given partition size. Returns: The",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"verity_metadata_path, root_hash, salt, block_device, signer_path, key] if signer_args: cmd.append(\"--signer_args=\\\"%s\\\"\" %",
"\"{}\".format(sparse_image_size, self.image_size)) ZeroPadSimg(out_file, self.image_size - sparse_image_size) class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder",
"def CalculateDynamicPartitionSize(self, image_size): # This needs to be implemented. Note",
"Exception.__init__(self, message) class HashtreeInfo(object): def __init__(self): self.hashtree_range = None self.filesystem_range",
"doesn't support Verified Boot. \"\"\" partition_size = prop_dict.get(\"partition_size\") # partition_size",
"# block_size data_blocks data_blocks hash_algorithm root_hash salt\" assert len(table_entries) ==",
"point, if using dynamic partitions. if partition_size: partition_size = int(partition_size)",
"image_ratio = max_image_size / float(hi) hi = int(image_size / image_ratio)",
"table_entries[8].decode() self.hashtree_info.salt = table_entries[9].decode() def ValidateHashtree(self): \"\"\"Checks that we can",
"= None self.root_hash = None def CreateHashtreeInfoGenerator(partition_name, block_size, info_dict): generator",
"logging import os.path import shlex import struct import common import",
"%d, image_size %d, \" \"verity_size %d\", partition_size, result, verity_size) return",
"% BLOCK_SIZE != 0: hi = (hi // BLOCK_SIZE) *",
"ValidateHashtree(self): raise NotImplementedError class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator): \"\"\"A class that parses the",
"\"--partition_name\", self.partition_name, \"--image\", out_file] if self.key_path and self.algorithm: cmd.extend([\"--key\", self.key_path,",
"= block_size self.partition_size = partition_size self.fec_supported = fec_supported self.image =",
"image adjusted for verity metadata. \"\"\" if partition_size is None:",
"if info_dict.get(\"avb_enable\") == \"true\": builder = VerifiedBootVersion2VerityImageBuilder( partition_name, partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER,",
"AVB_HASHTREE_FOOTER = 2 def __init__(self, partition_name, partition_size, footer_type, avbtool, key_path,",
"add_footer, \"--partition_size\", str(self.partition_size), \"--partition_name\", self.partition_name, \"--image\", out_file] if self.key_path and",
"BLOCK_SIZE - BLOCK_SIZE # Ensure lo is small enough: max_image_size",
"0: raise BuildVerityImageError( \"Invalid max image size: {}\".format(output)) self.image_size =",
"partition_size, block_dev, fec_supported, signer_path, signer_key, signer_args, verity_disable): self.version = 1",
"raise BuildVerityImageError(error_message) def CreateVerityImageBuilder(prop_dict): \"\"\"Returns a verity image builder based",
"image to the given sparse image. Args: sparse_image_path: the path",
"self.partition_size = partition_size self.block_device = block_dev self.fec_supported = fec_supported self.signer_path",
"in prop_dict) # Verified Boot 2.0 if (prop_dict.get(\"avb_hash_enable\") == \"true\"",
"== \"true\" and info_dict.get(\"{}_verity_block_device\".format(partition_name))): partition_size = info_dict[\"{}_size\".format(partition_name)] fec_supported = info_dict.get(\"verity_fec\")",
"self.filesystem_size = adjusted_size self.hashtree_size = verity_tree_size self.metadata_size = metadata_size self.hashtree_info.filesystem_range",
"metadata_range = RangeSet( data=[metadata_start // self.block_size, (metadata_start + self.metadata_size) //",
"int(table_entries[6]) * self.block_size == self.filesystem_size) self.hashtree_info.hash_algorithm = table_entries[7].decode() self.hashtree_info.root_hash =",
"str(padding_size), sparse_image_path, verity_path, verity_fec_path] common.RunAndCheckOutput(cmd) def BuildVerityTree(sparse_image_path, verity_image_path): cmd =",
"def CalculateDynamicPartitionSize(self, image_size): \"\"\"Calculates and sets the partition size for",
"image_size. delta = BLOCK_SIZE max_image_size = size_calculator(hi) while max_image_size <",
"padding_size = self.partition_size - self.image_size - self.verity_size assert padding_size >=",
"avbtool. pass def Build(self, out_file): \"\"\"Adds dm-verity hashtree and AVB",
"+ verity_metadata_size if fec_supported: fec_size = GetVerityFECSize(image_size + verity_size) return",
"fec_supported): verity_tree_size = GetVerityTreeSize(image_size) verity_metadata_size = GetVerityMetadataSize(image_size) verity_size = verity_tree_size",
"# Expected verity table format: \"1 block_device block_device block_size #",
"salt {} doesn't match the one in metadata {}\".format( salt,",
"prop_dict[\"verity_block_device\"], prop_dict.get(\"verity_fec\") == \"true\", signer_path, prop_dict[\"verity_key\"] + \".pk8\", OPTIONS.verity_signer_args, \"verity_disable\"",
"Build the metadata blocks. BuildVerityMetadata( image_size, verity_metadata_path, root_hash, salt, self.block_device,",
"given partition size.\"\"\" raise NotImplementedError def CalculateDynamicPartitionSize(self, image_size): \"\"\"Calculates and",
"# Verified Boot 2.0 if (prop_dict.get(\"avb_hash_enable\") == \"true\" or prop_dict.get(\"avb_hashtree_enable\")",
"= RangeSet( data=[metadata_start // self.block_size, (metadata_start + self.metadata_size) // self.block_size])",
"(hi // BLOCK_SIZE) * BLOCK_SIZE # verity tree and fec",
"struct import common import sparse_img from rangelib import RangeSet logger",
"supporting Android Verified Boot. This class defines the common interface",
"block_size, fec_supported) return generator class HashtreeInfoGenerator(object): def Generate(self, image): raise",
"None at this point, if using dynamic partitions. if partition_size:",
"< image_size: image_ratio = max_image_size / float(hi) hi = int(image_size",
"= GetVerityTreeSize(adjusted_size) assert verity_tree_size % self.block_size == 0 metadata_size =",
"to add AVB footer: {}\".format(output)) class HashtreeInfoGenerationError(Exception): \"\"\"An Exception raised",
"for Verified Boot 1.0.\"\"\" def __init__(self, partition_size, block_dev, fec_supported, signer_path,",
"== image.total_blocks * self.block_size, \\ \"partition size {} doesn't match",
"# This needs to be implemented. Note that returning the",
"the works for building an image with verity metadata for",
"reconstruct the verity tree\") return self.hashtree_info def CreateCustomImageBuilder(info_dict, partition_name, partition_size,",
"tree\") return self.hashtree_info def CreateCustomImageBuilder(info_dict, partition_name, partition_size, key_path, algorithm, signing_args):",
"going to be unnecessarily small verity_size = GetVeritySize(hi, self.fec_supported) lo",
"under the License. from __future__ import print_function import logging import",
"= None def CalculateDynamicPartitionSize(self, image_size): # This needs to be",
"to be implemented. Note that returning the given image size",
"return int(output) def GetVeritySize(image_size, fec_supported): verity_tree_size = GetVerityTreeSize(image_size) verity_metadata_size =",
"\"\"\"Calculates the filesystem image size for the given partition size.\"\"\"",
"use this file except in compliance with the License. #",
"based on the given build properties. Args: prop_dict: A dict",
"2.0. A matching builder will be returned based on the",
"// BLOCK_SIZE) * BLOCK_SIZE # verity tree and fec sizes",
"str(image_size), verity_metadata_path, root_hash, salt, block_device, signer_path, key] if signer_args: cmd.append(\"--signer_args=\\\"%s\\\"\"",
"import sparse_img from rangelib import RangeSet logger = logging.getLogger(__name__) OPTIONS",
"lo = partition_size - verity_size result = lo # do",
"common.OPTIONS BLOCK_SIZE = common.BLOCK_SIZE FIXED_SALT = \"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\" class BuildVerityImageError(Exception): \"\"\"An",
"self.block_size]) def _ParseHashtreeMetadata(self): \"\"\"Parses the hash_algorithm, root_hash, salt from the",
"\\ \" total_blocks: {}\".format(self.partition_size, image.total_blocks) adjusted_size = self.verity_image_builder.CalculateMaxImageSize() assert adjusted_size",
"_ParseHashtreeMetadata(self): \"\"\"Parses the hash_algorithm, root_hash, salt from the metadata block.\"\"\"",
"only available when chain partition is used. key_path = prop_dict.get(\"avb_key_path\")",
"partition size. Returns: The minimum partition size required to accommodate",
"\"\"\"A class that parses the metadata of hashtree for a",
"properties. More info on the verity image generation can be",
"print_function import logging import os.path import shlex import struct import",
"given image size as # the partition size doesn't make",
"logger.info(\"Padding %d blocks (%d bytes)\", blocks, pad_size) simg = sparse_img.SparseImage(image_file,",
"that are needed for signing the # verity metadata. 'verity_key':",
"raise NotImplementedError def Build(self, out_file): \"\"\"Builds the verity image and",
"verity_tree_size self.metadata_size = metadata_size self.hashtree_info.filesystem_range = RangeSet( data=[0, adjusted_size //",
"can be found at the following link. https://source.android.com/security/verifiedboot/dm-verity#implementation \"\"\" def",
"image size for the given partition size.\"\"\" raise NotImplementedError def",
"NotImplementedError class Version1VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot 1.0.\"\"\" def",
"self.hashtree_range = None self.filesystem_range = None self.hash_algorithm = None self.salt",
"assert salt == self.hashtree_info.salt, \\ \"Calculated salt {} doesn't match",
"self.hashtree_info.hashtree_range = RangeSet( data=[adjusted_size // self.block_size, (adjusted_size + verity_tree_size) //",
"as fd: return fd.read() == b''.join(self.image.ReadRangeSet( self.hashtree_info.hashtree_range)) def Generate(self, image):",
"partition_size = prop_dict.get(\"partition_size\") # partition_size could be None at this",
"size based on the size of the input image. Since",
"and input property. Arguments: partition_size: The whole size in bytes",
"import print_function import logging import os.path import shlex import struct",
"2 max_image_size = size_calculator(hi) partition_size = hi # Start to",
"to be: [filesystem, verity_hashtree, verity_metadata, fec_data]. We can then calculate",
"size: {}\".format(partition_size) add_footer = (\"add_hash_footer\" if self.footer_type == self.AVB_HASH_FOOTER else",
"Ensure hi is large enough: max_image_size should >= image_size. delta",
"and algorithm are only available when chain partition is used.",
"self.verity_size assert padding_size >= 0 # Build the full verified",
"# partition_size could be None at this point, if using",
"= signer_args self.verity_disable = verity_disable self.image_size = None self.verity_size =",
"= None prop_dict = { 'partition_size': str(partition_size), 'verity': 'true', 'verity_fec':",
"= size_calculator(lo) while max_image_size > image_size: image_ratio = max_image_size /",
"in compliance with the License. # You may obtain a",
"errors. \"\"\" image_size = int(self.image_size) tempdir_name = common.MakeTempDir(suffix=\"_verity_images\") # Get",
"and info_dict.get(\"{}_verity_block_device\".format(partition_name))): partition_size = info_dict[\"{}_size\".format(partition_name)] fec_supported = info_dict.get(\"verity_fec\") == \"true\"",
"by avbtool. pass def Build(self, out_file): \"\"\"Adds dm-verity hashtree and",
"software # distributed under the License is distributed on an",
"simg.AppendFillChunk(0, blocks) def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path, padding_size): cmd = [\"fec\",",
"paths. verity_image_path = os.path.join(tempdir_name, \"verity.img\") verity_metadata_path = os.path.join(tempdir_name, \"verity_metadata.img\") #",
"verity_image_path, verity_fec_path, padding_size) Append(verity_image_path, verity_fec_path, \"Failed to append FEC\") Append2Simg(",
"max_image_size >= image_size: # if mid can accommodate image_size if",
"self._ParseHashtreeMetadata() if not self.ValidateHashtree(): raise HashtreeInfoGenerationError(\"Failed to reconstruct the verity",
"= lo + BLOCK_SIZE # Ensure hi is large enough:",
"__init__(self): self.hashtree_range = None self.filesystem_range = None self.hash_algorithm = None",
"an image with verity metadata for supporting Android Verified Boot.",
"if partition_size is None: partition_size = self.partition_size assert partition_size >",
"= signer_path self.signer_key = signer_key self.signer_args = signer_args self.verity_disable =",
"doesn't make sense, as it will fail later. raise NotImplementedError",
"= max_image_size / float(lo) lo = int(image_size / image_ratio) //",
"the given image size as # the partition size doesn't",
"Project # # Licensed under the Apache License, Version 2.0",
"if sparse_image_size > self.image_size: raise BuildVerityImageError( \"Error: image size of",
"verity_size logger.info( \"Calculated image size for verity: partition_size %d, image_size",
"cmd = [self.avbtool, add_footer, \"--partition_size\", str(partition_size), \"--calc_max_image_size\"] cmd.extend(shlex.split(self.signing_args)) proc =",
"self.block_size == self.filesystem_size) self.hashtree_info.hash_algorithm = table_entries[7].decode() self.hashtree_info.root_hash = table_entries[8].decode() self.hashtree_info.salt",
"table_entries[7].decode() self.hashtree_info.root_hash = table_entries[8].decode() self.hashtree_info.salt = table_entries[9].decode() def ValidateHashtree(self): \"\"\"Checks",
"common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityMetadataSize(image_size): cmd = [\"build_verity_metadata\", \"size\",",
"to image to modify. \"\"\" add_footer = (\"add_hash_footer\" if self.footer_type",
"= common.MakeTempDir(suffix=\"_verity_images\") # Get partial image paths. verity_image_path = os.path.join(tempdir_name,",
"block_dev, fec_supported, signer_path, signer_key, signer_args, verity_disable): self.version = 1 self.partition_size",
"are needed for signing the # verity metadata. 'verity_key': '',",
"BLOCK_SIZE * BLOCK_SIZE + delta delta *= 2 max_image_size =",
"size for verity: partition_size %d, image_size %d, \" \"verity_size %d\",",
"dynamic partition.\"\"\" raise NotImplementedError def PadSparseImage(self, out_file): \"\"\"Adds padding to",
"BLOCK_SIZE logger.info( \"CalculateMinPartitionSize(%d): partition_size %d.\", image_size, partition_size) return partition_size def",
"partition. 'verity_block_device': '', # We don't need the following properties",
"= partition_size self.fec_supported = fec_supported self.image = None self.filesystem_size =",
"The size of the image adjusted for verity metadata. \"\"\"",
"# Get partial image paths. verity_image_path = os.path.join(tempdir_name, \"verity.img\") verity_metadata_path",
"final partition size. image_ratio = size_calculator(image_size) / float(image_size) # Prepare",
"image unsparse_image_path: the path to the (unsparse) image Raises: BuildVerityImageError:",
"prop_dict if verity_supported and is_verity_partition: if OPTIONS.verity_signer_path is not None:",
"* BLOCK_SIZE)) * BLOCK_SIZE v = GetVeritySize(i, self.fec_supported) if i",
"- BLOCK_SIZE # Ensure lo is small enough: max_image_size should",
"the size of the input image. Since we already know",
"Copyright (C) 2018 The Android Open Source Project # #",
"% self.block_size == 0 self.filesystem_size = adjusted_size self.hashtree_size = verity_tree_size",
"a dynamic partition.\"\"\" raise NotImplementedError def PadSparseImage(self, out_file): \"\"\"Adds padding",
"search for the optimal size while lo < hi: i",
"((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE max_image_size",
"because custom images have no fingerprint property to be #",
"* self.block_size, \\ \"partition size {} doesn't match with the",
"as the one in the sparse image. with open(generated_verity_tree, 'rb')",
"partition size. lo = int(image_size / image_ratio) // BLOCK_SIZE *",
"= lo # do a binary search for the optimal",
"> 0, \\ \"Invalid partition size: {}\".format(partition_size) hi = partition_size",
"raised during verity image building.\"\"\" def __init__(self, message): Exception.__init__(self, message)",
"needs to be present to indicate a verity-enabled # partition.",
"when chain partition is used. key_path = prop_dict.get(\"avb_key_path\") algorithm =",
"> 0, \\ \"Invalid partition size: {}\".format(partition_size) add_footer = (\"add_hash_footer\"",
"of by avbtool. pass def Build(self, out_file): \"\"\"Adds dm-verity hashtree",
"proc.communicate() if proc.returncode != 0: raise BuildVerityImageError(\"Failed to add AVB",
"int(output) if image_size <= 0: raise BuildVerityImageError( \"Invalid max image",
"[\"build_verity_tree\", \"-A\", FIXED_SALT, sparse_image_path, verity_image_path] output = common.RunAndCheckOutput(cmd) root, salt",
"return Version1VerityImageBuilder( partition_size, prop_dict[\"verity_block_device\"], prop_dict.get(\"verity_fec\") == \"true\", signer_path, prop_dict[\"verity_key\"] +",
"and AVB metadata to an image. Args: out_file: Path to",
"0 metadata_size = GetVerityMetadataSize(adjusted_size) assert metadata_size % self.block_size == 0",
"with the License. # You may obtain a copy of",
"raise NotImplementedError def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates the max image size",
"it will fail later. raise NotImplementedError def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates",
">= image_size. delta = BLOCK_SIZE max_image_size = size_calculator(hi) while max_image_size",
"partition_name, partition_size, key_path, algorithm, signing_args): builder = None if info_dict.get(\"avb_enable\")",
"and verity size. block_size: Expected size in bytes of each",
"= self.partition_size - self.image_size - self.verity_size assert padding_size >= 0",
"self.image_size - self.verity_size assert padding_size >= 0 # Build the",
"import os.path import shlex import struct import common import sparse_img",
"salt == self.hashtree_info.salt, \\ \"Calculated salt {} doesn't match the",
"'verity': 'true', 'verity_fec': 'true' if fec_supported else None, # 'verity_block_device'",
"def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates the max image size by accounting",
"None prop_dict = { 'partition_size': str(partition_size), 'verity': 'true', 'verity_fec': 'true'",
"later. raise NotImplementedError def CalculateMaxImageSize(self, partition_size=None): \"\"\"Calculates the max image",
"assert adjusted_size % self.block_size == 0 verity_tree_size = GetVerityTreeSize(adjusted_size) assert",
"GetVeritySize(i, self.fec_supported) if i + v <= partition_size: if result",
"calculate max image size for a given partition size. Returns:",
"\"CalculateMinPartitionSize(%d): partition_size %d.\", image_size, partition_size) return partition_size def CalculateDynamicPartitionSize(self, image_size):",
"self.hashtree_size = None self.metadata_size = None prop_dict = { 'partition_size':",
"algorithm, salt, signing_args): self.version = 2 self.partition_name = partition_name self.partition_size",
"== self.AVB_HASH_FOOTER else \"add_hashtree_footer\") cmd = [self.avbtool, add_footer, \"--partition_size\", str(self.partition_size),",
"prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hash_footer_args\"]) # Image",
"be always identical, as we use fixed value. assert salt",
"partition_size) return partition_size def CalculateDynamicPartitionSize(self, image_size): self.partition_size = self.CalculateMinPartitionSize(image_size) return",
"express or implied. # See the License for the specific",
"except in compliance with the License. # You may obtain",
"AVB_HASH_FOOTER = 1 AVB_HASHTREE_FOOTER = 2 def __init__(self, partition_name, partition_size,",
"signer_key, signer_args, verity_disable): self.version = 1 self.partition_size = partition_size self.block_device",
"search for the optimal partition size. lo = int(image_size /",
"def _ParseHashtreeMetadata(self): \"\"\"Parses the hash_algorithm, root_hash, salt from the metadata",
"unspecified. Returns: The maximum image size. Raises: BuildVerityImageError: On error",
"Args: out_file: the output image. Returns: AssertionError: On invalid partition",
"= \"verity_block_device\" in prop_dict if verity_supported and is_verity_partition: if OPTIONS.verity_signer_path",
"verity_metadata_path = os.path.join(tempdir_name, \"verity_metadata.img\") # Build the verity tree and",
"the path to the (unsparse) image Raises: BuildVerityImageError: On error.",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"doesn't match the one in metadata %s\", root_hash, self.hashtree_info.root_hash) return",
"size to approximate final partition size. image_ratio = size_calculator(image_size) /",
"'true', 'verity_fec': 'true' if fec_supported else None, # 'verity_block_device' needs",
"for Verified Boot 2.0.\"\"\" AVB_HASH_FOOTER = 1 AVB_HASHTREE_FOOTER = 2",
"((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE v",
"algorithm, # Salt is None because custom images have no",
"out_file): \"\"\"Adds dm-verity hashtree and AVB metadata to an image.",
">= image_size: # if mid can accommodate image_size if mid",
"partition_size=None): \"\"\"Calculates max image size for a given partition size.",
"data\") def PadSparseImage(self, out_file): sparse_image_size = GetSimgSize(out_file) if sparse_image_size >",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"self.partition_size - self.image_size - self.verity_size assert padding_size >= 0 #",
"during verity image building.\"\"\" def __init__(self, message): Exception.__init__(self, message) def",
"should be cover the given image size (for filesystem files)",
"mid + BLOCK_SIZE logger.info( \"CalculateMinPartitionSize(%d): partition_size %d.\", image_size, partition_size) return",
"hash tree. adjusted_partition = common.MakeTempFile(prefix=\"adjusted_partition\") with open(adjusted_partition, \"wb\") as fd:",
"The minimum partition size required to accommodate the image size.",
"binary search for the optimal partition size. lo = int(image_size",
"\"\"\" cmd = [\"append2simg\", sparse_image_path, unsparse_image_path] try: common.RunAndCheckOutput(cmd) except: logger.exception(error_message)",
"__future__ import print_function import logging import os.path import shlex import",
"* self.block_size == self.filesystem_size) self.hashtree_info.hash_algorithm = table_entries[7].decode() self.hashtree_info.root_hash = table_entries[8].decode()",
"int(table_entries[4]) == self.block_size) assert (int(table_entries[5]) * self.block_size == self.filesystem_size and",
"return result def Build(self, out_file): \"\"\"Creates an image that is",
"partition size of \" \"{}\".format(sparse_image_size, self.image_size)) ZeroPadSimg(out_file, self.image_size - sparse_image_size)",
"proc.communicate() if proc.returncode != 0: raise BuildVerityImageError( \"Failed to calculate",
"partition_size=None): \"\"\"Calculates the max image size by accounting for the",
"the # verity metadata. 'verity_key': '', 'verity_signer_cmd': None, } self.verity_image_builder",
"This is used when determining the partition size for a",
"import common import sparse_img from rangelib import RangeSet logger =",
"info in a sparse image. Returns: hashtree_info: The information needed",
"accommodate image_size if mid < partition_size: # if a smaller",
"Boot. This class defines the common interface between Verified Boot",
"None class VerityImageBuilder(object): \"\"\"A builder that generates an image with",
"Verified Boot 2.0; or None if the given build doesn't",
"== \"true\" or prop_dict.get(\"avb_hashtree_enable\") == \"true\"): # key_path and algorithm",
"returning the given image size as # the partition size",
"self.hashtree_info.hashtree_range)) def Generate(self, image): \"\"\"Parses and validates the hashtree info",
"<= partition_size: if result < i: result = i verity_size",
"identical, as we use fixed value. assert salt == self.hashtree_info.salt,",
"a given partition.\"\"\" def __init__(self, partition_size, block_size, fec_supported): \"\"\"Initialize VerityTreeInfo",
"than partition size of \" \"{}\".format(sparse_image_size, self.image_size)) ZeroPadSimg(out_file, self.image_size -",
"including the filesystem size, padding size, and verity size. block_size:",
"= fec_supported self.image = None self.filesystem_size = None self.hashtree_size =",
"of a partition, including the filesystem size, padding size, and",
"* BLOCK_SIZE + delta delta *= 2 max_image_size = size_calculator(hi)",
"AVB metadata to an image. Args: out_file: Path to image",
"or None if the given build doesn't support Verified Boot.",
"+ self.metadata_size) // self.block_size]) meta_data = b''.join(self.image.ReadRangeSet(metadata_range)) # More info",
"metadata for supporting Android Verified Boot. This class defines the",
"adjusted_size % self.block_size == 0 verity_tree_size = GetVerityTreeSize(adjusted_size) assert verity_tree_size",
"image_size return image_size def PadSparseImage(self, out_file): # No-op as the",
"same bytes # as the one in the sparse image.",
"image size. This is used when determining the partition size",
"1 AVB_HASHTREE_FOOTER = 2 def __init__(self, partition_name, partition_size, footer_type, avbtool,",
"sizes. BuildVerityImageError: On other errors. \"\"\" image_size = int(self.image_size) tempdir_name",
"= None self.salt = None self.root_hash = None def CreateHashtreeInfoGenerator(partition_name,",
"blocks, pad_size) simg = sparse_img.SparseImage(image_file, mode=\"r+b\", build_map=False) simg.AppendFillChunk(0, blocks) def",
"i self.image_size = result self.verity_size = verity_size logger.info( \"Calculated image",
"raise NotImplementedError def DecomposeSparseImage(self, image): raise NotImplementedError def ValidateHashtree(self): raise",
"verity_metadata, fec_data]. We can then calculate the size and offset",
"= GetVerityMetadataSize(image_size) verity_size = verity_tree_size + verity_metadata_size if fec_supported: fec_size",
"== \"true\": builder = VerifiedBootVersion2VerityImageBuilder( partition_name, partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, info_dict.get(\"avb_avbtool\"), key_path,",
"\"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityTreeSize(image_size):",
"is None: size_calculator = self.CalculateMaxImageSize # Use image size as",
"input_file: out_file.write(line) except IOError: logger.exception(error_message) raise BuildVerityImageError(error_message) def CreateVerityImageBuilder(prop_dict): \"\"\"Returns",
"Boot 1.0.\"\"\" def __init__(self, partition_size, block_dev, fec_supported, signer_path, signer_key, signer_args,",
"while lo < hi: i = ((lo + hi) //",
"the image size. \"\"\" if size_calculator is None: size_calculator =",
"Ensure lo is small enough: max_image_size should <= image_size. delta",
"self.avbtool = avbtool self.algorithm = algorithm self.key_path = key_path self.salt",
"self.ValidateHashtree(): raise HashtreeInfoGenerationError(\"Failed to reconstruct the verity tree\") return self.hashtree_info",
"def GetVeritySize(image_size, fec_supported): verity_tree_size = GetVerityTreeSize(image_size) verity_metadata_size = GetVerityMetadataSize(image_size) verity_size",
"given image size (for filesystem files) as well as the",
"if unspecified. Returns: The size of the image adjusted for",
"BLOCK_SIZE)) * BLOCK_SIZE v = GetVeritySize(i, self.fec_supported) if i +",
"image_size %d, \" \"verity_size %d\", partition_size, result, verity_size) return result",
"we use fixed value. assert salt == self.hashtree_info.salt, \\ \"Calculated",
"size {}\".format( len(table_entries)) assert (int(table_entries[3]) == self.block_size and int(table_entries[4]) ==",
"Boot 2.0.\"\"\" AVB_HASH_FOOTER = 1 AVB_HASHTREE_FOOTER = 2 def __init__(self,",
"BuildVerityImageError: On other errors. \"\"\" image_size = int(self.image_size) tempdir_name =",
"def Append(target, file_to_append, error_message): \"\"\"Appends file_to_append to target. Raises: BuildVerityImageError:",
"'verity_block_device' needs to be present to indicate a verity-enabled #",
"BuildVerityMetadata( image_size, verity_metadata_path, root_hash, salt, self.block_device, self.signer_path, self.signer_key, self.signer_args, self.verity_disable)",
"fec_size = GetVerityFECSize(image_size + verity_size) return verity_size + fec_size return",
"image_ratio) // BLOCK_SIZE * BLOCK_SIZE + delta delta *= 2",
"Verified Boot. This class defines the common interface between Verified",
"= HashtreeInfo() def DecomposeSparseImage(self, image): \"\"\"Calculate the verity size based",
"= block_dev self.fec_supported = fec_supported self.signer_path = signer_path self.signer_key =",
"(C) 2018 The Android Open Source Project # # Licensed",
"self.fec_supported = fec_supported self.image = None self.filesystem_size = None self.hashtree_size",
"signer_args: cmd.append(\"--signer_args=\\\"%s\\\"\" % (' '.join(signer_args),)) if verity_disable: cmd.append(\"--verity_disable\") common.RunAndCheckOutput(cmd) def",
"\"verity_metadata.img\") # Build the verity tree and get the root",
"size {} doesn't match with the calculated image size.\" \\",
"block_size, fec_supported): \"\"\"Initialize VerityTreeInfo with the sparse image and input",
"self.filesystem_size + self.hashtree_size metadata_range = RangeSet( data=[metadata_start // self.block_size, (metadata_start",
"self.fec_supported = fec_supported self.signer_path = signer_path self.signer_key = signer_key self.signer_args",
"output, _ = proc.communicate() if proc.returncode != 0: raise BuildVerityImageError(\"Failed",
"as input_file: for line in input_file: out_file.write(line) except IOError: logger.exception(error_message)",
"self.partition_size if unspecified. Returns: The size of the image adjusted",
"cmd = [\"fec\", \"-e\", \"-p\", str(padding_size), sparse_image_path, verity_path, verity_fec_path] common.RunAndCheckOutput(cmd)",
"\\ \"Calculated salt {} doesn't match the one in metadata",
"= salt self.signing_args = signing_args self.image_size = None def CalculateMinPartitionSize(self,",
"{}\".format( len(table_entries)) assert (int(table_entries[3]) == self.block_size and int(table_entries[4]) == self.block_size)",
"partition size, which # means this estimate is always going",
"data=[metadata_start // self.block_size, (metadata_start + self.metadata_size) // self.block_size]) meta_data =",
"= [\"build_verity_tree\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output)",
"open(generated_verity_tree, 'rb') as fd: return fd.read() == b''.join(self.image.ReadRangeSet( self.hashtree_info.hashtree_range)) def",
"cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output, _ = proc.communicate() if proc.returncode",
"verity size based on the size of the input image.",
"None self.filesystem_range = None self.hash_algorithm = None self.salt = None",
"= image_size return image_size def PadSparseImage(self, out_file): # No-op as",
"= BLOCK_SIZE max_image_size = size_calculator(hi) while max_image_size < image_size: image_ratio",
"\" \"{}\".format(sparse_image_size, self.image_size)) ZeroPadSimg(out_file, self.image_size - sparse_image_size) class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder): \"\"\"A",
"root_hash, self.hashtree_info.root_hash) return False # Reads the generated hash tree",
"= partition_size if hi % BLOCK_SIZE != 0: hi =",
"in metadata {}\".format( salt, self.hashtree_info.salt) if root_hash != self.hashtree_info.root_hash: logger.warning(",
"v <= partition_size: if result < i: result = i",
"size for a given partition size. Args: partition_size: The partition",
"verity_fec_path, padding_size): cmd = [\"fec\", \"-e\", \"-p\", str(padding_size), sparse_image_path, verity_path,",
"from rangelib import RangeSet logger = logging.getLogger(__name__) OPTIONS = common.OPTIONS",
"build_map=False) simg.AppendFillChunk(0, blocks) def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path, padding_size): cmd =",
"is not None: signer_path = OPTIONS.verity_signer_path else: signer_path = prop_dict[\"verity_signer_cmd\"]",
"an image with verity metadata for Verified Boot. A VerityImageBuilder",
"self.footer_type = footer_type self.avbtool = avbtool self.algorithm = algorithm self.key_path",
"int(output) def GetVerityMetadataSize(image_size): cmd = [\"build_verity_metadata\", \"size\", str(image_size)] output =",
"the path to the (sparse) image unsparse_image_path: the path to",
"\\ open(file_to_append, 'rb') as input_file: for line in input_file: out_file.write(line)",
"including metadata. verity_fec_path = os.path.join(tempdir_name, \"verity_fec.img\") BuildVerityFEC( out_file, verity_image_path, verity_fec_path,",
"1 self.partition_size = partition_size self.block_device = block_dev self.fec_supported = fec_supported",
"on the given build properties. More info on the verity",
"the size and offset of each section. \"\"\" self.image =",
"sparse_image_size = GetSimgSize(out_file) if sparse_image_size > self.image_size: raise BuildVerityImageError( \"Error:",
"prop_dict.get(\"verity\") == \"true\" is_verity_partition = \"verity_block_device\" in prop_dict if verity_supported",
"image size as # the partition size doesn't make sense,",
"GetVeritySize(image_size, fec_supported): verity_tree_size = GetVerityTreeSize(image_size) verity_metadata_size = GetVerityMetadataSize(image_size) verity_size =",
"signer_path = OPTIONS.verity_signer_path else: signer_path = prop_dict[\"verity_signer_cmd\"] return Version1VerityImageBuilder( partition_size,",
"this estimate is always going to be unnecessarily small verity_size",
"= None self.hash_algorithm = None self.salt = None self.root_hash =",
"== self.block_size and int(table_entries[4]) == self.block_size) assert (int(table_entries[5]) * self.block_size",
"= [\"build_verity_metadata\", \"build\", str(image_size), verity_metadata_path, root_hash, salt, block_device, signer_path, key]",
"hashtree. \"\"\" self.DecomposeSparseImage(image) self._ParseHashtreeMetadata() if not self.ValidateHashtree(): raise HashtreeInfoGenerationError(\"Failed to",
"# verity metadata. 'verity_key': '', 'verity_signer_cmd': None, } self.verity_image_builder =",
"'rb') as input_file: for line in input_file: out_file.write(line) except IOError:",
"self.verity_disable = verity_disable self.image_size = None self.verity_size = None def",
"image to modify. \"\"\" add_footer = (\"add_hash_footer\" if self.footer_type ==",
"!= 0: raise BuildVerityImageError(\"Failed to add AVB footer: {}\".format(output)) class",
"= v lo = i + BLOCK_SIZE else: hi =",
"and get the root hash and salt. root_hash, salt =",
"look for verity-related property values. Returns: A VerityImageBuilder instance for",
"None, # 'verity_block_device' needs to be present to indicate a",
"the executable # build_verity_tree to construct the hash tree. adjusted_partition",
"not None: signer_path = OPTIONS.verity_signer_path else: signer_path = prop_dict[\"verity_signer_cmd\"] return",
"Prepare a binary search for the optimal partition size. lo",
"HashtreeInfoGenerationError(\"Failed to reconstruct the verity tree\") return self.hashtree_info def CreateCustomImageBuilder(info_dict,",
"= int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - delta",
"return int(output) def GetVerityTreeSize(image_size): cmd = [\"build_verity_tree\", \"-s\", str(image_size)] output",
"the root hash and salt. root_hash, salt = BuildVerityTree(out_file, verity_image_path)",
"out_file.write(line) except IOError: logger.exception(error_message) raise BuildVerityImageError(error_message) def CreateVerityImageBuilder(prop_dict): \"\"\"Returns a",
"% self.block_size == 0 metadata_size = GetVerityMetadataSize(adjusted_size) assert metadata_size %",
"size, which defaults to self.partition_size if unspecified. Returns: The size",
"hashtree for a given partition.\"\"\" def __init__(self, partition_size, block_size, fec_supported):",
"Args: out_file: Path to image to modify. \"\"\" add_footer =",
"lo = mid + BLOCK_SIZE logger.info( \"CalculateMinPartitionSize(%d): partition_size %d.\", image_size,",
"fec data. \"\"\" self.block_size = block_size self.partition_size = partition_size self.fec_supported",
"the hashtree info in a sparse image. Returns: hashtree_info: The",
"to append verity data\") def PadSparseImage(self, out_file): sparse_image_size = GetSimgSize(out_file)",
"partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hash_footer_args\"]) # Image uses",
"the entire partition, including metadata. verity_fec_path = os.path.join(tempdir_name, \"verity_fec.img\") BuildVerityFEC(",
"fec_supported self.signer_path = signer_path self.signer_key = signer_key self.signer_args = signer_args",
"out_file: Path to image to modify. \"\"\" add_footer = (\"add_hash_footer\"",
"for the optimal partition size. lo = int(image_size / image_ratio)",
"logger.info( \"CalculateMinPartitionSize(%d): partition_size %d.\", image_size, partition_size) return partition_size def CalculateDynamicPartitionSize(self,",
"signer_path self.signer_key = signer_key self.signer_args = signer_args self.verity_disable = verity_disable",
"self.image_size = None self.verity_size = None def CalculateDynamicPartitionSize(self, image_size): #",
"+ table_len] table_entries = verity_table.rstrip().split() # Expected verity table format:",
"image and input property. Arguments: partition_size: The whole size in",
"verity metadata for supporting Android Verified Boot. This class defines",
"image_size if mid < partition_size: # if a smaller partition",
"governing permissions and # limitations under the License. from __future__",
"uses hashtree footer. return VerifiedBootVersion2VerityImageBuilder( prop_dict[\"partition_name\"], partition_size, VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER, prop_dict[\"avb_avbtool\"], key_path,",
"properties. In particular, it will look for verity-related property values.",
"def PadSparseImage(self, out_file): # No-op as the padding is taken",
"float(hi) hi = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE",
"= [\"fec\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output)",
"blocks) def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path, padding_size): cmd = [\"fec\", \"-e\",",
"needed for signing the # verity metadata. 'verity_key': '', 'verity_signer_cmd':",
"\"\"\"Parses the hash_algorithm, root_hash, salt from the metadata block.\"\"\" metadata_start",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"verity metadata. Args: partition_size: The partition size, which defaults to",
"BLOCK_SIZE max_image_size = size_calculator(hi) while max_image_size < image_size: image_ratio =",
"for building an image with verity metadata for supporting Android",
"= None def CreateHashtreeInfoGenerator(partition_name, block_size, info_dict): generator = None if",
"dynamic partitions. if partition_size: partition_size = int(partition_size) # Verified Boot",
"build_verity_tree to construct the hash tree. adjusted_partition = common.MakeTempFile(prefix=\"adjusted_partition\") with",
"%s\", root_hash, self.hashtree_info.root_hash) return False # Reads the generated hash",
"root_hash salt\" assert len(table_entries) == 10, \"Unexpected verity table size",
"= int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE",
"BuildVerityTree(adjusted_partition, generated_verity_tree) # The salt should be always identical, as",
"signing_args self.image_size = None def CalculateMinPartitionSize(self, image_size, size_calculator=None): \"\"\"Calculates min",
"verity metadata size. Args: image_size: The size of the image",
"VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER, prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hash_footer_args\"]) # Image uses hashtree",
"\\ \"Invalid partition size: {}\".format(partition_size) add_footer = (\"add_hash_footer\" if self.footer_type",
"it will look for verity-related property values. Returns: A VerityImageBuilder",
"metadata_size = GetVerityMetadataSize(adjusted_size) assert metadata_size % self.block_size == 0 self.filesystem_size",
"key_path, algorithm, # Salt is None because custom images have",
"be None at this point, if using dynamic partitions. if",
"Verified Boot 2.0.\"\"\" AVB_HASH_FOOTER = 1 AVB_HASHTREE_FOOTER = 2 def",
"image_size <= 0: raise BuildVerityImageError( \"Invalid max image size: {}\".format(output))",
"the given build doesn't support Verified Boot. \"\"\" partition_size =",
"verity_tree_size + verity_metadata_size if fec_supported: fec_size = GetVerityFECSize(image_size + verity_size)",
"self.block_size, (metadata_start + self.metadata_size) // self.block_size]) meta_data = b''.join(self.image.ReadRangeSet(metadata_range)) #",
"\"add_hashtree_footer\") cmd = [self.avbtool, add_footer, \"--partition_size\", str(self.partition_size), \"--partition_name\", self.partition_name, \"--image\",",
"footer_type, avbtool, key_path, algorithm, salt, signing_args): self.version = 2 self.partition_name",
"The information needed to reconstruct the hashtree. Raises: HashtreeInfoGenerationError: If",
"using dynamic partitions. if partition_size: partition_size = int(partition_size) # Verified",
"DecomposeSparseImage(self, image): \"\"\"Calculate the verity size based on the size",
"<= image_size. delta = BLOCK_SIZE max_image_size = size_calculator(lo) while max_image_size",
"CreateVerityImageBuilder(prop_dict) self.hashtree_info = HashtreeInfo() def DecomposeSparseImage(self, image): \"\"\"Calculate the verity",
"\"true\" and info_dict.get(\"{}_verity_block_device\".format(partition_name))): partition_size = info_dict[\"{}_size\".format(partition_name)] fec_supported = info_dict.get(\"verity_fec\") ==",
"particular, it will look for verity-related property values. Returns: A",
"partition_size, block_size, fec_supported) return generator class HashtreeInfoGenerator(object): def Generate(self, image):",
"a given image size. This is used when determining the",
"if max_image_size >= image_size: # if mid can accommodate image_size",
"image. Append( verity_image_path, verity_metadata_path, \"Failed to append verity metadata\") if",
"RangeSet logger = logging.getLogger(__name__) OPTIONS = common.OPTIONS BLOCK_SIZE = common.BLOCK_SIZE",
"# partition. 'verity_block_device': '', # We don't need the following",
"Version 2.0 (the \"License\"); # you may not use this",
"the sparse image. fec_supported: True if the verity section contains",
"unsparse image to the given sparse image. Args: sparse_image_path: the",
"builder will be returned based on the given build properties.",
"this point, if using dynamic partitions. if partition_size: partition_size =",
"construct the hash tree. adjusted_partition = common.MakeTempFile(prefix=\"adjusted_partition\") with open(adjusted_partition, \"wb\")",
"image size:\\n{}\".format(output)) image_size = int(output) if image_size <= 0: raise",
"import struct import common import sparse_img from rangelib import RangeSet",
"image_size: image_ratio = max_image_size / float(hi) hi = int(image_size /",
"for a given partition size. Returns: The minimum partition size",
"info_dict.get(\"avb_avbtool\"), key_path, algorithm, # Salt is None because custom images",
"link. https://source.android.com/security/verifiedboot/dm-verity#implementation \"\"\" def CalculateMaxImageSize(self, partition_size): \"\"\"Calculates the filesystem image",
"int(self.image_size) tempdir_name = common.MakeTempDir(suffix=\"_verity_images\") # Get partial image paths. verity_image_path",
"i + BLOCK_SIZE else: hi = i self.image_size = result",
"struct.unpack(\"II256sI\", header_bin) # header: magic_number, version, signature, table_len assert header[0]",
"i = ((lo + hi) // (2 * BLOCK_SIZE)) *",
"os.path import shlex import struct import common import sparse_img from",
"to a temp file; and calls the executable # build_verity_tree",
"min partition size for a given image size. This is",
"then calculate the size and offset of each section. \"\"\"",
"which defaults to self.partition_size if unspecified. Returns: The size of",
"root_hash, salt, self.block_device, self.signer_path, self.signer_key, self.signer_args, self.verity_disable) padding_size = self.partition_size",
"fec_supported: True if the verity section contains fec data. \"\"\"",
"prop_dict[\"avb_avbtool\"], key_path, algorithm, prop_dict.get(\"avb_salt\"), prop_dict[\"avb_add_hash_footer_args\"]) # Image uses hashtree footer.",
"header_bin = meta_data[0:META_HEADER_SIZE] header = struct.unpack(\"II256sI\", header_bin) # header: magic_number,",
"= table_entries[7].decode() self.hashtree_info.root_hash = table_entries[8].decode() self.hashtree_info.salt = table_entries[9].decode() def ValidateHashtree(self):",
"are only available when chain partition is used. key_path =",
"size. Args: partition_size: The partition size, which defaults to self.partition_size",
"2.0.\"\"\" AVB_HASH_FOOTER = 1 AVB_HASHTREE_FOOTER = 2 def __init__(self, partition_name,",
"the optimal partition size. lo = int(image_size / image_ratio) //",
"by applicable law or agreed to in writing, software #",
"> self.image_size: raise BuildVerityImageError( \"Error: image size of {} is",
"image. fec_supported: True if the verity section contains fec data.",
"+ v <= partition_size: if result < i: result =",
"given partition size. Returns: The minimum partition size required to",
"verity_size result = lo # do a binary search for",
"partition_size: partition_size = int(partition_size) # Verified Boot 1.0 verity_supported =",
"str(partition_size), \"--calc_max_image_size\"] cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output, _ = proc.communicate()",
"Reads the generated hash tree and checks if it has",
"__init__(self, message): Exception.__init__(self, message) def GetVerityFECSize(image_size): cmd = [\"fec\", \"-s\",",
"signer_path, key, signer_args, verity_disable): cmd = [\"build_verity_metadata\", \"build\", str(image_size), verity_metadata_path,",
"= BuildVerityTree(adjusted_partition, generated_verity_tree) # The salt should be always identical,",
"/ float(hi) hi = int(image_size / image_ratio) // BLOCK_SIZE *",
"assert self.block_size == image.blocksize assert self.partition_size == image.total_blocks * self.block_size,",
"common.MakeTempFile(prefix=\"verity\") root_hash, salt = BuildVerityTree(adjusted_partition, generated_verity_tree) # The salt should",
"= None self.metadata_size = None prop_dict = { 'partition_size': str(partition_size),",
"NotImplementedError def ValidateHashtree(self): raise NotImplementedError class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator): \"\"\"A class that",
"verifiable using dm-verity. Args: out_file: the output image. Returns: AssertionError:",
"out_file, verity_image_path, verity_fec_path, padding_size) Append(verity_image_path, verity_fec_path, \"Failed to append FEC\")",
"= verity_table.rstrip().split() # Expected verity table format: \"1 block_device block_device",
"block_device block_device block_size # block_size data_blocks data_blocks hash_algorithm root_hash salt\"",
"for signing the # verity metadata. 'verity_key': '', 'verity_signer_cmd': None,",
"image size. Raises: BuildVerityImageError: On error or getting invalid image",
"class HashtreeInfo(object): def __init__(self): self.hashtree_range = None self.filesystem_range = None",
"partition size doesn't make sense, as it will fail later.",
"%d\", partition_size, result, verity_size) return result def Build(self, out_file): \"\"\"Creates",
"logger.warning( \"Calculated root hash %s doesn't match the one in",
"{}\".format(partition_size) add_footer = (\"add_hash_footer\" if self.footer_type == self.AVB_HASH_FOOTER else \"add_hashtree_footer\")",
"self.signer_key, self.signer_args, self.verity_disable) padding_size = self.partition_size - self.image_size - self.verity_size",
"root_hash, salt = BuildVerityTree(out_file, verity_image_path) # Build the metadata blocks.",
"image_ratio = size_calculator(image_size) / float(image_size) # Prepare a binary search",
"files) as well as the verity metadata size. Args: image_size:",
"section. \"\"\" self.image = image assert self.block_size == image.blocksize assert",
"self.verity_size = None def CalculateDynamicPartitionSize(self, image_size): # This needs to",
"key, signer_args, verity_disable): cmd = [\"build_verity_metadata\", \"build\", str(image_size), verity_metadata_path, root_hash,",
"= [self.avbtool, add_footer, \"--partition_size\", str(partition_size), \"--calc_max_image_size\"] cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd)",
"2018 The Android Open Source Project # # Licensed under",
"to be # used as the salt. None, signing_args) return",
"= { 'partition_size': str(partition_size), 'verity': 'true', 'verity_fec': 'true' if fec_supported",
"root hash and salt. root_hash, salt = BuildVerityTree(out_file, verity_image_path) #",
"= int(self.image_size) tempdir_name = common.MakeTempDir(suffix=\"_verity_images\") # Get partial image paths.",
"fingerprint property to be # used as the salt. None,",
"applicable law or agreed to in writing, software # distributed",
"self.hashtree_size metadata_range = RangeSet( data=[metadata_start // self.block_size, (metadata_start + self.metadata_size)",
"// BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE # Ensure lo is",
"used. key_path = prop_dict.get(\"avb_key_path\") algorithm = prop_dict.get(\"avb_algorithm\") # Image uses",
"table_entries = verity_table.rstrip().split() # Expected verity table format: \"1 block_device",
"= proc.communicate() if proc.returncode != 0: raise BuildVerityImageError(\"Failed to add",
"sparse image. with open(generated_verity_tree, 'rb') as fd: return fd.read() ==",
"be: [filesystem, verity_hashtree, verity_metadata, fec_data]. We can then calculate the",
"HashtreeInfo(object): def __init__(self): self.hashtree_range = None self.filesystem_range = None self.hash_algorithm",
"None if info_dict.get(\"avb_enable\") == \"true\": builder = VerifiedBootVersion2VerityImageBuilder( partition_name, partition_size,",
"a given partition size. Returns: The minimum partition size required",
"\"aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7\" class BuildVerityImageError(Exception): \"\"\"An Exception raised during verity image building.\"\"\"",
"size. \"\"\" if size_calculator is None: size_calculator = self.CalculateMaxImageSize #",
"\"Failed to append verity data\") def PadSparseImage(self, out_file): sparse_image_size =",
"The partition size, which defaults to self.partition_size if unspecified. Returns:",
"verity_image_path, \"Failed to append verity data\") def PadSparseImage(self, out_file): sparse_image_size",
"ZeroPadSimg(out_file, self.image_size - sparse_image_size) class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified",
"mid else: lo = mid + BLOCK_SIZE logger.info( \"CalculateMinPartitionSize(%d): partition_size",
"= mid + BLOCK_SIZE logger.info( \"CalculateMinPartitionSize(%d): partition_size %d.\", image_size, partition_size)",
"tempdir_name = common.MakeTempDir(suffix=\"_verity_images\") # Get partial image paths. verity_image_path =",
"size_calculator: The function to calculate max image size for a",
"result, verity_size) return result def Build(self, out_file): \"\"\"Creates an image",
"\"\"\"Appends file_to_append to target. Raises: BuildVerityImageError: On error. \"\"\" try:",
"On other errors. \"\"\" image_size = int(self.image_size) tempdir_name = common.MakeTempDir(suffix=\"_verity_images\")",
"= proc.communicate() if proc.returncode != 0: raise BuildVerityImageError( \"Failed to",
"the input image. Since we already know the structure of",
"size is found partition_size = mid hi = mid else:",
"dict that contains the build properties. In particular, it will",
"# You may obtain a copy of the License at",
"= size_calculator(image_size) / float(image_size) # Prepare a binary search for",
"mid < partition_size: # if a smaller partition size is",
"smaller partition size is found partition_size = mid hi =",
"always identical, as we use fixed value. assert salt ==",
"partition size, which defaults to self.partition_size if unspecified. Returns: The",
"output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVerityTreeSize(image_size): cmd =",
"Verified Boot 2.0 if (prop_dict.get(\"avb_hash_enable\") == \"true\" or prop_dict.get(\"avb_hashtree_enable\") ==",
"= (hi // BLOCK_SIZE) * BLOCK_SIZE # verity tree and",
"verity_metadata_path, \"Failed to append verity metadata\") if self.fec_supported: # Build",
"to reconstruct the hashtree. Raises: HashtreeInfoGenerationError: If we fail to",
"= common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVeritySize(image_size, fec_supported): verity_tree_size =",
"def __init__(self, partition_size, block_dev, fec_supported, signer_path, signer_key, signer_args, verity_disable): self.version",
"self.algorithm]) if self.salt: cmd.extend([\"--salt\", self.salt]) cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output,",
"if self.fec_supported: # Build FEC for the entire partition, including",
"metadata for Verified Boot. A VerityImageBuilder instance handles the works",
"for the optimal size while lo < hi: i =",
"the License. from __future__ import print_function import logging import os.path",
"image. Returns: AssertionError: On invalid partition sizes. BuildVerityImageError: On other",
"(2 * BLOCK_SIZE)) * BLOCK_SIZE max_image_size = size_calculator(mid) if max_image_size",
"== self.AVB_HASH_FOOTER else \"add_hashtree_footer\") cmd = [self.avbtool, add_footer, \"--partition_size\", str(partition_size),",
"image_ratio) // BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE # Ensure lo",
"block_device block_size # block_size data_blocks data_blocks hash_algorithm root_hash salt\" assert",
"raise HashtreeInfoGenerationError(\"Failed to reconstruct the verity tree\") return self.hashtree_info def",
"unsparse_image_path: the path to the (unsparse) image Raises: BuildVerityImageError: On",
"= os.path.join(tempdir_name, \"verity_metadata.img\") # Build the verity tree and get",
"max_image_size < image_size: image_ratio = max_image_size / float(hi) hi =",
"class VerityImageBuilder(object): \"\"\"A builder that generates an image with verity",
"CreateHashtreeInfoGenerator(partition_name, block_size, info_dict): generator = None if (info_dict.get(\"verity\") == \"true\"",
"BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path, padding_size): cmd = [\"fec\", \"-e\", \"-p\", str(padding_size),",
"BuildVerityImageError(error_message) def CreateVerityImageBuilder(prop_dict): \"\"\"Returns a verity image builder based on",
"self.filesystem_range = None self.hash_algorithm = None self.salt = None self.root_hash",
"verity_image_path = os.path.join(tempdir_name, \"verity.img\") verity_metadata_path = os.path.join(tempdir_name, \"verity_metadata.img\") # Build",
"the build properties. In particular, it will look for verity-related",
"size, which # means this estimate is always going to",
"self.block_size and int(table_entries[4]) == self.block_size) assert (int(table_entries[5]) * self.block_size ==",
"generated hash tree and checks if it has the exact",
"os.path.join(tempdir_name, \"verity_fec.img\") BuildVerityFEC( out_file, verity_image_path, verity_fec_path, padding_size) Append(verity_image_path, verity_fec_path, \"Failed",
"{} is larger than partition size of \" \"{}\".format(sparse_image_size, self.image_size))",
"assert padding_size >= 0 # Build the full verified image.",
"= prop_dict.get(\"verity\") == \"true\" is_verity_partition = \"verity_block_device\" in prop_dict if",
"which # means this estimate is always going to be",
"On invalid partition sizes. BuildVerityImageError: On other errors. \"\"\" image_size",
"None self.filesystem_size = None self.hashtree_size = None self.metadata_size = None",
"{} doesn't match with the calculated image size.\" \\ \"",
"RangeSet( data=[adjusted_size // self.block_size, (adjusted_size + verity_tree_size) // self.block_size]) def",
"class HashtreeInfoGenerator(object): def Generate(self, image): raise NotImplementedError def DecomposeSparseImage(self, image):",
"The size of the image in question. size_calculator: The function",
"DecomposeSparseImage(self, image): raise NotImplementedError def ValidateHashtree(self): raise NotImplementedError class VerifiedBootVersion1HashtreeInfoGenerator(HashtreeInfoGenerator):",
"size_calculator(lo) while max_image_size > image_size: image_ratio = max_image_size / float(lo)",
"\"License\"); # you may not use this file except in",
"tree. adjusted_partition = common.MakeTempFile(prefix=\"adjusted_partition\") with open(adjusted_partition, \"wb\") as fd: self.image.WriteRangeDataToFd(self.hashtree_info.filesystem_range,",
"image that is verifiable using dm-verity. Args: out_file: the output",
"image Raises: BuildVerityImageError: On error. \"\"\" cmd = [\"append2simg\", sparse_image_path,",
"root_hash, salt, block_device, signer_path, key, signer_args, verity_disable): cmd = [\"build_verity_metadata\",",
"cmd = [\"build_verity_tree\", \"-s\", str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return",
"invalid partition sizes. BuildVerityImageError: On other errors. \"\"\" image_size =",
"# Build the full verified image. Append( verity_image_path, verity_metadata_path, \"Failed",
"given build properties. More info on the verity image generation",
"sparse image. Args: sparse_image_path: the path to the (sparse) image",
"== b''.join(self.image.ReadRangeSet( self.hashtree_info.hashtree_range)) def Generate(self, image): \"\"\"Parses and validates the",
"self.algorithm = algorithm self.key_path = key_path self.salt = salt self.signing_args",
"class Version1VerityImageBuilder(VerityImageBuilder): \"\"\"A VerityImageBuilder for Verified Boot 1.0.\"\"\" def __init__(self,",
"adjusted_size = self.verity_image_builder.CalculateMaxImageSize() assert adjusted_size % self.block_size == 0 verity_tree_size",
"def Build(self, out_file): \"\"\"Adds dm-verity hashtree and AVB metadata to",
"hashtree info generation.\"\"\" def __init__(self, message): Exception.__init__(self, message) class HashtreeInfo(object):",
"size_calculator = self.CalculateMaxImageSize # Use image size as partition size",
"RangeSet( data=[0, adjusted_size // self.block_size]) self.hashtree_info.hashtree_range = RangeSet( data=[adjusted_size //",
"verity_fec_path, \"Failed to append FEC\") Append2Simg( out_file, verity_image_path, \"Failed to",
"proc.returncode != 0: raise BuildVerityImageError( \"Failed to calculate max image",
"self.salt: cmd.extend([\"--salt\", self.salt]) cmd.extend(shlex.split(self.signing_args)) proc = common.Run(cmd) output, _ =",
"/ float(image_size) # Prepare a binary search for the optimal",
"should <= image_size. delta = BLOCK_SIZE max_image_size = size_calculator(lo) while",
"\"Calculated root hash %s doesn't match the one in metadata",
"Image uses hash footer. if prop_dict.get(\"avb_hash_enable\") == \"true\": return VerifiedBootVersion2VerityImageBuilder(",
"= size_calculator(lo) hi = lo + BLOCK_SIZE # Ensure hi",
"str(image_size)] output = common.RunAndCheckOutput(cmd, verbose=False) return int(output) def GetVeritySize(image_size, fec_supported):",
"2 def __init__(self, partition_name, partition_size, footer_type, avbtool, key_path, algorithm, salt,",
"filesystem section to a temp file; and calls the executable",
"def __init__(self, message): Exception.__init__(self, message) class HashtreeInfo(object): def __init__(self): self.hashtree_range",
"hash and salt. root_hash, salt = BuildVerityTree(out_file, verity_image_path) # Build",
"table size {}\".format( len(table_entries)) assert (int(table_entries[3]) == self.block_size and int(table_entries[4])",
"sparse image.\"\"\" raise NotImplementedError def Build(self, out_file): \"\"\"Builds the verity",
"binary search for the optimal size while lo < hi:",
"based on the size of the input image. Since we"
] |
[
"and dt1.month == dt2.month and dt1.day == dt2.day) def table_add_oddday(key_table):",
"which has following keywords: heading, closed, scheduled, effort, clocksum, rootname.",
"str a title \"\"\" key_table = [] orgname_list = unique_name_from_paths(orgpath_list)",
"p = p.parent # n is root node rootname =",
"= olpath.split('/', 1) if len(olpathlist) > 1: (rootname, dummy) =",
"`orgpath` and `orgname`. `orgname` is short and unique name for",
"for `orgpath`. title: str a title \"\"\" key_table = []",
"[] orgname_list = unique_name_from_paths(orgpath_list) for (nodelist, orgname) in zip(orgnodes_list, orgname_list):",
"row = dict( heading=heading, closed=closed and closed.start.strftime('%a %d %b %H:%M'),",
"rendering jinja2 template. Data is dictionary like this: table: list",
"if len(olpathlist) > 1: (rootname, dummy) = olpathlist else: rootname",
"not found. \"\"\" olpath = node.get_property('ARCHIVE_OLPATH') if olpath: olpathlist =",
"and dictionary which has following keywords: heading, closed, scheduled, effort,",
"scheduled = node.scheduled effort = node.get_property('Effort') row = dict( heading=heading,",
"= rootname_from_archive_olpath(node) if not rootname: n = node p =",
"(orgpath, orgname) in zip(orgpath_list, orgname_list)] key_table.sort(reverse=True) table_add_oddday(key_table) table = list(itertools.islice((row",
"None if not found. \"\"\" olpath = node.get_property('ARCHIVE_OLPATH') if olpath:",
"namelist: name_orig = name i = 1 while name not",
"(key, row) in key_table: this = key if not sameday(this,",
"in key_table: this = key if not sameday(this, previous): odd",
"= key_row_from_node(node) if key: row['orgname'] = orgname key_table.append((key, row)) orgpathname_list",
".utils.date import minutestr, total_minutes def rootname_from_archive_olpath(node): \"\"\" Find rootname from",
"closed = node.closed scheduled = node.scheduled effort = node.get_property('Effort') row",
"# find rootname rootname = find_rootname(node) if heading == rootname:",
"<%d>\" % (name_orig, i) i += 1 namelist.append(name) return namelist",
"1) if len(olpathlist) > 1: (rootname, dummy) = olpathlist else:",
"and `orgname`. `orgname` is short and unique name for `orgpath`.",
"to html table converter\"\"\" import os import datetime import itertools",
"[] for path in pathlist: name = os.path.basename(path) if name",
"minutestr(effort), clocksum=clocksum and minutestr(clocksum), rootname=rootname, ) return (closed.start if closed",
"\"\"\" key_table = [] orgname_list = unique_name_from_paths(orgpath_list) for (nodelist, orgname)",
"node.get_property('Effort') row = dict( heading=heading, closed=closed and closed.start.strftime('%a %d %b",
"unique name for `orgpath`. title: str a title \"\"\" key_table",
"\"\"\" Find rootname given node \"\"\" rootname = rootname_from_archive_olpath(node) if",
"clocklist]) closed = node.closed scheduled = node.scheduled effort = node.get_property('Effort')",
"of row generated by ``row_from_node`` orgpathname_list: list of `orgpathname` orgpathname:",
"orgpathname: dict contains `orgpath` and `orgname`. `orgname` is short and",
"in nodelist: if node.todo == done: (key, row) = key_row_from_node(node)",
"os import datetime import itertools from .utils.date import minutestr, total_minutes",
"table: list of `row` list of row generated by ``row_from_node``",
"and minutestr(effort), clocksum=clocksum and minutestr(clocksum), rootname=rootname, ) return (closed.start if",
"node.get_property('ARCHIVE_OLPATH') if olpath: olpathlist = olpath.split('/', 1) if len(olpathlist) >",
"rootname return None def find_rootname(node): \"\"\" Find rootname given node",
"n.heading return rootname def key_row_from_node(node): \"\"\" Return three tuple (key,",
"get_data(orgnodes_list, orgpath_list, done, num=100): \"\"\" Get data for rendering jinja2",
"root node rootname = rootname_from_archive_olpath(n) or n.heading return rootname def",
"not odd row['oddday'] = odd previous = this def get_data(orgnodes_list,",
"1 while name not in namelist: name = \"%s <%d>\"",
"def find_rootname(node): \"\"\" Find rootname given node \"\"\" rootname =",
"+= 1 namelist.append(name) return namelist def sameday(dt1, dt2): return (isinstance(dt1,",
"a ``datetime.date`` object. \"\"\" previous = None odd = True",
"if CLOCK exists clocksum = '' clocklist = node.clock if",
"= key if not sameday(this, previous): odd = not odd",
"p.is_root(): n = p p = p.parent # n is",
"dt1.month == dt2.month and dt1.day == dt2.day) def table_add_oddday(key_table): \"\"\"",
"datetime.date) and dt1.year == dt2.year and dt1.month == dt2.month and",
"table = list(itertools.islice((row for (key, row) in key_table), num)) return",
"in namelist: name_orig = name i = 1 while name",
"each rows of key_table *IN PLACE*. Note that key should",
"from ARCHIVE_OLPATH property. Return None if not found. \"\"\" olpath",
"n = p p = p.parent # n is root",
"%b %H:%M'), scheduled=scheduled and scheduled.start.strftime('%a %d %b %H:%M'), effort=effort and",
"row generated by ``row_from_node`` orgpathname_list: list of `orgpathname` orgpathname: dict",
"``datetime.date`` object. \"\"\" previous = None odd = True for",
"= None odd = True for (key, row) in key_table:",
"jinja2 template. Data is dictionary like this: table: list of",
"rootname from ARCHIVE_OLPATH property. Return None if not found. \"\"\"",
"rootname_from_archive_olpath(node) if not rootname: n = node p = node.parent",
"itertools from .utils.date import minutestr, total_minutes def rootname_from_archive_olpath(node): \"\"\" Find",
"node.parent while not p.is_root(): n = p p = p.parent",
"table converter\"\"\" import os import datetime import itertools from .utils.date",
"def get_data(orgnodes_list, orgpath_list, done, num=100): \"\"\" Get data for rendering",
"if not sameday(this, previous): odd = not odd row['oddday'] =",
"orgname) in zip(orgpath_list, orgname_list)] key_table.sort(reverse=True) table_add_oddday(key_table) table = list(itertools.islice((row for",
"find rootname rootname = find_rootname(node) if heading == rootname: rootname",
"olpath = node.get_property('ARCHIVE_OLPATH') if olpath: olpathlist = olpath.split('/', 1) if",
"= node.closed scheduled = node.scheduled effort = node.get_property('Effort') row =",
"\"\"\" Get data for rendering jinja2 template. Data is dictionary",
"in each rows of key_table *IN PLACE*. Note that key",
"previous): odd = not odd row['oddday'] = odd previous =",
"None odd = True for (key, row) in key_table: this",
"= name i = 1 while name not in namelist:",
"return None def find_rootname(node): \"\"\" Find rootname given node \"\"\"",
"if not rootname: n = node p = node.parent while",
"%b %H:%M'), effort=effort and minutestr(effort), clocksum=clocksum and minutestr(clocksum), rootname=rootname, )",
"node.clock if clocklist: clocksum = sum([total_minutes(c.duration) for c in clocklist])",
"(closed.start if closed else None, row) def unique_name_from_paths(pathlist): namelist =",
"os.path.basename(path) if name in namelist: name_orig = name i =",
"for rendering jinja2 template. Data is dictionary like this: table:",
"\"\"\" heading = node.heading # find rootname rootname = find_rootname(node)",
"namelist.append(name) return namelist def sameday(dt1, dt2): return (isinstance(dt1, datetime.date) and",
"dummy) = olpathlist else: rootname = olpath return rootname return",
"scheduled.start.strftime('%a %d %b %H:%M'), effort=effort and minutestr(effort), clocksum=clocksum and minutestr(clocksum),",
"= [] for path in pathlist: name = os.path.basename(path) if",
"keywords: heading, closed, scheduled, effort, clocksum, rootname. \"\"\" heading =",
"\"\"\" Find rootname from ARCHIVE_OLPATH property. Return None if not",
"if heading == rootname: rootname = \"\" # calc clocksum",
"== done: (key, row) = key_row_from_node(node) if key: row['orgname'] =",
"a title \"\"\" key_table = [] orgname_list = unique_name_from_paths(orgpath_list) for",
"if name in namelist: name_orig = name i = 1",
"unique_name_from_paths(orgpath_list) for (nodelist, orgname) in zip(orgnodes_list, orgname_list): for node in",
"has following keywords: heading, closed, scheduled, effort, clocksum, rootname. \"\"\"",
"%d %b %H:%M'), effort=effort and minutestr(effort), clocksum=clocksum and minutestr(clocksum), rootname=rootname,",
"1: (rootname, dummy) = olpathlist else: rootname = olpath return",
"== dt2.month and dt1.day == dt2.day) def table_add_oddday(key_table): \"\"\" Add",
"html table converter\"\"\" import os import datetime import itertools from",
"key: row['orgname'] = orgname key_table.append((key, row)) orgpathname_list = [ dict(orgpath=orgpath,",
"node.closed scheduled = node.scheduled effort = node.get_property('Effort') row = dict(",
"<filename>orgviz/dones.py #!/usr/bin/env python \"\"\"org archive to html table converter\"\"\" import",
"orgpathname_list: list of `orgpathname` orgpathname: dict contains `orgpath` and `orgname`.",
"in namelist: name = \"%s <%d>\" % (name_orig, i) i",
"contains `orgpath` and `orgname`. `orgname` is short and unique name",
"= '' clocklist = node.clock if clocklist: clocksum = sum([total_minutes(c.duration)",
"def unique_name_from_paths(pathlist): namelist = [] for path in pathlist: name",
"def table_add_oddday(key_table): \"\"\" Add oddday key in each rows of",
"given node \"\"\" rootname = rootname_from_archive_olpath(node) if not rootname: n",
"`orgname` is short and unique name for `orgpath`. title: str",
"rootname=rootname, ) return (closed.start if closed else None, row) def",
"None def find_rootname(node): \"\"\" Find rootname given node \"\"\" rootname",
"if not found. \"\"\" olpath = node.get_property('ARCHIVE_OLPATH') if olpath: olpathlist",
"if olpath: olpathlist = olpath.split('/', 1) if len(olpathlist) > 1:",
"= node.clock if clocklist: clocksum = sum([total_minutes(c.duration) for c in",
"minutestr(clocksum), rootname=rootname, ) return (closed.start if closed else None, row)",
"'' clocklist = node.clock if clocklist: clocksum = sum([total_minutes(c.duration) for",
"rootname = rootname_from_archive_olpath(node) if not rootname: n = node p",
"= dict( heading=heading, closed=closed and closed.start.strftime('%a %d %b %H:%M'), scheduled=scheduled",
"pathlist: name = os.path.basename(path) if name in namelist: name_orig =",
"datetime.date) and isinstance(dt2, datetime.date) and dt1.year == dt2.year and dt1.month",
"heading == rootname: rootname = \"\" # calc clocksum if",
"from .utils.date import minutestr, total_minutes def rootname_from_archive_olpath(node): \"\"\" Find rootname",
"is dictionary like this: table: list of `row` list of",
"for c in clocklist]) closed = node.closed scheduled = node.scheduled",
"archive to html table converter\"\"\" import os import datetime import",
"node p = node.parent while not p.is_root(): n = p",
"i += 1 namelist.append(name) return namelist def sameday(dt1, dt2): return",
"whose elemens are key object for sorting table and dictionary",
"key_table = [] orgname_list = unique_name_from_paths(orgpath_list) for (nodelist, orgname) in",
"= this def get_data(orgnodes_list, orgpath_list, done, num=100): \"\"\" Get data",
"exists clocksum = '' clocklist = node.clock if clocklist: clocksum",
"`orgname`. `orgname` is short and unique name for `orgpath`. title:",
"are key object for sorting table and dictionary which has",
"list of row generated by ``row_from_node`` orgpathname_list: list of `orgpathname`",
"dictionary which has following keywords: heading, closed, scheduled, effort, clocksum,",
"dict(orgpath=orgpath, orgname=orgname) for (orgpath, orgname) in zip(orgpath_list, orgname_list)] key_table.sort(reverse=True) table_add_oddday(key_table)",
"table and dictionary which has following keywords: heading, closed, scheduled,",
"#!/usr/bin/env python \"\"\"org archive to html table converter\"\"\" import os",
"[ dict(orgpath=orgpath, orgname=orgname) for (orgpath, orgname) in zip(orgpath_list, orgname_list)] key_table.sort(reverse=True)",
"following keywords: heading, closed, scheduled, effort, clocksum, rootname. \"\"\" heading",
"find_rootname(node) if heading == rootname: rootname = \"\" # calc",
"\"\"\"org archive to html table converter\"\"\" import os import datetime",
"in zip(orgnodes_list, orgname_list): for node in nodelist: if node.todo ==",
"= [] orgname_list = unique_name_from_paths(orgpath_list) for (nodelist, orgname) in zip(orgnodes_list,",
"or n.heading return rootname def key_row_from_node(node): \"\"\" Return three tuple",
"clocksum=clocksum and minutestr(clocksum), rootname=rootname, ) return (closed.start if closed else",
"while name not in namelist: name = \"%s <%d>\" %",
"name in namelist: name_orig = name i = 1 while",
"= orgname key_table.append((key, row)) orgpathname_list = [ dict(orgpath=orgpath, orgname=orgname) for",
"and closed.start.strftime('%a %d %b %H:%M'), scheduled=scheduled and scheduled.start.strftime('%a %d %b",
"be a ``datetime.date`` object. \"\"\" previous = None odd =",
"i = 1 while name not in namelist: name =",
"return rootname def key_row_from_node(node): \"\"\" Return three tuple (key, row)",
"sameday(dt1, dt2): return (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date) and dt1.year",
"previous = None odd = True for (key, row) in",
"= unique_name_from_paths(orgpath_list) for (nodelist, orgname) in zip(orgnodes_list, orgname_list): for node",
"of `row` list of row generated by ``row_from_node`` orgpathname_list: list",
"while not p.is_root(): n = p p = p.parent #",
"rootname rootname = find_rootname(node) if heading == rootname: rootname =",
"dt1.year == dt2.year and dt1.month == dt2.month and dt1.day ==",
"node.heading # find rootname rootname = find_rootname(node) if heading ==",
"closed else None, row) def unique_name_from_paths(pathlist): namelist = [] for",
"== dt2.day) def table_add_oddday(key_table): \"\"\" Add oddday key in each",
"orgname_list): for node in nodelist: if node.todo == done: (key,",
"\"\" # calc clocksum if CLOCK exists clocksum = ''",
"effort=effort and minutestr(effort), clocksum=clocksum and minutestr(clocksum), rootname=rootname, ) return (closed.start",
"for (key, row) in key_table: this = key if not",
"for path in pathlist: name = os.path.basename(path) if name in",
"if clocklist: clocksum = sum([total_minutes(c.duration) for c in clocklist]) closed",
"path in pathlist: name = os.path.basename(path) if name in namelist:",
"closed.start.strftime('%a %d %b %H:%M'), scheduled=scheduled and scheduled.start.strftime('%a %d %b %H:%M'),",
"else: rootname = olpath return rootname return None def find_rootname(node):",
"p = node.parent while not p.is_root(): n = p p",
"scheduled, effort, clocksum, rootname. \"\"\" heading = node.heading # find",
"rootname_from_archive_olpath(node): \"\"\" Find rootname from ARCHIVE_OLPATH property. Return None if",
"closed, scheduled, effort, clocksum, rootname. \"\"\" heading = node.heading #",
"is root node rootname = rootname_from_archive_olpath(n) or n.heading return rootname",
"minutestr, total_minutes def rootname_from_archive_olpath(node): \"\"\" Find rootname from ARCHIVE_OLPATH property.",
"(key, row) whose elemens are key object for sorting table",
"this = key if not sameday(this, previous): odd = not",
"`orgpathname` orgpathname: dict contains `orgpath` and `orgname`. `orgname` is short",
"dictionary like this: table: list of `row` list of row",
"> 1: (rootname, dummy) = olpathlist else: rootname = olpath",
"orgname=orgname) for (orgpath, orgname) in zip(orgpath_list, orgname_list)] key_table.sort(reverse=True) table_add_oddday(key_table) table",
"key if not sameday(this, previous): odd = not odd row['oddday']",
"generated by ``row_from_node`` orgpathname_list: list of `orgpathname` orgpathname: dict contains",
"CLOCK exists clocksum = '' clocklist = node.clock if clocklist:",
"(nodelist, orgname) in zip(orgnodes_list, orgname_list): for node in nodelist: if",
"name_orig = name i = 1 while name not in",
"olpath.split('/', 1) if len(olpathlist) > 1: (rootname, dummy) = olpathlist",
"scheduled=scheduled and scheduled.start.strftime('%a %d %b %H:%M'), effort=effort and minutestr(effort), clocksum=clocksum",
"\"\"\" olpath = node.get_property('ARCHIVE_OLPATH') if olpath: olpathlist = olpath.split('/', 1)",
"= node.get_property('ARCHIVE_OLPATH') if olpath: olpathlist = olpath.split('/', 1) if len(olpathlist)",
"row) whose elemens are key object for sorting table and",
"# n is root node rootname = rootname_from_archive_olpath(n) or n.heading",
"key in each rows of key_table *IN PLACE*. Note that",
"(name_orig, i) i += 1 namelist.append(name) return namelist def sameday(dt1,",
"effort, clocksum, rootname. \"\"\" heading = node.heading # find rootname",
"should be a ``datetime.date`` object. \"\"\" previous = None odd",
"sameday(this, previous): odd = not odd row['oddday'] = odd previous",
"done: (key, row) = key_row_from_node(node) if key: row['orgname'] = orgname",
"== rootname: rootname = \"\" # calc clocksum if CLOCK",
"Add oddday key in each rows of key_table *IN PLACE*.",
"key object for sorting table and dictionary which has following",
"Return three tuple (key, row) whose elemens are key object",
"clocksum = '' clocklist = node.clock if clocklist: clocksum =",
"orgname) in zip(orgnodes_list, orgname_list): for node in nodelist: if node.todo",
"in clocklist]) closed = node.closed scheduled = node.scheduled effort =",
"for (orgpath, orgname) in zip(orgpath_list, orgname_list)] key_table.sort(reverse=True) table_add_oddday(key_table) table =",
"list(itertools.islice((row for (key, row) in key_table), num)) return dict(table=table, orgpathname_list=orgpathname_list,",
"Get data for rendering jinja2 template. Data is dictionary like",
"Find rootname given node \"\"\" rootname = rootname_from_archive_olpath(node) if not",
"that key should be a ``datetime.date`` object. \"\"\" previous =",
"Find rootname from ARCHIVE_OLPATH property. Return None if not found.",
"namelist: name = \"%s <%d>\" % (name_orig, i) i +=",
"= rootname_from_archive_olpath(n) or n.heading return rootname def key_row_from_node(node): \"\"\" Return",
"= True for (key, row) in key_table: this = key",
"and scheduled.start.strftime('%a %d %b %H:%M'), effort=effort and minutestr(effort), clocksum=clocksum and",
"rootname given node \"\"\" rootname = rootname_from_archive_olpath(node) if not rootname:",
"row) = key_row_from_node(node) if key: row['orgname'] = orgname key_table.append((key, row))",
"key_row_from_node(node) if key: row['orgname'] = orgname key_table.append((key, row)) orgpathname_list =",
"import datetime import itertools from .utils.date import minutestr, total_minutes def",
"if key: row['orgname'] = orgname key_table.append((key, row)) orgpathname_list = [",
"and dt1.year == dt2.year and dt1.month == dt2.month and dt1.day",
"dict contains `orgpath` and `orgname`. `orgname` is short and unique",
"rootname = find_rootname(node) if heading == rootname: rootname = \"\"",
"calc clocksum if CLOCK exists clocksum = '' clocklist =",
"= [ dict(orgpath=orgpath, orgname=orgname) for (orgpath, orgname) in zip(orgpath_list, orgname_list)]",
"1 namelist.append(name) return namelist def sameday(dt1, dt2): return (isinstance(dt1, datetime.date)",
"if node.todo == done: (key, row) = key_row_from_node(node) if key:",
"unique_name_from_paths(pathlist): namelist = [] for path in pathlist: name =",
"True for (key, row) in key_table: this = key if",
"and isinstance(dt2, datetime.date) and dt1.year == dt2.year and dt1.month ==",
"odd row['oddday'] = odd previous = this def get_data(orgnodes_list, orgpath_list,",
"effort = node.get_property('Effort') row = dict( heading=heading, closed=closed and closed.start.strftime('%a",
"closed=closed and closed.start.strftime('%a %d %b %H:%M'), scheduled=scheduled and scheduled.start.strftime('%a %d",
"found. \"\"\" olpath = node.get_property('ARCHIVE_OLPATH') if olpath: olpathlist = olpath.split('/',",
"heading, closed, scheduled, effort, clocksum, rootname. \"\"\" heading = node.heading",
"name i = 1 while name not in namelist: name",
"by ``row_from_node`` orgpathname_list: list of `orgpathname` orgpathname: dict contains `orgpath`",
"clocksum, rootname. \"\"\" heading = node.heading # find rootname rootname",
"else None, row) def unique_name_from_paths(pathlist): namelist = [] for path",
"dt1.day == dt2.day) def table_add_oddday(key_table): \"\"\" Add oddday key in",
"c in clocklist]) closed = node.closed scheduled = node.scheduled effort",
"this: table: list of `row` list of row generated by",
"title: str a title \"\"\" key_table = [] orgname_list =",
"three tuple (key, row) whose elemens are key object for",
"in pathlist: name = os.path.basename(path) if name in namelist: name_orig",
"\"%s <%d>\" % (name_orig, i) i += 1 namelist.append(name) return",
"(isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date) and dt1.year == dt2.year and",
"(key, row) = key_row_from_node(node) if key: row['orgname'] = orgname key_table.append((key,",
"clocksum = sum([total_minutes(c.duration) for c in clocklist]) closed = node.closed",
"for (nodelist, orgname) in zip(orgnodes_list, orgname_list): for node in nodelist:",
"ARCHIVE_OLPATH property. Return None if not found. \"\"\" olpath =",
"olpathlist else: rootname = olpath return rootname return None def",
"\"\"\" Return three tuple (key, row) whose elemens are key",
"not in namelist: name = \"%s <%d>\" % (name_orig, i)",
"name for `orgpath`. title: str a title \"\"\" key_table =",
"not rootname: n = node p = node.parent while not",
"\"\"\" previous = None odd = True for (key, row)",
"olpath return rootname return None def find_rootname(node): \"\"\" Find rootname",
"zip(orgnodes_list, orgname_list): for node in nodelist: if node.todo == done:",
"not p.is_root(): n = p p = p.parent # n",
"orgpath_list, done, num=100): \"\"\" Get data for rendering jinja2 template.",
"datetime import itertools from .utils.date import minutestr, total_minutes def rootname_from_archive_olpath(node):",
"nodelist: if node.todo == done: (key, row) = key_row_from_node(node) if",
"rootname. \"\"\" heading = node.heading # find rootname rootname =",
"= find_rootname(node) if heading == rootname: rootname = \"\" #",
"row) def unique_name_from_paths(pathlist): namelist = [] for path in pathlist:",
"return (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date) and dt1.year == dt2.year",
"n is root node rootname = rootname_from_archive_olpath(n) or n.heading return",
"Note that key should be a ``datetime.date`` object. \"\"\" previous",
"p p = p.parent # n is root node rootname",
"%H:%M'), scheduled=scheduled and scheduled.start.strftime('%a %d %b %H:%M'), effort=effort and minutestr(effort),",
"rootname: n = node p = node.parent while not p.is_root():",
"n = node p = node.parent while not p.is_root(): n",
"orgpathname_list = [ dict(orgpath=orgpath, orgname=orgname) for (orgpath, orgname) in zip(orgpath_list,",
"short and unique name for `orgpath`. title: str a title",
"heading = node.heading # find rootname rootname = find_rootname(node) if",
"for (key, row) in key_table), num)) return dict(table=table, orgpathname_list=orgpathname_list, title='Recently",
"list of `orgpathname` orgpathname: dict contains `orgpath` and `orgname`. `orgname`",
"find_rootname(node): \"\"\" Find rootname given node \"\"\" rootname = rootname_from_archive_olpath(node)",
"Return None if not found. \"\"\" olpath = node.get_property('ARCHIVE_OLPATH') if",
"= olpathlist else: rootname = olpath return rootname return None",
"dt2.day) def table_add_oddday(key_table): \"\"\" Add oddday key in each rows",
"title \"\"\" key_table = [] orgname_list = unique_name_from_paths(orgpath_list) for (nodelist,",
"= p.parent # n is root node rootname = rootname_from_archive_olpath(n)",
"clocksum if CLOCK exists clocksum = '' clocklist = node.clock",
"\"\"\" Add oddday key in each rows of key_table *IN",
"= node.parent while not p.is_root(): n = p p =",
"row)) orgpathname_list = [ dict(orgpath=orgpath, orgname=orgname) for (orgpath, orgname) in",
"olpathlist = olpath.split('/', 1) if len(olpathlist) > 1: (rootname, dummy)",
"clocklist: clocksum = sum([total_minutes(c.duration) for c in clocklist]) closed =",
"len(olpathlist) > 1: (rootname, dummy) = olpathlist else: rootname =",
"def rootname_from_archive_olpath(node): \"\"\" Find rootname from ARCHIVE_OLPATH property. Return None",
"key_row_from_node(node): \"\"\" Return three tuple (key, row) whose elemens are",
"= odd previous = this def get_data(orgnodes_list, orgpath_list, done, num=100):",
"table_add_oddday(key_table): \"\"\" Add oddday key in each rows of key_table",
"namelist def sameday(dt1, dt2): return (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date)",
"name = os.path.basename(path) if name in namelist: name_orig = name",
"odd = True for (key, row) in key_table: this =",
"= node.heading # find rootname rootname = find_rootname(node) if heading",
"isinstance(dt2, datetime.date) and dt1.year == dt2.year and dt1.month == dt2.month",
"for node in nodelist: if node.todo == done: (key, row)",
"% (name_orig, i) i += 1 namelist.append(name) return namelist def",
"odd previous = this def get_data(orgnodes_list, orgpath_list, done, num=100): \"\"\"",
"(key, row) in key_table), num)) return dict(table=table, orgpathname_list=orgpathname_list, title='Recently archived",
"name not in namelist: name = \"%s <%d>\" % (name_orig,",
"dt2.month and dt1.day == dt2.day) def table_add_oddday(key_table): \"\"\" Add oddday",
"import os import datetime import itertools from .utils.date import minutestr,",
"of key_table *IN PLACE*. Note that key should be a",
"sum([total_minutes(c.duration) for c in clocklist]) closed = node.closed scheduled =",
"converter\"\"\" import os import datetime import itertools from .utils.date import",
"rows of key_table *IN PLACE*. Note that key should be",
"= olpath return rootname return None def find_rootname(node): \"\"\" Find",
"done, num=100): \"\"\" Get data for rendering jinja2 template. Data",
"import itertools from .utils.date import minutestr, total_minutes def rootname_from_archive_olpath(node): \"\"\"",
"rootname = rootname_from_archive_olpath(n) or n.heading return rootname def key_row_from_node(node): \"\"\"",
"`orgpath`. title: str a title \"\"\" key_table = [] orgname_list",
"return rootname return None def find_rootname(node): \"\"\" Find rootname given",
"key_table.sort(reverse=True) table_add_oddday(key_table) table = list(itertools.islice((row for (key, row) in key_table),",
"dt2): return (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date) and dt1.year ==",
"rootname = \"\" # calc clocksum if CLOCK exists clocksum",
"= os.path.basename(path) if name in namelist: name_orig = name i",
"and unique name for `orgpath`. title: str a title \"\"\"",
"node.todo == done: (key, row) = key_row_from_node(node) if key: row['orgname']",
"= 1 while name not in namelist: name = \"%s",
"in zip(orgpath_list, orgname_list)] key_table.sort(reverse=True) table_add_oddday(key_table) table = list(itertools.islice((row for (key,",
"i) i += 1 namelist.append(name) return namelist def sameday(dt1, dt2):",
"of `orgpathname` orgpathname: dict contains `orgpath` and `orgname`. `orgname` is",
"elemens are key object for sorting table and dictionary which",
"*IN PLACE*. Note that key should be a ``datetime.date`` object.",
"== dt2.year and dt1.month == dt2.month and dt1.day == dt2.day)",
"and minutestr(clocksum), rootname=rootname, ) return (closed.start if closed else None,",
"heading=heading, closed=closed and closed.start.strftime('%a %d %b %H:%M'), scheduled=scheduled and scheduled.start.strftime('%a",
"data for rendering jinja2 template. Data is dictionary like this:",
"clocklist = node.clock if clocklist: clocksum = sum([total_minutes(c.duration) for c",
"object. \"\"\" previous = None odd = True for (key,",
"\"\"\" rootname = rootname_from_archive_olpath(node) if not rootname: n = node",
"node in nodelist: if node.todo == done: (key, row) =",
") return (closed.start if closed else None, row) def unique_name_from_paths(pathlist):",
"is short and unique name for `orgpath`. title: str a",
"orgname_list = unique_name_from_paths(orgpath_list) for (nodelist, orgname) in zip(orgnodes_list, orgname_list): for",
"if closed else None, row) def unique_name_from_paths(pathlist): namelist = []",
"key_table: this = key if not sameday(this, previous): odd =",
"orgname key_table.append((key, row)) orgpathname_list = [ dict(orgpath=orgpath, orgname=orgname) for (orgpath,",
"row['oddday'] = odd previous = this def get_data(orgnodes_list, orgpath_list, done,",
"PLACE*. Note that key should be a ``datetime.date`` object. \"\"\"",
"name = \"%s <%d>\" % (name_orig, i) i += 1",
"total_minutes def rootname_from_archive_olpath(node): \"\"\" Find rootname from ARCHIVE_OLPATH property. Return",
"(rootname, dummy) = olpathlist else: rootname = olpath return rootname",
"row) in key_table: this = key if not sameday(this, previous):",
"= node.get_property('Effort') row = dict( heading=heading, closed=closed and closed.start.strftime('%a %d",
"return namelist def sameday(dt1, dt2): return (isinstance(dt1, datetime.date) and isinstance(dt2,",
"# calc clocksum if CLOCK exists clocksum = '' clocklist",
"this def get_data(orgnodes_list, orgpath_list, done, num=100): \"\"\" Get data for",
"tuple (key, row) whose elemens are key object for sorting",
"dict( heading=heading, closed=closed and closed.start.strftime('%a %d %b %H:%M'), scheduled=scheduled and",
"not sameday(this, previous): odd = not odd row['oddday'] = odd",
"key_table.append((key, row)) orgpathname_list = [ dict(orgpath=orgpath, orgname=orgname) for (orgpath, orgname)",
"rootname_from_archive_olpath(n) or n.heading return rootname def key_row_from_node(node): \"\"\" Return three",
"dt2.year and dt1.month == dt2.month and dt1.day == dt2.day) def",
"property. Return None if not found. \"\"\" olpath = node.get_property('ARCHIVE_OLPATH')",
"key_table *IN PLACE*. Note that key should be a ``datetime.date``",
"rootname: rootname = \"\" # calc clocksum if CLOCK exists",
"None, row) def unique_name_from_paths(pathlist): namelist = [] for path in",
"sorting table and dictionary which has following keywords: heading, closed,",
"node \"\"\" rootname = rootname_from_archive_olpath(node) if not rootname: n =",
"def sameday(dt1, dt2): return (isinstance(dt1, datetime.date) and isinstance(dt2, datetime.date) and",
"and dt1.day == dt2.day) def table_add_oddday(key_table): \"\"\" Add oddday key",
"%d %b %H:%M'), scheduled=scheduled and scheduled.start.strftime('%a %d %b %H:%M'), effort=effort",
"= p p = p.parent # n is root node",
"import minutestr, total_minutes def rootname_from_archive_olpath(node): \"\"\" Find rootname from ARCHIVE_OLPATH",
"list of `row` list of row generated by ``row_from_node`` orgpathname_list:",
"node rootname = rootname_from_archive_olpath(n) or n.heading return rootname def key_row_from_node(node):",
"row['orgname'] = orgname key_table.append((key, row)) orgpathname_list = [ dict(orgpath=orgpath, orgname=orgname)",
"previous = this def get_data(orgnodes_list, orgpath_list, done, num=100): \"\"\" Get",
"= sum([total_minutes(c.duration) for c in clocklist]) closed = node.closed scheduled",
"num=100): \"\"\" Get data for rendering jinja2 template. Data is",
"orgname_list)] key_table.sort(reverse=True) table_add_oddday(key_table) table = list(itertools.islice((row for (key, row) in",
"= \"\" # calc clocksum if CLOCK exists clocksum =",
"p.parent # n is root node rootname = rootname_from_archive_olpath(n) or",
"rootname = olpath return rootname return None def find_rootname(node): \"\"\"",
"node.scheduled effort = node.get_property('Effort') row = dict( heading=heading, closed=closed and",
"table_add_oddday(key_table) table = list(itertools.islice((row for (key, row) in key_table), num))",
"%H:%M'), effort=effort and minutestr(effort), clocksum=clocksum and minutestr(clocksum), rootname=rootname, ) return",
"oddday key in each rows of key_table *IN PLACE*. Note",
"``row_from_node`` orgpathname_list: list of `orgpathname` orgpathname: dict contains `orgpath` and",
"namelist = [] for path in pathlist: name = os.path.basename(path)",
"= node.scheduled effort = node.get_property('Effort') row = dict( heading=heading, closed=closed",
"for sorting table and dictionary which has following keywords: heading,",
"key should be a ``datetime.date`` object. \"\"\" previous = None",
"= node p = node.parent while not p.is_root(): n =",
"Data is dictionary like this: table: list of `row` list",
"olpath: olpathlist = olpath.split('/', 1) if len(olpathlist) > 1: (rootname,",
"return (closed.start if closed else None, row) def unique_name_from_paths(pathlist): namelist",
"row) in key_table), num)) return dict(table=table, orgpathname_list=orgpathname_list, title='Recently archived tasks')",
"like this: table: list of `row` list of row generated",
"= not odd row['oddday'] = odd previous = this def",
"python \"\"\"org archive to html table converter\"\"\" import os import",
"def key_row_from_node(node): \"\"\" Return three tuple (key, row) whose elemens",
"odd = not odd row['oddday'] = odd previous = this",
"= list(itertools.islice((row for (key, row) in key_table), num)) return dict(table=table,",
"rootname def key_row_from_node(node): \"\"\" Return three tuple (key, row) whose",
"= \"%s <%d>\" % (name_orig, i) i += 1 namelist.append(name)",
"`row` list of row generated by ``row_from_node`` orgpathname_list: list of",
"template. Data is dictionary like this: table: list of `row`",
"object for sorting table and dictionary which has following keywords:",
"zip(orgpath_list, orgname_list)] key_table.sort(reverse=True) table_add_oddday(key_table) table = list(itertools.islice((row for (key, row)"
] |
[
"OF ANY # KIND, either express or implied. See the",
"= tvm.size_var('n') m = tvm.size_var('m') l = tvm.size_var('l') A =",
"def test_nested(): n = tvm.size_var('n') c = tvm.size_var('c') h =",
"more contributor license agreements. See the NOTICE file # distributed",
"Apache Software Foundation (ASF) under one # or more contributor",
"WARRANTIES OR CONDITIONS OF ANY # KIND, either express or",
"2.0 (the # \"License\"); you may not use this file",
"@tvm.tag_scope(tag=\"conv\") def compute_conv(data, weight): N, IC, H, W = data.shape",
"C = compute_conv(A, B) assert C.op.tag == 'conv' assert len(C.op.attrs)",
"l), name='B') with tvm.tag_scope(tag=\"gemm\"): k = tvm.reduce_axis((0, l), name='k') C",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"= tvm.placeholder((c, c, kh, kw), name='B') try: with tvm.tag_scope(tag='conv'): C",
"specific language governing permissions and limitations # under the License.",
"under the License is distributed on an # \"AS IS\"",
"IC), name='ic') dh = tvm.reduce_axis((0, KH), name='dh') dw = tvm.reduce_axis((0,",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either",
"dw])) def test_with(): n = tvm.size_var('n') m = tvm.size_var('m') l",
"License. import json import tvm @tvm.tag_scope(tag=\"conv\") def compute_conv(data, weight): N,",
"l), name='A') B = tvm.placeholder((m, l), name='B') with tvm.tag_scope(tag=\"gemm\"): k",
"assert C.op.tag == 'gemm' assert \"hello\" in C.op.attrs assert \"xx\"",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #",
"+ 1 ic = tvm.reduce_axis((0, IC), name='ic') dh = tvm.reduce_axis((0,",
"compute_conv(A, B) assert C.op.tag == 'conv' assert len(C.op.attrs) == 0",
"k = tvm.reduce_axis((0, l), name='k') C = tvm.compute((n, m), lambda",
"c = tvm.size_var('c') h = tvm.size_var('h') w = tvm.size_var('w') kh",
"distributed with this work for additional information # regarding copyright",
"# str format happened to be json compatible assert json.loads(str(CC.op.attrs))[\"arr\"][1]",
"i, j: tvm.sum(A[i, k] * B[j, k], axis=k), attrs={\"hello\" :",
"= tvm.placeholder((m, l), name='B') with tvm.tag_scope(tag=\"gemm\"): k = tvm.reduce_axis((0, l),",
"for the # specific language governing permissions and limitations #",
"assert len(C.op.attrs) == 0 def test_nested(): n = tvm.size_var('n') c",
"See the License for the # specific language governing permissions",
"to in writing, # software distributed under the License is",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"json compatible assert json.loads(str(CC.op.attrs))[\"arr\"][1] == 12 def test_decorator(): n =",
"n = tvm.size_var('n') m = tvm.size_var('m') l = tvm.size_var('l') A",
"file # distributed with this work for additional information #",
"12 def test_decorator(): n = tvm.size_var('n') c = tvm.size_var('c') h",
"axis=k), attrs={\"hello\" : 1, \"arr\": [10, 12]}) assert C.op.tag ==",
"tvm.placeholder((n, l), name='A') B = tvm.placeholder((m, l), name='B') with tvm.tag_scope(tag=\"gemm\"):",
"= tvm.placeholder((c, c, kh, kw), name='B') C = compute_conv(A, B)",
"not in C.op.attrs assert C.op.attrs[\"hello\"].value == 1 CC = tvm.load_json(tvm.save_json(C))",
"c, h, w), name='A') B = tvm.placeholder((c, c, kh, kw),",
"implied. See the License for the # specific language governing",
"to you under the Apache License, Version 2.0 (the #",
"tvm @tvm.tag_scope(tag=\"conv\") def compute_conv(data, weight): N, IC, H, W =",
"OW = W - KW + 1 ic = tvm.reduce_axis((0,",
"IC, H, W = data.shape OC, IC, KH, KW =",
"len(C.op.attrs) == 0 def test_nested(): n = tvm.size_var('n') c =",
"may not use this file except in compliance # with",
"C.op.attrs assert C.op.attrs[\"hello\"].value == 1 CC = tvm.load_json(tvm.save_json(C)) assert CC.op.attrs[\"hello\"].value",
"OW), lambda i, oc, h, w: \\ tvm.sum(data[i, ic, h+dh,",
"License, Version 2.0 (the # \"License\"); you may not use",
"kw = tvm.size_var('kw') A = tvm.placeholder((n, c, h, w), name='A')",
"either express or implied. See the License for the #",
"tvm.size_var('kh') kw = tvm.size_var('kw') A = tvm.placeholder((n, c, h, w),",
"tvm.placeholder((m, l), name='B') with tvm.tag_scope(tag=\"gemm\"): k = tvm.reduce_axis((0, l), name='k')",
"= tvm.size_var('kw') A = tvm.placeholder((n, c, h, w), name='A') B",
"tvm.compute((N, OC, OH, OW), lambda i, oc, h, w: \\",
"tvm.size_var('h') w = tvm.size_var('w') kh = tvm.size_var('kh') kw = tvm.size_var('kw')",
"= compute_conv(A, B) assert False except ValueError: pass if __name__",
"ic = tvm.reduce_axis((0, IC), name='ic') dh = tvm.reduce_axis((0, KH), name='dh')",
"additional information # regarding copyright ownership. The ASF licenses this",
"* B[j, k], axis=k), attrs={\"hello\" : 1, \"arr\": [10, 12]})",
"See the NOTICE file # distributed with this work for",
"def compute_conv(data, weight): N, IC, H, W = data.shape OC,",
"tvm.reduce_axis((0, KH), name='dh') dw = tvm.reduce_axis((0, KW), name='dw') return tvm.compute((N,",
"== 10 # str format happened to be json compatible",
"Apache License, Version 2.0 (the # \"License\"); you may not",
"dw = tvm.reduce_axis((0, KW), name='dw') return tvm.compute((N, OC, OH, OW),",
"oc, h, w: \\ tvm.sum(data[i, ic, h+dh, w+dw] * weight[oc,",
"kw), name='B') C = compute_conv(A, B) assert C.op.tag == 'conv'",
"= tvm.size_var('m') l = tvm.size_var('l') A = tvm.placeholder((n, l), name='A')",
"c, kh, kw), name='B') try: with tvm.tag_scope(tag='conv'): C = compute_conv(A,",
"B = tvm.placeholder((c, c, kh, kw), name='B') try: with tvm.tag_scope(tag='conv'):",
"return tvm.compute((N, OC, OH, OW), lambda i, oc, h, w:",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"C = compute_conv(A, B) assert False except ValueError: pass if",
"file except in compliance # with the License. You may",
"= tvm.load_json(tvm.save_json(C)) assert CC.op.attrs[\"hello\"].value == 1 assert CC.op.attrs[\"arr\"][0].value == 10",
"# specific language governing permissions and limitations # under the",
"import json import tvm @tvm.tag_scope(tag=\"conv\") def compute_conv(data, weight): N, IC,",
"assert False except ValueError: pass if __name__ == \"__main__\": test_with()",
"you may not use this file except in compliance #",
"[10, 12]}) assert C.op.tag == 'gemm' assert \"hello\" in C.op.attrs",
"use this file except in compliance # with the License.",
"= tvm.size_var('l') A = tvm.placeholder((n, l), name='A') B = tvm.placeholder((m,",
"contributor license agreements. See the NOTICE file # distributed with",
"try: with tvm.tag_scope(tag='conv'): C = compute_conv(A, B) assert False except",
"tvm.size_var('n') c = tvm.size_var('c') h = tvm.size_var('h') w = tvm.size_var('w')",
"kh, kw), name='B') C = compute_conv(A, B) assert C.op.tag ==",
"= data.shape OC, IC, KH, KW = weight.shape OH =",
"an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express",
": 1, \"arr\": [10, 12]}) assert C.op.tag == 'gemm' assert",
"with this work for additional information # regarding copyright ownership.",
"1 ic = tvm.reduce_axis((0, IC), name='ic') dh = tvm.reduce_axis((0, KH),",
"CC = tvm.load_json(tvm.save_json(C)) assert CC.op.attrs[\"hello\"].value == 1 assert CC.op.attrs[\"arr\"][0].value ==",
"N, IC, H, W = data.shape OC, IC, KH, KW",
"name='k') C = tvm.compute((n, m), lambda i, j: tvm.sum(A[i, k]",
"be json compatible assert json.loads(str(CC.op.attrs))[\"arr\"][1] == 12 def test_decorator(): n",
"work for additional information # regarding copyright ownership. The ASF",
"name='ic') dh = tvm.reduce_axis((0, KH), name='dh') dw = tvm.reduce_axis((0, KW),",
"A = tvm.placeholder((n, c, h, w), name='A') B = tvm.placeholder((c,",
"the License. import json import tvm @tvm.tag_scope(tag=\"conv\") def compute_conv(data, weight):",
"data.shape OC, IC, KH, KW = weight.shape OH = H",
"tvm.size_var('kw') A = tvm.placeholder((n, c, h, w), name='A') B =",
"distributed under the License is distributed on an # \"AS",
"tvm.size_var('w') kh = tvm.size_var('kh') kw = tvm.size_var('kw') A = tvm.placeholder((n,",
"# software distributed under the License is distributed on an",
"name='dw') return tvm.compute((N, OC, OH, OW), lambda i, oc, h,",
"format happened to be json compatible assert json.loads(str(CC.op.attrs))[\"arr\"][1] == 12",
"happened to be json compatible assert json.loads(str(CC.op.attrs))[\"arr\"][1] == 12 def",
"the License. You may obtain a copy of the License",
"tvm.tag_scope(tag='conv'): C = compute_conv(A, B) assert False except ValueError: pass",
"under the Apache License, Version 2.0 (the # \"License\"); you",
"dh, dw])) def test_with(): n = tvm.size_var('n') m = tvm.size_var('m')",
"distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"regarding copyright ownership. The ASF licenses this file # to",
"or agreed to in writing, # software distributed under the",
"B) assert C.op.tag == 'conv' assert len(C.op.attrs) == 0 def",
"k] * B[j, k], axis=k), attrs={\"hello\" : 1, \"arr\": [10,",
"dw], axis=[ic, dh, dw])) def test_with(): n = tvm.size_var('n') m",
"n = tvm.size_var('n') c = tvm.size_var('c') h = tvm.size_var('h') w",
"\"hello\" in C.op.attrs assert \"xx\" not in C.op.attrs assert C.op.attrs[\"hello\"].value",
"json.loads(str(CC.op.attrs))[\"arr\"][1] == 12 def test_decorator(): n = tvm.size_var('n') c =",
"tvm.reduce_axis((0, l), name='k') C = tvm.compute((n, m), lambda i, j:",
"tvm.size_var('m') l = tvm.size_var('l') A = tvm.placeholder((n, l), name='A') B",
"or more contributor license agreements. See the NOTICE file #",
"compute_conv(A, B) assert False except ValueError: pass if __name__ ==",
"this work for additional information # regarding copyright ownership. The",
"the NOTICE file # distributed with this work for additional",
"dh = tvm.reduce_axis((0, KH), name='dh') dw = tvm.reduce_axis((0, KW), name='dw')",
"import tvm @tvm.tag_scope(tag=\"conv\") def compute_conv(data, weight): N, IC, H, W",
"KW = weight.shape OH = H - KH + 1",
"= W - KW + 1 ic = tvm.reduce_axis((0, IC),",
"m = tvm.size_var('m') l = tvm.size_var('l') A = tvm.placeholder((n, l),",
"'gemm' assert \"hello\" in C.op.attrs assert \"xx\" not in C.op.attrs",
"h, w: \\ tvm.sum(data[i, ic, h+dh, w+dw] * weight[oc, ic,",
"False except ValueError: pass if __name__ == \"__main__\": test_with() test_decorator()",
"tvm.size_var('c') h = tvm.size_var('h') w = tvm.size_var('w') kh = tvm.size_var('kh')",
"i, oc, h, w: \\ tvm.sum(data[i, ic, h+dh, w+dw] *",
"tvm.sum(data[i, ic, h+dh, w+dw] * weight[oc, ic, dh, dw], axis=[ic,",
"B = tvm.placeholder((c, c, kh, kw), name='B') C = compute_conv(A,",
"KIND, either express or implied. See the License for the",
"weight): N, IC, H, W = data.shape OC, IC, KH,",
"CC.op.attrs[\"arr\"][0].value == 10 # str format happened to be json",
"tvm.size_var('l') A = tvm.placeholder((n, l), name='A') B = tvm.placeholder((m, l),",
"w), name='A') B = tvm.placeholder((c, c, kh, kw), name='B') C",
"or implied. See the License for the # specific language",
"express or implied. See the License for the # specific",
"test_decorator(): n = tvm.size_var('n') c = tvm.size_var('c') h = tvm.size_var('h')",
"\\ tvm.sum(data[i, ic, h+dh, w+dw] * weight[oc, ic, dh, dw],",
"w+dw] * weight[oc, ic, dh, dw], axis=[ic, dh, dw])) def",
"= tvm.placeholder((n, c, h, w), name='A') B = tvm.placeholder((c, c,",
"in C.op.attrs assert C.op.attrs[\"hello\"].value == 1 CC = tvm.load_json(tvm.save_json(C)) assert",
"the # specific language governing permissions and limitations # under",
"assert \"xx\" not in C.op.attrs assert C.op.attrs[\"hello\"].value == 1 CC",
"may obtain a copy of the License at # #",
"w: \\ tvm.sum(data[i, ic, h+dh, w+dw] * weight[oc, ic, dh,",
"tvm.placeholder((c, c, kh, kw), name='B') try: with tvm.tag_scope(tag='conv'): C =",
"The ASF licenses this file # to you under the",
"= tvm.size_var('n') c = tvm.size_var('c') h = tvm.size_var('h') w =",
"attrs={\"hello\" : 1, \"arr\": [10, 12]}) assert C.op.tag == 'gemm'",
"# Licensed to the Apache Software Foundation (ASF) under one",
"= tvm.size_var('kh') kw = tvm.size_var('kw') A = tvm.placeholder((n, c, h,",
"law or agreed to in writing, # software distributed under",
"Foundation (ASF) under one # or more contributor license agreements.",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"= H - KH + 1 OW = W -",
"Software Foundation (ASF) under one # or more contributor license",
"# regarding copyright ownership. The ASF licenses this file #",
"in compliance # with the License. You may obtain a",
"# to you under the Apache License, Version 2.0 (the",
"License for the # specific language governing permissions and limitations",
"'conv' assert len(C.op.attrs) == 0 def test_nested(): n = tvm.size_var('n')",
"tvm.tag_scope(tag=\"gemm\"): k = tvm.reduce_axis((0, l), name='k') C = tvm.compute((n, m),",
"= tvm.reduce_axis((0, l), name='k') C = tvm.compute((n, m), lambda i,",
"OR CONDITIONS OF ANY # KIND, either express or implied.",
"under the License. import json import tvm @tvm.tag_scope(tag=\"conv\") def compute_conv(data,",
"C.op.tag == 'conv' assert len(C.op.attrs) == 0 def test_nested(): n",
"assert \"hello\" in C.op.attrs assert \"xx\" not in C.op.attrs assert",
"compute_conv(data, weight): N, IC, H, W = data.shape OC, IC,",
"this file # to you under the Apache License, Version",
"copyright ownership. The ASF licenses this file # to you",
"l), name='k') C = tvm.compute((n, m), lambda i, j: tvm.sum(A[i,",
"1 OW = W - KW + 1 ic =",
"ic, dh, dw], axis=[ic, dh, dw])) def test_with(): n =",
"with tvm.tag_scope(tag=\"gemm\"): k = tvm.reduce_axis((0, l), name='k') C = tvm.compute((n,",
"name='B') C = compute_conv(A, B) assert C.op.tag == 'conv' assert",
"in writing, # software distributed under the License is distributed",
"weight[oc, ic, dh, dw], axis=[ic, dh, dw])) def test_with(): n",
"limitations # under the License. import json import tvm @tvm.tag_scope(tag=\"conv\")",
"\"arr\": [10, 12]}) assert C.op.tag == 'gemm' assert \"hello\" in",
"0 def test_nested(): n = tvm.size_var('n') c = tvm.size_var('c') h",
"str format happened to be json compatible assert json.loads(str(CC.op.attrs))[\"arr\"][1] ==",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"License is distributed on an # \"AS IS\" BASIS, WITHOUT",
"C.op.tag == 'gemm' assert \"hello\" in C.op.attrs assert \"xx\" not",
"B) assert False except ValueError: pass if __name__ == \"__main__\":",
"+ 1 OW = W - KW + 1 ic",
"c, kh, kw), name='B') C = compute_conv(A, B) assert C.op.tag",
"# \"License\"); you may not use this file except in",
"* weight[oc, ic, dh, dw], axis=[ic, dh, dw])) def test_with():",
"# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"to the Apache Software Foundation (ASF) under one # or",
"lambda i, j: tvm.sum(A[i, k] * B[j, k], axis=k), attrs={\"hello\"",
"\"License\"); you may not use this file except in compliance",
"compatible assert json.loads(str(CC.op.attrs))[\"arr\"][1] == 12 def test_decorator(): n = tvm.size_var('n')",
"permissions and limitations # under the License. import json import",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"= tvm.size_var('c') h = tvm.size_var('h') w = tvm.size_var('w') kh =",
"test_with(): n = tvm.size_var('n') m = tvm.size_var('m') l = tvm.size_var('l')",
"# distributed with this work for additional information # regarding",
"W = data.shape OC, IC, KH, KW = weight.shape OH",
"kw), name='B') try: with tvm.tag_scope(tag='conv'): C = compute_conv(A, B) assert",
"writing, # software distributed under the License is distributed on",
"ic, h+dh, w+dw] * weight[oc, ic, dh, dw], axis=[ic, dh,",
"OC, IC, KH, KW = weight.shape OH = H -",
"H, W = data.shape OC, IC, KH, KW = weight.shape",
"CONDITIONS OF ANY # KIND, either express or implied. See",
"kh, kw), name='B') try: with tvm.tag_scope(tag='conv'): C = compute_conv(A, B)",
"KH + 1 OW = W - KW + 1",
"def test_with(): n = tvm.size_var('n') m = tvm.size_var('m') l =",
"C.op.attrs[\"hello\"].value == 1 CC = tvm.load_json(tvm.save_json(C)) assert CC.op.attrs[\"hello\"].value == 1",
"B[j, k], axis=k), attrs={\"hello\" : 1, \"arr\": [10, 12]}) assert",
"for additional information # regarding copyright ownership. The ASF licenses",
"- KW + 1 ic = tvm.reduce_axis((0, IC), name='ic') dh",
"assert C.op.tag == 'conv' assert len(C.op.attrs) == 0 def test_nested():",
"the Apache Software Foundation (ASF) under one # or more",
"# # Unless required by applicable law or agreed to",
"Version 2.0 (the # \"License\"); you may not use this",
"one # or more contributor license agreements. See the NOTICE",
"except ValueError: pass if __name__ == \"__main__\": test_with() test_decorator() test_nested()",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"k], axis=k), attrs={\"hello\" : 1, \"arr\": [10, 12]}) assert C.op.tag",
"KW + 1 ic = tvm.reduce_axis((0, IC), name='ic') dh =",
"except in compliance # with the License. You may obtain",
"tvm.placeholder((n, c, h, w), name='A') B = tvm.placeholder((c, c, kh,",
"name='A') B = tvm.placeholder((c, c, kh, kw), name='B') try: with",
"w = tvm.size_var('w') kh = tvm.size_var('kh') kw = tvm.size_var('kw') A",
"NOTICE file # distributed with this work for additional information",
"and limitations # under the License. import json import tvm",
"assert C.op.attrs[\"hello\"].value == 1 CC = tvm.load_json(tvm.save_json(C)) assert CC.op.attrs[\"hello\"].value ==",
"OC, OH, OW), lambda i, oc, h, w: \\ tvm.sum(data[i,",
"this file except in compliance # with the License. You",
"w), name='A') B = tvm.placeholder((c, c, kh, kw), name='B') try:",
"OH = H - KH + 1 OW = W",
"license agreements. See the NOTICE file # distributed with this",
"10 # str format happened to be json compatible assert",
"tvm.reduce_axis((0, KW), name='dw') return tvm.compute((N, OC, OH, OW), lambda i,",
"required by applicable law or agreed to in writing, #",
"assert CC.op.attrs[\"hello\"].value == 1 assert CC.op.attrs[\"arr\"][0].value == 10 # str",
"== 12 def test_decorator(): n = tvm.size_var('n') c = tvm.size_var('c')",
"= tvm.compute((n, m), lambda i, j: tvm.sum(A[i, k] * B[j,",
"12]}) assert C.op.tag == 'gemm' assert \"hello\" in C.op.attrs assert",
"name='A') B = tvm.placeholder((m, l), name='B') with tvm.tag_scope(tag=\"gemm\"): k =",
"the License for the # specific language governing permissions and",
"lambda i, oc, h, w: \\ tvm.sum(data[i, ic, h+dh, w+dw]",
"ANY # KIND, either express or implied. See the License",
"the License is distributed on an # \"AS IS\" BASIS,",
"1, \"arr\": [10, 12]}) assert C.op.tag == 'gemm' assert \"hello\"",
"OH, OW), lambda i, oc, h, w: \\ tvm.sum(data[i, ic,",
"= tvm.size_var('h') w = tvm.size_var('w') kh = tvm.size_var('kh') kw =",
"not use this file except in compliance # with the",
"tvm.compute((n, m), lambda i, j: tvm.sum(A[i, k] * B[j, k],",
"Unless required by applicable law or agreed to in writing,",
"W - KW + 1 ic = tvm.reduce_axis((0, IC), name='ic')",
"tvm.reduce_axis((0, IC), name='ic') dh = tvm.reduce_axis((0, KH), name='dh') dw =",
"(ASF) under one # or more contributor license agreements. See",
"== 1 assert CC.op.attrs[\"arr\"][0].value == 10 # str format happened",
"# or more contributor license agreements. See the NOTICE file",
"agreed to in writing, # software distributed under the License",
"== 'gemm' assert \"hello\" in C.op.attrs assert \"xx\" not in",
"= tvm.reduce_axis((0, KH), name='dh') dw = tvm.reduce_axis((0, KW), name='dw') return",
"to be json compatible assert json.loads(str(CC.op.attrs))[\"arr\"][1] == 12 def test_decorator():",
"- KH + 1 OW = W - KW +",
"j: tvm.sum(A[i, k] * B[j, k], axis=k), attrs={\"hello\" : 1,",
"KH), name='dh') dw = tvm.reduce_axis((0, KW), name='dw') return tvm.compute((N, OC,",
"= tvm.reduce_axis((0, KW), name='dw') return tvm.compute((N, OC, OH, OW), lambda",
"== 0 def test_nested(): n = tvm.size_var('n') c = tvm.size_var('c')",
"(the # \"License\"); you may not use this file except",
"ASF licenses this file # to you under the Apache",
"on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"H - KH + 1 OW = W - KW",
"name='dh') dw = tvm.reduce_axis((0, KW), name='dw') return tvm.compute((N, OC, OH,",
"ownership. The ASF licenses this file # to you under",
"tvm.sum(A[i, k] * B[j, k], axis=k), attrs={\"hello\" : 1, \"arr\":",
"== 1 CC = tvm.load_json(tvm.save_json(C)) assert CC.op.attrs[\"hello\"].value == 1 assert",
"assert json.loads(str(CC.op.attrs))[\"arr\"][1] == 12 def test_decorator(): n = tvm.size_var('n') c",
"A = tvm.placeholder((n, l), name='A') B = tvm.placeholder((m, l), name='B')",
"tvm.placeholder((c, c, kh, kw), name='B') C = compute_conv(A, B) assert",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"\"xx\" not in C.op.attrs assert C.op.attrs[\"hello\"].value == 1 CC =",
"= tvm.placeholder((n, l), name='A') B = tvm.placeholder((m, l), name='B') with",
"with the License. You may obtain a copy of the",
"with tvm.tag_scope(tag='conv'): C = compute_conv(A, B) assert False except ValueError:",
"applicable law or agreed to in writing, # software distributed",
"l = tvm.size_var('l') A = tvm.placeholder((n, l), name='A') B =",
"= tvm.reduce_axis((0, IC), name='ic') dh = tvm.reduce_axis((0, KH), name='dh') dw",
"in C.op.attrs assert \"xx\" not in C.op.attrs assert C.op.attrs[\"hello\"].value ==",
"h+dh, w+dw] * weight[oc, ic, dh, dw], axis=[ic, dh, dw]))",
"def test_decorator(): n = tvm.size_var('n') c = tvm.size_var('c') h =",
"is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES",
"file # to you under the Apache License, Version 2.0",
"m), lambda i, j: tvm.sum(A[i, k] * B[j, k], axis=k),",
"# with the License. You may obtain a copy of",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"software distributed under the License is distributed on an #",
"Licensed to the Apache Software Foundation (ASF) under one #",
"= tvm.size_var('w') kh = tvm.size_var('kh') kw = tvm.size_var('kw') A =",
"name='B') try: with tvm.tag_scope(tag='conv'): C = compute_conv(A, B) assert False",
"name='A') B = tvm.placeholder((c, c, kh, kw), name='B') C =",
"assert CC.op.attrs[\"arr\"][0].value == 10 # str format happened to be",
"under one # or more contributor license agreements. See the",
"name='B') with tvm.tag_scope(tag=\"gemm\"): k = tvm.reduce_axis((0, l), name='k') C =",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"dh, dw], axis=[ic, dh, dw])) def test_with(): n = tvm.size_var('n')",
"1 CC = tvm.load_json(tvm.save_json(C)) assert CC.op.attrs[\"hello\"].value == 1 assert CC.op.attrs[\"arr\"][0].value",
"h = tvm.size_var('h') w = tvm.size_var('w') kh = tvm.size_var('kh') kw",
"information # regarding copyright ownership. The ASF licenses this file",
"the Apache License, Version 2.0 (the # \"License\"); you may",
"governing permissions and limitations # under the License. import json",
"= weight.shape OH = H - KH + 1 OW",
"# under the License. import json import tvm @tvm.tag_scope(tag=\"conv\") def",
"tvm.load_json(tvm.save_json(C)) assert CC.op.attrs[\"hello\"].value == 1 assert CC.op.attrs[\"arr\"][0].value == 10 #",
"h, w), name='A') B = tvm.placeholder((c, c, kh, kw), name='B')",
"you under the Apache License, Version 2.0 (the # \"License\");",
"= compute_conv(A, B) assert C.op.tag == 'conv' assert len(C.op.attrs) ==",
"# KIND, either express or implied. See the License for",
"kh = tvm.size_var('kh') kw = tvm.size_var('kw') A = tvm.placeholder((n, c,",
"axis=[ic, dh, dw])) def test_with(): n = tvm.size_var('n') m =",
"tvm.size_var('n') m = tvm.size_var('m') l = tvm.size_var('l') A = tvm.placeholder((n,",
"KW), name='dw') return tvm.compute((N, OC, OH, OW), lambda i, oc,",
"agreements. See the NOTICE file # distributed with this work",
"language governing permissions and limitations # under the License. import",
"licenses this file # to you under the Apache License,",
"CC.op.attrs[\"hello\"].value == 1 assert CC.op.attrs[\"arr\"][0].value == 10 # str format",
"by applicable law or agreed to in writing, # software",
"# Unless required by applicable law or agreed to in",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,",
"C.op.attrs assert \"xx\" not in C.op.attrs assert C.op.attrs[\"hello\"].value == 1",
"B = tvm.placeholder((m, l), name='B') with tvm.tag_scope(tag=\"gemm\"): k = tvm.reduce_axis((0,",
"License. You may obtain a copy of the License at",
"You may obtain a copy of the License at #",
"weight.shape OH = H - KH + 1 OW =",
"test_nested(): n = tvm.size_var('n') c = tvm.size_var('c') h = tvm.size_var('h')",
"1 assert CC.op.attrs[\"arr\"][0].value == 10 # str format happened to",
"compliance # with the License. You may obtain a copy",
"IC, KH, KW = weight.shape OH = H - KH",
"KH, KW = weight.shape OH = H - KH +",
"json import tvm @tvm.tag_scope(tag=\"conv\") def compute_conv(data, weight): N, IC, H,",
"C = tvm.compute((n, m), lambda i, j: tvm.sum(A[i, k] *",
"== 'conv' assert len(C.op.attrs) == 0 def test_nested(): n ="
] |
[
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"with probabilistic uncertainties\" IFAC Proceedings (2014): 7079-7084 \"\"\" class Model",
"substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS",
"notice shall be included in all copies or substantial portions",
"super().__init__(name) def __call__ (self, x, u, p): f = lambda",
"scenario (no fault) \"\"\" def __init__ (self): super().__init__('M1') self._ode_func =",
"MSFB2014 \"\"\" <NAME>, <NAME>, <NAME> and <NAME> (2014) \"Active fault",
"(2014): 7079-7084 \"\"\" class Model (MSFB2014.Model): def __init__ (self, name):",
"= MSFB2014.M2() self.p0 = self._ode_func.p0 class M3 (Model): \"\"\" Circular",
"from scipy.integrate import odeint from ..continuous_time import MSFB2014 \"\"\" <NAME>,",
"__init__ (self): super().__init__('M2') self._ode_func = MSFB2014.M2() self.p0 = self._ode_func.p0 class",
"0.82, 0.96, 0.67 ]) def __call__ (self, x, u): return",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import",
"(self): super().__init__('M3') self._ode_func = MSFB2014.M3() self.p0 = self._ode_func.p0 class DataGen",
"\"\"\" Nominal scenario (no fault) \"\"\" def __init__ (self): super().__init__('M1')",
"u, p): f = lambda x,t: self._ode_func(x,u,p) t = np.linspace(0,",
"np from scipy.integrate import odeint from ..continuous_time import MSFB2014 \"\"\"",
"Software without restriction, including without limitation the rights to use,",
"import MSFB2014 \"\"\" <NAME>, <NAME>, <NAME> and <NAME> (2014) \"Active",
"= odeint(f, x, t) return X[-1] class M1 (Model): \"\"\"",
"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS",
"copies of the Software, and to permit persons to whom",
"hereby granted, free of charge, to any person obtaining a",
"to deal in the Software without restriction, including without limitation",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"super().__init__('M1') self._ode_func = MSFB2014.M1() self.p0 = self._ode_func.p0 class M2 (Model):",
"in inlet pump \"\"\" def __init__ (self): super().__init__('M2') self._ode_func =",
"class DataGen (M2): def __init__ (self): super().__init__() self.true_param = np.array([",
"numpy as np from scipy.integrate import odeint from ..continuous_time import",
"__init__ (self): super().__init__('M1') self._ode_func = MSFB2014.M1() self.p0 = self._ode_func.p0 class",
"portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",",
"DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"(Model): \"\"\" Circular leak in tank \"\"\" def __init__ (self):",
"modify, merge, publish, distribute, sublicense, and/or sell copies of the",
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"persons to whom the Software is furnished to do so,",
"__init__ (self, name): super().__init__(name) def __call__ (self, x, u, p):",
"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",
"self.p0 = self._ode_func.p0 class M2 (Model): \"\"\" Multiplicative actuator fault",
"of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A",
"self._ode_func.p0 class DataGen (M2): def __init__ (self): super().__init__() self.true_param =",
"Software is furnished to do so, subject to the following",
"Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"return super().__call__(x, u, self.true_param) def get (): return DataGen(), [M1(),",
"x, u, p): f = lambda x,t: self._ode_func(x,u,p) t =",
"sell copies of the Software, and to permit persons to",
"class M2 (Model): \"\"\" Multiplicative actuator fault in inlet pump",
"included in all copies or substantial portions of the Software.",
"SOFTWARE. \"\"\" import numpy as np from scipy.integrate import odeint",
"= self._ode_func.p0 class M3 (Model): \"\"\" Circular leak in tank",
"<reponame>scwolof/doepy<gh_stars>1-10 \"\"\" MIT License Copyright (c) 2019 <NAME> Permission is",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"\"\"\" Circular leak in tank \"\"\" def __init__ (self): super().__init__('M3')",
"odeint from ..continuous_time import MSFB2014 \"\"\" <NAME>, <NAME>, <NAME> and",
"import numpy as np from scipy.integrate import odeint from ..continuous_time",
"def __init__ (self): super().__init__('M1') self._ode_func = MSFB2014.M1() self.p0 = self._ode_func.p0",
"self._ode_func.p0 class M3 (Model): \"\"\" Circular leak in tank \"\"\"",
"MSFB2014.M2() self.p0 = self._ode_func.p0 class M3 (Model): \"\"\" Circular leak",
"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",
"(self): super().__init__() self.true_param = np.array([ 0.97, 0.82, 0.96, 0.67 ])",
"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"publish, distribute, sublicense, and/or sell copies of the Software, and",
"\"\"\" class Model (MSFB2014.Model): def __init__ (self, name): super().__init__(name) def",
"t) return X[-1] class M1 (Model): \"\"\" Nominal scenario (no",
"\"Software\"), to deal in the Software without restriction, including without",
"MIT License Copyright (c) 2019 <NAME> Permission is hereby granted,",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"License Copyright (c) 2019 <NAME> Permission is hereby granted, free",
"\"\"\" <NAME>, <NAME>, <NAME> and <NAME> (2014) \"Active fault diagnosis",
"diagnosis for nonlinear systems with probabilistic uncertainties\" IFAC Proceedings (2014):",
"self.dt, 51) X = odeint(f, x, t) return X[-1] class",
"as np from scipy.integrate import odeint from ..continuous_time import MSFB2014",
"be included in all copies or substantial portions of the",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"pump \"\"\" def __init__ (self): super().__init__('M2') self._ode_func = MSFB2014.M2() self.p0",
"u, self.true_param) def get (): return DataGen(), [M1(), M2(), M3()]",
"lambda x,t: self._ode_func(x,u,p) t = np.linspace(0, self.dt, 51) X =",
"fault diagnosis for nonlinear systems with probabilistic uncertainties\" IFAC Proceedings",
"super().__init__('M3') self._ode_func = MSFB2014.M3() self.p0 = self._ode_func.p0 class DataGen (M2):",
"in tank \"\"\" def __init__ (self): super().__init__('M3') self._ode_func = MSFB2014.M3()",
"<NAME>, <NAME>, <NAME> and <NAME> (2014) \"Active fault diagnosis for",
"MSFB2014.M3() self.p0 = self._ode_func.p0 class DataGen (M2): def __init__ (self):",
"def __init__ (self): super().__init__('M3') self._ode_func = MSFB2014.M3() self.p0 = self._ode_func.p0",
"__init__ (self): super().__init__() self.true_param = np.array([ 0.97, 0.82, 0.96, 0.67",
"USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import numpy",
"the following conditions: The above copyright notice and this permission",
"files (the \"Software\"), to deal in the Software without restriction,",
"(self, x, u): return super().__call__(x, u, self.true_param) def get ():",
"__call__ (self, x, u): return super().__call__(x, u, self.true_param) def get",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF",
"the rights to use, copy, modify, merge, publish, distribute, sublicense,",
"= MSFB2014.M1() self.p0 = self._ode_func.p0 class M2 (Model): \"\"\" Multiplicative",
"inlet pump \"\"\" def __init__ (self): super().__init__('M2') self._ode_func = MSFB2014.M2()",
"uncertainties\" IFAC Proceedings (2014): 7079-7084 \"\"\" class Model (MSFB2014.Model): def",
"software and associated documentation files (the \"Software\"), to deal in",
"notice and this permission notice shall be included in all",
"is hereby granted, free of charge, to any person obtaining",
"self._ode_func = MSFB2014.M2() self.p0 = self._ode_func.p0 class M3 (Model): \"\"\"",
"from ..continuous_time import MSFB2014 \"\"\" <NAME>, <NAME>, <NAME> and <NAME>",
"DataGen (M2): def __init__ (self): super().__init__() self.true_param = np.array([ 0.97,",
"to the following conditions: The above copyright notice and this",
"conditions: The above copyright notice and this permission notice shall",
"the Software without restriction, including without limitation the rights to",
"THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"X[-1] class M1 (Model): \"\"\" Nominal scenario (no fault) \"\"\"",
"and/or sell copies of the Software, and to permit persons",
"permit persons to whom the Software is furnished to do",
"do so, subject to the following conditions: The above copyright",
"any person obtaining a copy of this software and associated",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"\"Active fault diagnosis for nonlinear systems with probabilistic uncertainties\" IFAC",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"super().__call__(x, u, self.true_param) def get (): return DataGen(), [M1(), M2(),",
"(Model): \"\"\" Multiplicative actuator fault in inlet pump \"\"\" def",
"THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"copy of this software and associated documentation files (the \"Software\"),",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"including without limitation the rights to use, copy, modify, merge,",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"M3 (Model): \"\"\" Circular leak in tank \"\"\" def __init__",
"fault) \"\"\" def __init__ (self): super().__init__('M1') self._ode_func = MSFB2014.M1() self.p0",
"IFAC Proceedings (2014): 7079-7084 \"\"\" class Model (MSFB2014.Model): def __init__",
"x, t) return X[-1] class M1 (Model): \"\"\" Nominal scenario",
"(self, x, u, p): f = lambda x,t: self._ode_func(x,u,p) t",
"without limitation the rights to use, copy, modify, merge, publish,",
"\"\"\" def __init__ (self): super().__init__('M1') self._ode_func = MSFB2014.M1() self.p0 =",
"def __call__ (self, x, u, p): f = lambda x,t:",
"restriction, including without limitation the rights to use, copy, modify,",
"to permit persons to whom the Software is furnished to",
"Proceedings (2014): 7079-7084 \"\"\" class Model (MSFB2014.Model): def __init__ (self,",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"]) def __call__ (self, x, u): return super().__call__(x, u, self.true_param)",
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"deal in the Software without restriction, including without limitation the",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR",
"self._ode_func.p0 class M2 (Model): \"\"\" Multiplicative actuator fault in inlet",
"<NAME>, <NAME> and <NAME> (2014) \"Active fault diagnosis for nonlinear",
"ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"distribute, sublicense, and/or sell copies of the Software, and to",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR",
"(self): super().__init__('M1') self._ode_func = MSFB2014.M1() self.p0 = self._ode_func.p0 class M2",
"..continuous_time import MSFB2014 \"\"\" <NAME>, <NAME>, <NAME> and <NAME> (2014)",
"the Software, and to permit persons to whom the Software",
"and associated documentation files (the \"Software\"), to deal in the",
"the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"to whom the Software is furnished to do so, subject",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"(MSFB2014.Model): def __init__ (self, name): super().__init__(name) def __call__ (self, x,",
"0.97, 0.82, 0.96, 0.67 ]) def __call__ (self, x, u):",
"fault in inlet pump \"\"\" def __init__ (self): super().__init__('M2') self._ode_func",
"WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT",
"M2 (Model): \"\"\" Multiplicative actuator fault in inlet pump \"\"\"",
"systems with probabilistic uncertainties\" IFAC Proceedings (2014): 7079-7084 \"\"\" class",
"odeint(f, x, t) return X[-1] class M1 (Model): \"\"\" Nominal",
"TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE",
"OTHER DEALINGS IN THE SOFTWARE. \"\"\" import numpy as np",
"of the Software, and to permit persons to whom the",
"this software and associated documentation files (the \"Software\"), to deal",
"all copies or substantial portions of the Software. THE SOFTWARE",
"51) X = odeint(f, x, t) return X[-1] class M1",
"(the \"Software\"), to deal in the Software without restriction, including",
"merge, publish, distribute, sublicense, and/or sell copies of the Software,",
"so, subject to the following conditions: The above copyright notice",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"charge, to any person obtaining a copy of this software",
"to do so, subject to the following conditions: The above",
"(2014) \"Active fault diagnosis for nonlinear systems with probabilistic uncertainties\"",
"WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"following conditions: The above copyright notice and this permission notice",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"Multiplicative actuator fault in inlet pump \"\"\" def __init__ (self):",
"and <NAME> (2014) \"Active fault diagnosis for nonlinear systems with",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"<NAME> and <NAME> (2014) \"Active fault diagnosis for nonlinear systems",
"self.true_param = np.array([ 0.97, 0.82, 0.96, 0.67 ]) def __call__",
"in the Software without restriction, including without limitation the rights",
"Circular leak in tank \"\"\" def __init__ (self): super().__init__('M3') self._ode_func",
"permission notice shall be included in all copies or substantial",
"= np.array([ 0.97, 0.82, 0.96, 0.67 ]) def __call__ (self,",
"__call__ (self, x, u, p): f = lambda x,t: self._ode_func(x,u,p)",
"(c) 2019 <NAME> Permission is hereby granted, free of charge,",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"class Model (MSFB2014.Model): def __init__ (self, name): super().__init__(name) def __call__",
"\"\"\" import numpy as np from scipy.integrate import odeint from",
"super().__init__('M2') self._ode_func = MSFB2014.M2() self.p0 = self._ode_func.p0 class M3 (Model):",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS",
"u): return super().__call__(x, u, self.true_param) def get (): return DataGen(),",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"copyright notice and this permission notice shall be included in",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"",
"Nominal scenario (no fault) \"\"\" def __init__ (self): super().__init__('M1') self._ode_func",
"and to permit persons to whom the Software is furnished",
"leak in tank \"\"\" def __init__ (self): super().__init__('M3') self._ode_func =",
"copies or substantial portions of the Software. THE SOFTWARE IS",
"x, u): return super().__call__(x, u, self.true_param) def get (): return",
"OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED",
"self.p0 = self._ode_func.p0 class DataGen (M2): def __init__ (self): super().__init__()",
"7079-7084 \"\"\" class Model (MSFB2014.Model): def __init__ (self, name): super().__init__(name)",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"= MSFB2014.M3() self.p0 = self._ode_func.p0 class DataGen (M2): def __init__",
"Copyright (c) 2019 <NAME> Permission is hereby granted, free of",
"self.p0 = self._ode_func.p0 class M3 (Model): \"\"\" Circular leak in",
"DEALINGS IN THE SOFTWARE. \"\"\" import numpy as np from",
"whom the Software is furnished to do so, subject to",
"<NAME> Permission is hereby granted, free of charge, to any",
"(M2): def __init__ (self): super().__init__() self.true_param = np.array([ 0.97, 0.82,",
"X = odeint(f, x, t) return X[-1] class M1 (Model):",
"= self._ode_func.p0 class M2 (Model): \"\"\" Multiplicative actuator fault in",
"\"\"\" def __init__ (self): super().__init__('M3') self._ode_func = MSFB2014.M3() self.p0 =",
"self._ode_func = MSFB2014.M3() self.p0 = self._ode_func.p0 class DataGen (M2): def",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT",
"in all copies or substantial portions of the Software. THE",
"obtaining a copy of this software and associated documentation files",
"import odeint from ..continuous_time import MSFB2014 \"\"\" <NAME>, <NAME>, <NAME>",
"class M1 (Model): \"\"\" Nominal scenario (no fault) \"\"\" def",
"def __call__ (self, x, u): return super().__call__(x, u, self.true_param) def",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
"\"\"\" def __init__ (self): super().__init__('M2') self._ode_func = MSFB2014.M2() self.p0 =",
"name): super().__init__(name) def __call__ (self, x, u, p): f =",
"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",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"(self): super().__init__('M2') self._ode_func = MSFB2014.M2() self.p0 = self._ode_func.p0 class M3",
"t = np.linspace(0, self.dt, 51) X = odeint(f, x, t)",
"def __init__ (self): super().__init__() self.true_param = np.array([ 0.97, 0.82, 0.96,",
"sublicense, and/or sell copies of the Software, and to permit",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR",
"OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"0.96, 0.67 ]) def __call__ (self, x, u): return super().__call__(x,",
"for nonlinear systems with probabilistic uncertainties\" IFAC Proceedings (2014): 7079-7084",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF",
"this permission notice shall be included in all copies or",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"above copyright notice and this permission notice shall be included",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"super().__init__() self.true_param = np.array([ 0.97, 0.82, 0.96, 0.67 ]) def",
"f = lambda x,t: self._ode_func(x,u,p) t = np.linspace(0, self.dt, 51)",
"\"\"\" Multiplicative actuator fault in inlet pump \"\"\" def __init__",
"\"\"\" MIT License Copyright (c) 2019 <NAME> Permission is hereby",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,",
"MSFB2014.M1() self.p0 = self._ode_func.p0 class M2 (Model): \"\"\" Multiplicative actuator",
"M1 (Model): \"\"\" Nominal scenario (no fault) \"\"\" def __init__",
"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:",
"nonlinear systems with probabilistic uncertainties\" IFAC Proceedings (2014): 7079-7084 \"\"\"",
"self._ode_func(x,u,p) t = np.linspace(0, self.dt, 51) X = odeint(f, x,",
"def __init__ (self): super().__init__('M2') self._ode_func = MSFB2014.M2() self.p0 = self._ode_func.p0",
"to any person obtaining a copy of this software and",
"class M3 (Model): \"\"\" Circular leak in tank \"\"\" def",
"shall be included in all copies or substantial portions of",
"person obtaining a copy of this software and associated documentation",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN",
"__init__ (self): super().__init__('M3') self._ode_func = MSFB2014.M3() self.p0 = self._ode_func.p0 class",
"and this permission notice shall be included in all copies",
"def __init__ (self, name): super().__init__(name) def __call__ (self, x, u,",
"np.array([ 0.97, 0.82, 0.96, 0.67 ]) def __call__ (self, x,",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE",
"free of charge, to any person obtaining a copy of",
"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"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",
"scipy.integrate import odeint from ..continuous_time import MSFB2014 \"\"\" <NAME>, <NAME>,",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"(no fault) \"\"\" def __init__ (self): super().__init__('M1') self._ode_func = MSFB2014.M1()",
"THE SOFTWARE. \"\"\" import numpy as np from scipy.integrate import",
"rights to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import numpy as",
"p): f = lambda x,t: self._ode_func(x,u,p) t = np.linspace(0, self.dt,",
"documentation files (the \"Software\"), to deal in the Software without",
"= self._ode_func.p0 class DataGen (M2): def __init__ (self): super().__init__() self.true_param",
"np.linspace(0, self.dt, 51) X = odeint(f, x, t) return X[-1]",
"without restriction, including without limitation the rights to use, copy,",
"return X[-1] class M1 (Model): \"\"\" Nominal scenario (no fault)",
"(Model): \"\"\" Nominal scenario (no fault) \"\"\" def __init__ (self):",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"self._ode_func = MSFB2014.M1() self.p0 = self._ode_func.p0 class M2 (Model): \"\"\"",
"x,t: self._ode_func(x,u,p) t = np.linspace(0, self.dt, 51) X = odeint(f,",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"tank \"\"\" def __init__ (self): super().__init__('M3') self._ode_func = MSFB2014.M3() self.p0",
"= lambda x,t: self._ode_func(x,u,p) t = np.linspace(0, self.dt, 51) X",
"0.67 ]) def __call__ (self, x, u): return super().__call__(x, u,",
"NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"IN THE SOFTWARE. \"\"\" import numpy as np from scipy.integrate",
"granted, free of charge, to any person obtaining a copy",
"probabilistic uncertainties\" IFAC Proceedings (2014): 7079-7084 \"\"\" class Model (MSFB2014.Model):",
"(self, name): super().__init__(name) def __call__ (self, x, u, p): f",
"of charge, to any person obtaining a copy of this",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS",
"2019 <NAME> Permission is hereby granted, free of charge, to",
"Permission is hereby granted, free of charge, to any person",
"actuator fault in inlet pump \"\"\" def __init__ (self): super().__init__('M2')",
"Model (MSFB2014.Model): def __init__ (self, name): super().__init__(name) def __call__ (self,",
"The above copyright notice and this permission notice shall be",
"<NAME> (2014) \"Active fault diagnosis for nonlinear systems with probabilistic",
"= np.linspace(0, self.dt, 51) X = odeint(f, x, t) return",
"associated documentation files (the \"Software\"), to deal in the Software",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING"
] |
[
"import time as t class Orientation3D(object): \"\"\"Reads out all sensor",
"self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/error\", [operation, network_id, error_code[0]]) else:",
"position, self.dimension, self.height, self.algorithm, remote_id=self.remote_id) if status == POZYX_SUCCESS: #",
"height self.remote_id = remote_id def setup(self): \"\"\"There is no specific",
"(the acceleration excluding gravity) - the gravitational vector The data",
"the body coordinate system to the world coordinate system. -",
"device_list) for i in range(list_size[0]): anchor_coordinates = Coordinates() status =",
"is not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, error_code[0]]) return status =",
"UserInput.get_filename(to_use_file) attributes_to_log = UserInput.get_multiple_attributes_to_log() use_processing = True ip = \"127.0.0.1\"",
"printPublishErrorCode(self, operation): \"\"\"Prints the Pozyx's error and possibly sends it",
"POZYX_SUCCESS: status = self.pozyx.getAllSensorData(sensor_data, self.remote_id) status &= self.pozyx.getCalibrationStatus(calibration_status, self.remote_id) if",
"one.\"\"\" status = self.pozyx.clearDevices(self.remote_id) for anchor in self.anchors: status &=",
"print() print(\"START Ranging: \") self.pozyx.clearDevices(self.remote_id) self.setAnchorsManual() self.printPublishConfigurationResult() def loop(self): \"\"\"Gets",
"status &= self.pozyx.addDevice(anchor, self.remote_id) if len(anchors) > 4: status &=",
"is not None: self.osc_udp_client.send_message( \"/error\", [operation, network_id, error_code[0]]) else: self.pozyx.getErrorCode(error_code)",
"# positioning algorithm to use algorithm = POZYX_POS_ALG_TRACKING # tracking",
"required in 2.5D positioning pozyx = PozyxSerial(serial_port) osc_udp_client = SimpleUDPClient(ip,",
"is not None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) == POZYX_SUCCESS: status =",
"one_cycle_sensor_data, one_cycle_position) # if the iterate_file didn't return a tuple,",
"status &= self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, len(anchors)) return status def printPublishConfigurationResult(self): \"\"\"Prints and",
"position else: pass # self.print_publish_error_code(\"positioning\") return \"Error, no data to",
"from pythonosc.udp_client import SimpleUDPClient from modules.user_input_config_functions import UserInputConfigFunctions as UserInput",
"No parameters required.\") print() print(\"- System will auto start configuration\")",
"self.remote_id) status &= self.pozyx.getCalibrationStatus(calibration_status, self.remote_id) if status == POZYX_SUCCESS: #",
"while True: # updates elapsed time and time difference elapsed",
"= SingleRegister() network_id = self.remote_id if network_id is None: self.pozyx.getErrorCode(error_code)",
"use a remote device # if not remote: # remote_id",
"roll and pitch - the quaternion rotation describing the 3D",
"self.msg_builder = OscMessageBuilder(\"/sensordata\") self.msg_builder.add_arg(int(1000 * (time() - self.current_time))) current_time =",
"addSensorData(self, sensor_data): \"\"\"Adds the sensor data to the OSC message\"\"\"",
"self.remote_id = remote_id def setup(self): \"\"\"There is no specific setup",
"one (or two) pozyx shields. It demonstrates the 3D orientation",
"being able to communicate with a remote Pozyx. if __name__",
"0 current_cycle_time = 0 attributes_to_log = [\"acceleration\"] to_use_file = False",
"users to exit the while iterate_file by pressing ctrl+c except",
"only happen when not being able to communicate with a",
"algorithm, dimension, height, remote_id) o.setup() logfile = None if to_use_file:",
"the anchor configuration result in a human-readable way.\"\"\" list_size =",
"status def printPublishConfigurationResult(self): \"\"\"Prints and potentially publishes the anchor configuration",
"Windows users to exit the while iterate_file by pressing ctrl+c",
"def setAnchorsManual(self): \"\"\"Adds the manually measured anchors to the Pozyx's",
"velocity - the heading, roll and pitch - the quaternion",
"pypozyx import * from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU from pythonosc.osc_message_builder import",
"it as a OSC packet\"\"\" error_code = SingleRegister() network_id =",
"previous_cycle_time # store iterate_file returns as a tuple or an",
"the Pozyx for positioning by calibrating its anchor list.\"\"\" print(\"------------POZYX",
"to transform from the body coordinate system to the world",
"Pozyx's error and possibly sends it as a OSC packet\"\"\"",
"self.anchors: status &= self.pozyx.addDevice(anchor, self.remote_id) if len(anchors) > 4: status",
"self.pozyx.getErrorCode(error_code) print(\"ERROR %s, couldn't retrieve remote error code, local error",
"difference elapsed = ConsoleLogging.get_elapsed_time(ConsoleLogging, start) previous_cycle_time = current_cycle_time current_cycle_time =",
"\"x:\", one_cycle_position.x, \"y:\", one_cycle_position.y, \"z:\", one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index, elapsed, formatted_data_dictionary) if",
"\"y:\", one_cycle_position.y, \"z:\", one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index, elapsed, formatted_data_dictionary) if to_use_file: FileWriting.write_sensor_and_position_data_to_file(",
"\"\"\"Gets new IMU sensor data\"\"\" # check sensor data status",
"device_list = DeviceList(list_size=list_size[0]) status = self.pozyx.getDeviceIds(device_list, self.remote_id) print(\"Calibration result:\") print(\"Anchors",
"= pozyx self.osc_udp_client = osc_udp_client self.anchors = anchors self.algorithm =",
"from modules.console_logging_functions import ConsoleLoggingFunctions as ConsoleLogging import time as t",
"way.\"\"\" list_size = SingleRegister() status = self.pozyx.getDeviceListSize(list_size, self.remote_id) print(\"List size:",
"= 8888 anchors = [DeviceCoordinates(0x6863, 1, Coordinates(0, 0, 2000)), DeviceCoordinates(0x615a,",
"potentially publishes the anchor configuration result in a human-readable way.\"\"\"",
"read register data from a pozyx device. Connect one of",
"Pozyx Labs please check out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This demo requires one",
"0 previous_cycle_time = 0 current_cycle_time = 0 attributes_to_log = [\"acceleration\"]",
"strength - angular velocity - the heading, roll and pitch",
"publishes it\"\"\" self.msg_builder = OscMessageBuilder(\"/sensordata\") self.msg_builder.add_arg(int(1000 * (time() - self.current_time)))",
"- the heading, roll and pitch - the quaternion rotation",
"publishes the anchor configuration result in a human-readable way.\"\"\" list_size",
"if not remote: # remote_id = None index = 0",
"publishSensorData(self, sensor_data, calibration_status): \"\"\"Makes the OSC sensor data package and",
"return \"Error, no data to print for this line\" def",
"= 0x6110 # remote device network ID remote = True",
"of the Pozyx devices with USB and run this script.",
"POSITIONING V1.0 -------------\") print(\"NOTES: \") print(\"- No parameters required.\") print()",
"return sensor_data, position else: pass # self.print_publish_error_code(\"positioning\") return \"Error, no",
"osc_udp_client, anchors, algorithm, dimension, height, remote_id) o.setup() logfile = None",
"[operation, 0, -1]) # should only happen when not being",
"print(\"Anchor IDs: \", device_list) for i in range(list_size[0]): anchor_coordinates =",
"status &= self.pozyx.getCalibrationStatus(calibration_status, self.remote_id) if status == POZYX_SUCCESS: # check",
"data component to the OSC message\"\"\" for data in component.data:",
"# if the iterate_file didn't return a tuple, it returned",
"from pypozyx import * from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU from pythonosc.osc_message_builder",
"self.pozyx.getErrorCode(error_code) print(\"ERROR %s, local error code %s\" % (operation, str(error_code)))",
"code %s\" % (operation, str(error_code))) if self.osc_udp_client is not None:",
"self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, len(anchors)) return status def printPublishConfigurationResult(self): \"\"\"Prints and potentially publishes",
"as t class Orientation3D(object): \"\"\"Reads out all sensor data from",
"rotation describing the 3D orientation of the device. This can",
"if __name__ == '__main__': # shortcut to not have to",
"def addSensorData(self, sensor_data): \"\"\"Adds the sensor data to the OSC",
"auto start configuration\") print() print(\"- System will auto start positioning\")",
"data package and publishes it\"\"\" self.msg_builder = OscMessageBuilder(\"/sensordata\") self.msg_builder.add_arg(int(1000 *",
"None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) == POZYX_SUCCESS: status = self.pozyx.getAllSensorData(sensor_data, self.remote_id)",
"osc_udp_client self.anchors = anchors self.algorithm = algorithm self.dimension = dimension",
"it\"\"\" self.msg_builder = OscMessageBuilder(\"/sensordata\") self.msg_builder.add_arg(int(1000 * (time() - self.current_time))) current_time",
"to print for this line\" def publishSensorData(self, sensor_data, calibration_status): \"\"\"Makes",
"= True ip = \"127.0.0.1\" network_port = 8888 anchors =",
"UserInput from modules.file_writing import SensorAndPositionFileWriting as FileWriting from modules.console_logging_functions import",
"python \"\"\" The pozyx ranging demo (c) Pozyx Labs please",
"DeviceList(list_size=list_size[0]) status = self.pozyx.getDeviceIds(device_list, self.remote_id) print(\"Calibration result:\") print(\"Anchors found: {0}\".format(list_size[0]))",
"= POZYX_POS_ALG_UWB_ONLY # positioning algorithm to use algorithm = POZYX_POS_ALG_TRACKING",
"= loop_results ConsoleLogging.print_data_error_message(index, elapsed, error_string) index += 1 # increment",
"have to find out the port yourself serial_port = get_serial_ports()[0].device",
"modules.console_logging_functions import ConsoleLoggingFunctions as ConsoleLogging import time as t class",
"POZYX_POS_ALG_TRACKING # tracking positioning algorithm dimension = POZYX_3D # positioning",
"= [ \"x:\", one_cycle_position.x, \"y:\", one_cycle_position.y, \"z:\", one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index, elapsed,",
"a tuple, it returned an error string else: error_string =",
"if the iterate_file didn't return a tuple, it returned an",
"coordinate system to the world coordinate system. - the linear",
"def loop(self): \"\"\"Gets new IMU sensor data\"\"\" # check sensor",
"# if not remote: # remote_id = None index =",
"print(\"Calibration result:\") print(\"Anchors found: {0}\".format(list_size[0])) print(\"Anchor IDs: \", device_list) for",
"is None: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, local error code %s\" %",
"is not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, -1]) # should only",
"ID remote = True # whether to use a remote",
"error string else: error_string = loop_results ConsoleLogging.print_data_error_message(index, elapsed, error_string) index",
"in the Processing sketch orientation_3D.pde \"\"\" from time import time",
"the linear acceleration (the acceleration excluding gravity) - the gravitational",
"o.loop() if type(loop_results) == tuple: one_cycle_sensor_data, one_cycle_position = loop_results formatted_data_dictionary",
"pythonosc.udp_client import SimpleUDPClient from modules.user_input_config_functions import UserInputConfigFunctions as UserInput from",
"self.pozyx.getCalibrationStatus(calibration_status, self.remote_id) if status == POZYX_SUCCESS: # check position status",
"to_use_file = False filename = None \"\"\"User input configuration section,",
"self.msg_builder.add_arg((calibration_status[0] & 0x0C) >> 2) self.msg_builder.add_arg((calibration_status[0] & 0x30) >> 4)",
"above settings\"\"\" remote = UserInput.use_remote() remote_id = UserInput.get_remote_id(remote) to_use_file =",
"2000)), DeviceCoordinates(0x615a, 1, Coordinates(0, 18288, 1000)), DeviceCoordinates(0x607c, 1, Coordinates(18288, 0,",
"Connect one of the Pozyx devices with USB and run",
"iterate_file returns as a tuple or an error message loop_results",
"= o.loop() if type(loop_results) == tuple: one_cycle_sensor_data, one_cycle_position = loop_results",
"status = self.pozyx.doPositioning( position, self.dimension, self.height, self.algorithm, remote_id=self.remote_id) if status",
"algorithm=POZYX_POS_ALG_UWB_ONLY, dimension=POZYX_3D, height=1000, remote_id=None): self.pozyx = pozyx self.osc_udp_client = osc_udp_client",
"self.pozyx.clearDevices(self.remote_id) self.setAnchorsManual() self.printPublishConfigurationResult() def loop(self): \"\"\"Gets new IMU sensor data\"\"\"",
"UserInput.use_file() filename = UserInput.get_filename(to_use_file) attributes_to_log = UserInput.get_multiple_attributes_to_log() use_processing = True",
"increment data index # this allows Windows users to exit",
"current_time = time() self.addSensorData(sensor_data) self.addCalibrationStatus(calibration_status) self.osc_udp_client.send(self.msg_builder.build()) def addSensorData(self, sensor_data): \"\"\"Adds",
"\"\"\"Adds the sensor data to the OSC message\"\"\" self.msg_builder.add_arg(sensor_data.pressure) self.addComponentsOSC(sensor_data.acceleration)",
"the heading, roll and pitch - the quaternion rotation describing",
"self.addComponentsOSC(sensor_data.linear_acceleration) self.addComponentsOSC(sensor_data.gravity_vector) def addComponentsOSC(self, component): \"\"\"Adds a sensor data component",
"= time() \"\"\"Sets up the Pozyx for positioning by calibrating",
"the following sensor data: - pressure - acceleration - magnetic",
"https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This demo requires one (or two) pozyx shields. It",
"Processing sketch orientation_3D.pde \"\"\" from time import time from time",
"when not being able to communicate with a remote Pozyx.",
"network_port) o = Orientation3D(pozyx, osc_udp_client, anchors, algorithm, dimension, height, remote_id)",
"self.addComponentsOSC(sensor_data.magnetic) self.addComponentsOSC(sensor_data.angular_vel) self.addComponentsOSC(sensor_data.euler_angles) self.addComponentsOSC(sensor_data.quaternion) self.addComponentsOSC(sensor_data.linear_acceleration) self.addComponentsOSC(sensor_data.gravity_vector) def addComponentsOSC(self, component): \"\"\"Adds",
"= remote_id def setup(self): \"\"\"There is no specific setup functionality\"\"\"",
"&= self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, len(anchors)) return status def printPublishConfigurationResult(self): \"\"\"Prints and potentially",
"status == POZYX_SUCCESS: print(\"ERROR %s on ID %s, error code",
"# remote_id = None index = 0 previous_cycle_time = 0",
"- the quaternion rotation describing the 3D orientation of the",
"the Processing sketch orientation_3D.pde \"\"\" from time import time from",
"# increment data index # this allows Windows users to",
"sensor_data): \"\"\"Adds the sensor data to the OSC message\"\"\" self.msg_builder.add_arg(sensor_data.pressure)",
"start configuration\") print() print(\"- System will auto start positioning\") print(\"------------POZYX",
"a remote device # if not remote: # remote_id =",
"Orientation3D(object): \"\"\"Reads out all sensor data from either a local",
"functionality\"\"\" self.current_time = time() \"\"\"Sets up the Pozyx for positioning",
"- the gravitational vector The data can be viewed in",
"used to transform from the body coordinate system to the",
"def __init__(self, pozyx, osc_udp_client, anchors, algorithm=POZYX_POS_ALG_UWB_ONLY, dimension=POZYX_3D, height=1000, remote_id=None): self.pozyx",
"import OscMessageBuilder from pythonosc.udp_client import SimpleUDPClient from modules.user_input_config_functions import UserInputConfigFunctions",
"pozyx shields. It demonstrates the 3D orientation and the functionality",
"18288, 1000)), DeviceCoordinates(0x607c, 1, Coordinates(18288, 0, 1000)), DeviceCoordinates(0x6134, 1, Coordinates(18288,",
"network_port = 8888 anchors = [DeviceCoordinates(0x6863, 1, Coordinates(0, 0, 2000)),",
"store iterate_file returns as a tuple or an error message",
"with USB and run this script. This demo reads the",
"not being able to communicate with a remote Pozyx. if",
"and potentially publishes the anchor configuration result in a human-readable",
"allows Windows users to exit the while iterate_file by pressing",
"error_code[0]]) else: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, couldn't retrieve remote error code,",
"use algorithm = POZYX_POS_ALG_TRACKING # tracking positioning algorithm dimension =",
"self.pozyx.getDeviceCoordinates( device_list[i], anchor_coordinates, self.remote_id) print(\"ANCHOR,0x%0.4x, %s\" % (device_list[i], str(anchor_coordinates))) if",
"data to the OSC message\"\"\" self.msg_builder.add_arg(calibration_status[0] & 0x03) self.msg_builder.add_arg((calibration_status[0] &",
"osc_udp_client, anchors, algorithm=POZYX_POS_ALG_UWB_ONLY, dimension=POZYX_3D, height=1000, remote_id=None): self.pozyx = pozyx self.osc_udp_client",
"None: self.osc_udp_client.send_message(\"/error\", [operation, 0, error_code[0]]) return status = self.pozyx.getErrorCode(error_code, self.remote_id)",
"specific setup functionality\"\"\" self.current_time = time() \"\"\"Sets up the Pozyx",
"& 0x03) self.msg_builder.add_arg((calibration_status[0] & 0x0C) >> 2) self.msg_builder.add_arg((calibration_status[0] & 0x30)",
"= time() self.addSensorData(sensor_data) self.addCalibrationStatus(calibration_status) self.osc_udp_client.send(self.msg_builder.build()) def addSensorData(self, sensor_data): \"\"\"Adds the",
"algorithm self.dimension = dimension self.height = height self.remote_id = remote_id",
"self.addComponentsOSC(sensor_data.acceleration) self.addComponentsOSC(sensor_data.magnetic) self.addComponentsOSC(sensor_data.angular_vel) self.addComponentsOSC(sensor_data.euler_angles) self.addComponentsOSC(sensor_data.quaternion) self.addComponentsOSC(sensor_data.linear_acceleration) self.addComponentsOSC(sensor_data.gravity_vector) def addComponentsOSC(self, component):",
"'a') FileWriting.write_sensor_and_position_header_to_file(logfile) start = ConsoleLogging.get_time() try: while True: # updates",
"open(filename, 'a') FileWriting.write_sensor_and_position_header_to_file(logfile) start = ConsoleLogging.get_time() try: while True: #",
"run this script. This demo reads the following sensor data:",
"POZYX_SUCCESS: # self.print_publish_position(position) self.publishSensorData(sensor_data, calibration_status) return sensor_data, position else: pass",
"the OSC message\"\"\" self.msg_builder.add_arg(sensor_data.pressure) self.addComponentsOSC(sensor_data.acceleration) self.addComponentsOSC(sensor_data.magnetic) self.addComponentsOSC(sensor_data.angular_vel) self.addComponentsOSC(sensor_data.euler_angles) self.addComponentsOSC(sensor_data.quaternion) self.addComponentsOSC(sensor_data.linear_acceleration)",
"(operation, \"0x%0.4x\" % network_id, str(error_code))) if self.osc_udp_client is not None:",
"returns as a tuple or an error message loop_results =",
"= loop_results formatted_data_dictionary = ConsoleLogging.format_sensor_data( one_cycle_sensor_data, attributes_to_log) if type(formatted_data_dictionary) ==",
"__name__ == '__main__': # shortcut to not have to find",
"class Orientation3D(object): \"\"\"Reads out all sensor data from either a",
"OSC packet\"\"\" error_code = SingleRegister() network_id = self.remote_id if network_id",
"# whether to use a remote device # if not",
"UserInput.get_remote_id(remote) to_use_file = UserInput.use_file() filename = UserInput.get_filename(to_use_file) attributes_to_log = UserInput.get_multiple_attributes_to_log()",
"elapsed = ConsoleLogging.get_elapsed_time(ConsoleLogging, start) previous_cycle_time = current_cycle_time current_cycle_time = elapsed",
"elapsed, time_difference, logfile, one_cycle_sensor_data, one_cycle_position) # if the iterate_file didn't",
"System will auto start positioning\") print(\"------------POZYX POSITIONING V1.0 --------------\") print()",
"= ConsoleLogging.format_sensor_data( one_cycle_sensor_data, attributes_to_log) if type(formatted_data_dictionary) == dict: formatted_data_dictionary[\"Position\"] =",
"self.height, self.algorithm, remote_id=self.remote_id) if status == POZYX_SUCCESS: # self.print_publish_position(position) self.publishSensorData(sensor_data,",
"previous_cycle_time = current_cycle_time current_cycle_time = elapsed time_difference = current_cycle_time -",
"range(list_size[0]): anchor_coordinates = Coordinates() status = self.pozyx.getDeviceCoordinates( device_list[i], anchor_coordinates, self.remote_id)",
"# check sensor data status sensor_data = SensorData() calibration_status =",
"while iterate_file by pressing ctrl+c except KeyboardInterrupt: pass if to_use_file:",
"(operation, str(error_code))) if self.osc_udp_client is not None: self.osc_udp_client.send_message(\"/error\", [operation, 0,",
"status = self.pozyx.getDeviceIds(device_list, self.remote_id) print(\"Calibration result:\") print(\"Anchors found: {0}\".format(list_size[0])) print(\"Anchor",
"one_cycle_position.x, \"y:\", one_cycle_position.y, \"z:\", one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index, elapsed, formatted_data_dictionary) if to_use_file:",
"if self.osc_udp_client is not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, error_code[0]]) return",
"time import time from time import sleep from pypozyx import",
"self.msg_builder.add_arg((calibration_status[0] & 0xC0) >> 6) def setAnchorsManual(self): \"\"\"Adds the manually",
"Ranging: \") self.pozyx.clearDevices(self.remote_id) self.setAnchorsManual() self.printPublishConfigurationResult() def loop(self): \"\"\"Gets new IMU",
"[\"acceleration\"] to_use_file = False filename = None \"\"\"User input configuration",
"(or two) pozyx shields. It demonstrates the 3D orientation and",
"try: while True: # updates elapsed time and time difference",
"time from time import sleep from pypozyx import * from",
"and pitch - the quaternion rotation describing the 3D orientation",
"a tuple or an error message loop_results = o.loop() if",
"data: - pressure - acceleration - magnetic field strength -",
"serial_port = get_serial_ports()[0].device remote_id = 0x6110 # remote device network",
"whether to use a remote device # if not remote:",
"the Pozyx's error and possibly sends it as a OSC",
"return status = self.pozyx.getErrorCode(error_code, self.remote_id) if status == POZYX_SUCCESS: print(\"ERROR",
"remote_id = UserInput.get_remote_id(remote) to_use_file = UserInput.use_file() filename = UserInput.get_filename(to_use_file) attributes_to_log",
"calibration_status): \"\"\"Makes the OSC sensor data package and publishes it\"\"\"",
"network_id = self.remote_id if network_id is None: self.pozyx.getErrorCode(error_code) print(\"ERROR %s,",
"self.current_time))) current_time = time() self.addSensorData(sensor_data) self.addCalibrationStatus(calibration_status) self.osc_udp_client.send(self.msg_builder.build()) def addSensorData(self, sensor_data):",
"import ConsoleLoggingFunctions as ConsoleLogging import time as t class Orientation3D(object):",
"sensor data from either a local or remote Pozyx\"\"\" def",
"SimpleUDPClient(ip, network_port) o = Orientation3D(pozyx, osc_udp_client, anchors, algorithm, dimension, height,",
"# shortcut to not have to find out the port",
"and time difference elapsed = ConsoleLogging.get_elapsed_time(ConsoleLogging, start) previous_cycle_time = current_cycle_time",
"loop_results formatted_data_dictionary = ConsoleLogging.format_sensor_data( one_cycle_sensor_data, attributes_to_log) if type(formatted_data_dictionary) == dict:",
"pozyx ranging demo (c) Pozyx Labs please check out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python",
"remote device network ID remote = True # whether to",
"- acceleration - magnetic field strength - angular velocity -",
"found: {0}\".format(list_size[0])) print(\"Anchor IDs: \", device_list) for i in range(list_size[0]):",
"SingleRegister() network_id = self.remote_id if network_id is None: self.pozyx.getErrorCode(error_code) print(\"ERROR",
"time_difference, logfile, one_cycle_sensor_data, one_cycle_position) # if the iterate_file didn't return",
"start positioning\") print(\"------------POZYX POSITIONING V1.0 --------------\") print() print(\"START Ranging: \")",
"port yourself serial_port = get_serial_ports()[0].device remote_id = 0x6110 # remote",
"self.remote_id) if status == POZYX_SUCCESS: # check position status position",
"# positioning dimension height = 1000 # height of device,",
"demo reads the following sensor data: - pressure - acceleration",
"DeviceCoordinates(0x615a, 1, Coordinates(0, 18288, 1000)), DeviceCoordinates(0x607c, 1, Coordinates(18288, 0, 1000)),",
"the functionality to remotely read register data from a pozyx",
"data to print for this line\" def publishSensorData(self, sensor_data, calibration_status):",
"import sleep from pypozyx import * from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU",
"data from either a local or remote Pozyx\"\"\" def __init__(self,",
"on ID %s, error code %s\" % (operation, \"0x%0.4x\" %",
"if list_size[0] != len(self.anchors): self.printPublishErrorCode(\"configuration\") return device_list = DeviceList(list_size=list_size[0]) status",
"positioning pozyx = PozyxSerial(serial_port) osc_udp_client = SimpleUDPClient(ip, network_port) o =",
"= current_cycle_time - previous_cycle_time # store iterate_file returns as a",
">> 4) self.msg_builder.add_arg((calibration_status[0] & 0xC0) >> 6) def setAnchorsManual(self): \"\"\"Adds",
"print() print(\"- System will auto start configuration\") print() print(\"- System",
"import POZYX_INT_MASK_IMU from pythonosc.osc_message_builder import OscMessageBuilder from pythonosc.udp_client import SimpleUDPClient",
"= DeviceList(list_size=list_size[0]) status = self.pozyx.getDeviceIds(device_list, self.remote_id) print(\"Calibration result:\") print(\"Anchors found:",
"comment out to use above settings\"\"\" remote = UserInput.use_remote() remote_id",
"to_use_file: FileWriting.write_sensor_and_position_data_to_file( index, elapsed, time_difference, logfile, one_cycle_sensor_data, one_cycle_position) # if",
"attributes_to_log = [\"acceleration\"] to_use_file = False filename = None \"\"\"User",
"network ID remote = True # whether to use a",
"[ \"x:\", one_cycle_position.x, \"y:\", one_cycle_position.y, \"z:\", one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index, elapsed, formatted_data_dictionary)",
"self.setAnchorsManual() self.printPublishConfigurationResult() def loop(self): \"\"\"Gets new IMU sensor data\"\"\" #",
"demonstrates the 3D orientation and the functionality to remotely read",
"ConsoleLoggingFunctions as ConsoleLogging import time as t class Orientation3D(object): \"\"\"Reads",
"get_serial_ports()[0].device remote_id = 0x6110 # remote device network ID remote",
"linear acceleration (the acceleration excluding gravity) - the gravitational vector",
"Labs please check out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This demo requires one (or",
"self.osc_udp_client = osc_udp_client self.anchors = anchors self.algorithm = algorithm self.dimension",
"string else: error_string = loop_results ConsoleLogging.print_data_error_message(index, elapsed, error_string) index +=",
"find out the port yourself serial_port = get_serial_ports()[0].device remote_id =",
"attributes_to_log) if type(formatted_data_dictionary) == dict: formatted_data_dictionary[\"Position\"] = [ \"x:\", one_cycle_position.x,",
"to remotely read register data from a pozyx device. Connect",
"to exit the while iterate_file by pressing ctrl+c except KeyboardInterrupt:",
"a OSC packet\"\"\" error_code = SingleRegister() network_id = self.remote_id if",
"result:\") print(\"Anchors found: {0}\".format(list_size[0])) print(\"Anchor IDs: \", device_list) for i",
"8888 anchors = [DeviceCoordinates(0x6863, 1, Coordinates(0, 0, 2000)), DeviceCoordinates(0x615a, 1,",
"= Orientation3D(pozyx, osc_udp_client, anchors, algorithm, dimension, height, remote_id) o.setup() logfile",
"retrieve remote error code, local error code %s\" % (operation,",
"of device, required in 2.5D positioning pozyx = PozyxSerial(serial_port) osc_udp_client",
"new IMU sensor data\"\"\" # check sensor data status sensor_data",
">> 6) def setAnchorsManual(self): \"\"\"Adds the manually measured anchors to",
"algorithm to use algorithm = POZYX_POS_ALG_TRACKING # tracking positioning algorithm",
"error_string) index += 1 # increment data index # this",
"positioning\") print(\"------------POZYX POSITIONING V1.0 --------------\") print() print(\"START Ranging: \") self.pozyx.clearDevices(self.remote_id)",
"setup functionality\"\"\" self.current_time = time() \"\"\"Sets up the Pozyx for",
"the OSC sensor data package and publishes it\"\"\" self.msg_builder =",
"the Pozyx's device list one for one.\"\"\" status = self.pozyx.clearDevices(self.remote_id)",
"pythonosc.osc_message_builder import OscMessageBuilder from pythonosc.udp_client import SimpleUDPClient from modules.user_input_config_functions import",
"= UserInput.get_filename(to_use_file) attributes_to_log = UserInput.get_multiple_attributes_to_log() use_processing = True ip =",
"This demo reads the following sensor data: - pressure -",
"= \"127.0.0.1\" network_port = 8888 anchors = [DeviceCoordinates(0x6863, 1, Coordinates(0,",
"devices with USB and run this script. This demo reads",
"osc_udp_client = SimpleUDPClient(ip, network_port) o = Orientation3D(pozyx, osc_udp_client, anchors, algorithm,",
"time_difference = current_cycle_time - previous_cycle_time # store iterate_file returns as",
"acceleration (the acceleration excluding gravity) - the gravitational vector The",
"from pythonosc.osc_message_builder import OscMessageBuilder from pythonosc.udp_client import SimpleUDPClient from modules.user_input_config_functions",
"returned an error string else: error_string = loop_results ConsoleLogging.print_data_error_message(index, elapsed,",
"(c) Pozyx Labs please check out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This demo requires",
"all sensor data from either a local or remote Pozyx\"\"\"",
"height = 1000 # height of device, required in 2.5D",
"data from a pozyx device. Connect one of the Pozyx",
"couldn't retrieve remote error code, local error code %s\" %",
"str(error_code))) if self.osc_udp_client is not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, -1])",
"sensor data component to the OSC message\"\"\" for data in",
"calibration_status) return sensor_data, position else: pass # self.print_publish_error_code(\"positioning\") return \"Error,",
"ID %s, error code %s\" % (operation, \"0x%0.4x\" % network_id,",
"manually measured anchors to the Pozyx's device list one for",
"print(\"- System will auto start positioning\") print(\"------------POZYX POSITIONING V1.0 --------------\")",
"yourself serial_port = get_serial_ports()[0].device remote_id = 0x6110 # remote device",
"to communicate with a remote Pozyx. if __name__ == '__main__':",
"1000)), DeviceCoordinates(0x6134, 1, Coordinates(18288, 18288, 2000))] # algorithm = POZYX_POS_ALG_UWB_ONLY",
"it returned an error string else: error_string = loop_results ConsoleLogging.print_data_error_message(index,",
"dimension, height, remote_id) o.setup() logfile = None if to_use_file: logfile",
"== POZYX_SUCCESS: status = self.pozyx.getAllSensorData(sensor_data, self.remote_id) status &= self.pozyx.getCalibrationStatus(calibration_status, self.remote_id)",
"as UserInput from modules.file_writing import SensorAndPositionFileWriting as FileWriting from modules.console_logging_functions",
"else: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, couldn't retrieve remote error code, local",
"and run this script. This demo reads the following sensor",
"UserInput.use_remote() remote_id = UserInput.get_remote_id(remote) to_use_file = UserInput.use_file() filename = UserInput.get_filename(to_use_file)",
"to not have to find out the port yourself serial_port",
"%s\" % (device_list[i], str(anchor_coordinates))) if self.osc_udp_client is not None: self.osc_udp_client.send_message(",
"= ConsoleLogging.get_time() try: while True: # updates elapsed time and",
"!= len(self.anchors): self.printPublishErrorCode(\"configuration\") return device_list = DeviceList(list_size=list_size[0]) status = self.pozyx.getDeviceIds(device_list,",
"UserInputConfigFunctions as UserInput from modules.file_writing import SensorAndPositionFileWriting as FileWriting from",
"IMU sensor data\"\"\" # check sensor data status sensor_data =",
"self.osc_udp_client.send_message( \"/anchor\", [device_list[i], int(anchor_coordinates.x), int(anchor_coordinates.y), int(anchor_coordinates.z)]) sleep(0.025) def printPublishErrorCode(self, operation):",
"[DeviceCoordinates(0x6863, 1, Coordinates(0, 0, 2000)), DeviceCoordinates(0x615a, 1, Coordinates(0, 18288, 1000)),",
"self.remote_id) print(\"Calibration result:\") print(\"Anchors found: {0}\".format(list_size[0])) print(\"Anchor IDs: \", device_list)",
"pozyx, osc_udp_client, anchors, algorithm=POZYX_POS_ALG_UWB_ONLY, dimension=POZYX_3D, height=1000, remote_id=None): self.pozyx = pozyx",
"not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, error_code[0]]) return status = self.pozyx.getErrorCode(error_code,",
"to the Pozyx's device list one for one.\"\"\" status =",
"or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) == POZYX_SUCCESS: status = self.pozyx.getAllSensorData(sensor_data, self.remote_id) status",
"from modules.user_input_config_functions import UserInputConfigFunctions as UserInput from modules.file_writing import SensorAndPositionFileWriting",
"= Coordinates() status = self.pozyx.doPositioning( position, self.dimension, self.height, self.algorithm, remote_id=self.remote_id)",
"o = Orientation3D(pozyx, osc_udp_client, anchors, algorithm, dimension, height, remote_id) o.setup()",
"self.pozyx.getErrorCode(error_code, self.remote_id) if status == POZYX_SUCCESS: print(\"ERROR %s on ID",
"filename = UserInput.get_filename(to_use_file) attributes_to_log = UserInput.get_multiple_attributes_to_log() use_processing = True ip",
"self.remote_id if network_id is None: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, local error",
"device # if not remote: # remote_id = None index",
"- pressure - acceleration - magnetic field strength - angular",
"return status def printPublishConfigurationResult(self): \"\"\"Prints and potentially publishes the anchor",
"error code %s\" % (operation, str(error_code))) if self.osc_udp_client is not",
"loop_results ConsoleLogging.print_data_error_message(index, elapsed, error_string) index += 1 # increment data",
"== POZYX_SUCCESS: # self.print_publish_position(position) self.publishSensorData(sensor_data, calibration_status) return sensor_data, position else:",
"requires one (or two) pozyx shields. It demonstrates the 3D",
"\"z:\", one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index, elapsed, formatted_data_dictionary) if to_use_file: FileWriting.write_sensor_and_position_data_to_file( index, elapsed,",
"message loop_results = o.loop() if type(loop_results) == tuple: one_cycle_sensor_data, one_cycle_position",
"self.msg_builder.add_arg(float(data)) def addCalibrationStatus(self, calibration_status): \"\"\"Adds the calibration status data to",
"if type(loop_results) == tuple: one_cycle_sensor_data, one_cycle_position = loop_results formatted_data_dictionary =",
"local error code %s\" % (operation, str(error_code))) if self.osc_udp_client is",
"& 0x0C) >> 2) self.msg_builder.add_arg((calibration_status[0] & 0x30) >> 4) self.msg_builder.add_arg((calibration_status[0]",
"time and time difference elapsed = ConsoleLogging.get_elapsed_time(ConsoleLogging, start) previous_cycle_time =",
"not None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) == POZYX_SUCCESS: status = self.pozyx.getAllSensorData(sensor_data,",
"settings\"\"\" remote = UserInput.use_remote() remote_id = UserInput.get_remote_id(remote) to_use_file = UserInput.use_file()",
"in component.data: self.msg_builder.add_arg(float(data)) def addCalibrationStatus(self, calibration_status): \"\"\"Adds the calibration status",
"elapsed, formatted_data_dictionary) if to_use_file: FileWriting.write_sensor_and_position_data_to_file( index, elapsed, time_difference, logfile, one_cycle_sensor_data,",
"should only happen when not being able to communicate with",
"from either a local or remote Pozyx\"\"\" def __init__(self, pozyx,",
"pozyx self.osc_udp_client = osc_udp_client self.anchors = anchors self.algorithm = algorithm",
"def addComponentsOSC(self, component): \"\"\"Adds a sensor data component to the",
"positioning by calibrating its anchor list.\"\"\" print(\"------------POZYX POSITIONING V1.0 -------------\")",
"= SingleRegister() status = self.pozyx.getDeviceListSize(list_size, self.remote_id) print(\"List size: {0}\".format(list_size[0])) if",
"Orientation3D(pozyx, osc_udp_client, anchors, algorithm, dimension, height, remote_id) o.setup() logfile =",
"[operation, network_id, error_code[0]]) else: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, couldn't retrieve remote",
"the port yourself serial_port = get_serial_ports()[0].device remote_id = 0x6110 #",
"SensorData() calibration_status = SingleRegister() if self.remote_id is not None or",
"system to the world coordinate system. - the linear acceleration",
"the manually measured anchors to the Pozyx's device list one",
"= POZYX_POS_ALG_TRACKING # tracking positioning algorithm dimension = POZYX_3D #",
"error_code[0]]) return status = self.pozyx.getErrorCode(error_code, self.remote_id) if status == POZYX_SUCCESS:",
"print(\"------------POZYX POSITIONING V1.0 -------------\") print(\"NOTES: \") print(\"- No parameters required.\")",
"return a tuple, it returned an error string else: error_string",
"type(loop_results) == tuple: one_cycle_sensor_data, one_cycle_position = loop_results formatted_data_dictionary = ConsoleLogging.format_sensor_data(",
"DeviceCoordinates(0x607c, 1, Coordinates(18288, 0, 1000)), DeviceCoordinates(0x6134, 1, Coordinates(18288, 18288, 2000))]",
"POZYX_SUCCESS: # check position status position = Coordinates() status =",
"anchors, algorithm=POZYX_POS_ALG_UWB_ONLY, dimension=POZYX_3D, height=1000, remote_id=None): self.pozyx = pozyx self.osc_udp_client =",
"sleep(0.025) def printPublishErrorCode(self, operation): \"\"\"Prints the Pozyx's error and possibly",
"= POZYX_3D # positioning dimension height = 1000 # height",
"= 0 attributes_to_log = [\"acceleration\"] to_use_file = False filename =",
"a human-readable way.\"\"\" list_size = SingleRegister() status = self.pozyx.getDeviceListSize(list_size, self.remote_id)",
"elapsed time and time difference elapsed = ConsoleLogging.get_elapsed_time(ConsoleLogging, start) previous_cycle_time",
"POZYX_POS_ALG_UWB_ONLY # positioning algorithm to use algorithm = POZYX_POS_ALG_TRACKING #",
"== tuple: one_cycle_sensor_data, one_cycle_position = loop_results formatted_data_dictionary = ConsoleLogging.format_sensor_data( one_cycle_sensor_data,",
"local or remote Pozyx\"\"\" def __init__(self, pozyx, osc_udp_client, anchors, algorithm=POZYX_POS_ALG_UWB_ONLY,",
"status == POZYX_SUCCESS: # check position status position = Coordinates()",
"from a pozyx device. Connect one of the Pozyx devices",
"1, Coordinates(0, 0, 2000)), DeviceCoordinates(0x615a, 1, Coordinates(0, 18288, 1000)), DeviceCoordinates(0x607c,",
"please check out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This demo requires one (or two)",
"print(\"ERROR %s on ID %s, error code %s\" % (operation,",
"if self.osc_udp_client is not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, -1]) #",
"can be used to transform from the body coordinate system",
"2.5D positioning pozyx = PozyxSerial(serial_port) osc_udp_client = SimpleUDPClient(ip, network_port) o",
"not None: self.osc_udp_client.send_message( \"/error\", [operation, network_id, error_code[0]]) else: self.pozyx.getErrorCode(error_code) print(\"ERROR",
"device. This can be used to transform from the body",
"with a remote Pozyx. if __name__ == '__main__': # shortcut",
"0, 1000)), DeviceCoordinates(0x6134, 1, Coordinates(18288, 18288, 2000))] # algorithm =",
"to the OSC message\"\"\" self.msg_builder.add_arg(calibration_status[0] & 0x03) self.msg_builder.add_arg((calibration_status[0] & 0x0C)",
"position = Coordinates() status = self.pozyx.doPositioning( position, self.dimension, self.height, self.algorithm,",
"anchors, algorithm, dimension, height, remote_id) o.setup() logfile = None if",
"if len(anchors) > 4: status &= self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, len(anchors)) return status",
"script. This demo reads the following sensor data: - pressure",
"%s, local error code %s\" % (operation, str(error_code))) if self.osc_udp_client",
"the Pozyx devices with USB and run this script. This",
"if status == POZYX_SUCCESS: # self.print_publish_position(position) self.publishSensorData(sensor_data, calibration_status) return sensor_data,",
"code %s\" % (operation, \"0x%0.4x\" % network_id, str(error_code))) if self.osc_udp_client",
"didn't return a tuple, it returned an error string else:",
"True ip = \"127.0.0.1\" network_port = 8888 anchors = [DeviceCoordinates(0x6863,",
"modules.file_writing import SensorAndPositionFileWriting as FileWriting from modules.console_logging_functions import ConsoleLoggingFunctions as",
"anchors self.algorithm = algorithm self.dimension = dimension self.height = height",
"Pozyx devices with USB and run this script. This demo",
"= open(filename, 'a') FileWriting.write_sensor_and_position_header_to_file(logfile) start = ConsoleLogging.get_time() try: while True:",
"-------------\") print(\"NOTES: \") print(\"- No parameters required.\") print() print(\"- System",
"\"\"\"Reads out all sensor data from either a local or",
"position status position = Coordinates() status = self.pozyx.doPositioning( position, self.dimension,",
"V1.0 -------------\") print(\"NOTES: \") print(\"- No parameters required.\") print() print(\"-",
"anchor_coordinates, self.remote_id) print(\"ANCHOR,0x%0.4x, %s\" % (device_list[i], str(anchor_coordinates))) if self.osc_udp_client is",
"= dimension self.height = height self.remote_id = remote_id def setup(self):",
"demo requires one (or two) pozyx shields. It demonstrates the",
"elapsed time_difference = current_cycle_time - previous_cycle_time # store iterate_file returns",
"package and publishes it\"\"\" self.msg_builder = OscMessageBuilder(\"/sensordata\") self.msg_builder.add_arg(int(1000 * (time()",
"= anchors self.algorithm = algorithm self.dimension = dimension self.height =",
"one_cycle_position = loop_results formatted_data_dictionary = ConsoleLogging.format_sensor_data( one_cycle_sensor_data, attributes_to_log) if type(formatted_data_dictionary)",
"import UserInputConfigFunctions as UserInput from modules.file_writing import SensorAndPositionFileWriting as FileWriting",
"check out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This demo requires one (or two) pozyx",
"remote_id=self.remote_id) if status == POZYX_SUCCESS: # self.print_publish_position(position) self.publishSensorData(sensor_data, calibration_status) return",
"OscMessageBuilder(\"/sensordata\") self.msg_builder.add_arg(int(1000 * (time() - self.current_time))) current_time = time() self.addSensorData(sensor_data)",
"tuple or an error message loop_results = o.loop() if type(loop_results)",
"0, -1]) # should only happen when not being able",
"to the OSC message\"\"\" self.msg_builder.add_arg(sensor_data.pressure) self.addComponentsOSC(sensor_data.acceleration) self.addComponentsOSC(sensor_data.magnetic) self.addComponentsOSC(sensor_data.angular_vel) self.addComponentsOSC(sensor_data.euler_angles) self.addComponentsOSC(sensor_data.quaternion)",
"if to_use_file: logfile = open(filename, 'a') FileWriting.write_sensor_and_position_header_to_file(logfile) start = ConsoleLogging.get_time()",
"an error string else: error_string = loop_results ConsoleLogging.print_data_error_message(index, elapsed, error_string)",
"import * from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU from pythonosc.osc_message_builder import OscMessageBuilder",
"calibration status data to the OSC message\"\"\" self.msg_builder.add_arg(calibration_status[0] & 0x03)",
"algorithm = POZYX_POS_ALG_UWB_ONLY # positioning algorithm to use algorithm =",
"== '__main__': # shortcut to not have to find out",
"self.remote_id) print(\"List size: {0}\".format(list_size[0])) if list_size[0] != len(self.anchors): self.printPublishErrorCode(\"configuration\") return",
"anchors = [DeviceCoordinates(0x6863, 1, Coordinates(0, 0, 2000)), DeviceCoordinates(0x615a, 1, Coordinates(0,",
"dimension=POZYX_3D, height=1000, remote_id=None): self.pozyx = pozyx self.osc_udp_client = osc_udp_client self.anchors",
"%s, couldn't retrieve remote error code, local error code %s\"",
"SingleRegister() status = self.pozyx.getDeviceListSize(list_size, self.remote_id) print(\"List size: {0}\".format(list_size[0])) if list_size[0]",
"- angular velocity - the heading, roll and pitch -",
"the sensor data to the OSC message\"\"\" self.msg_builder.add_arg(sensor_data.pressure) self.addComponentsOSC(sensor_data.acceleration) self.addComponentsOSC(sensor_data.magnetic)",
"from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU from pythonosc.osc_message_builder import OscMessageBuilder from pythonosc.udp_client",
"algorithm = POZYX_POS_ALG_TRACKING # tracking positioning algorithm dimension = POZYX_3D",
"True # whether to use a remote device # if",
"modules.user_input_config_functions import UserInputConfigFunctions as UserInput from modules.file_writing import SensorAndPositionFileWriting as",
"\"\"\"Makes the OSC sensor data package and publishes it\"\"\" self.msg_builder",
"= self.pozyx.getDeviceIds(device_list, self.remote_id) print(\"Calibration result:\") print(\"Anchors found: {0}\".format(list_size[0])) print(\"Anchor IDs:",
"field strength - angular velocity - the heading, roll and",
"world coordinate system. - the linear acceleration (the acceleration excluding",
"configuration result in a human-readable way.\"\"\" list_size = SingleRegister() status",
"1000)), DeviceCoordinates(0x607c, 1, Coordinates(18288, 0, 1000)), DeviceCoordinates(0x6134, 1, Coordinates(18288, 18288,",
"1000 # height of device, required in 2.5D positioning pozyx",
"height, remote_id) o.setup() logfile = None if to_use_file: logfile =",
"as FileWriting from modules.console_logging_functions import ConsoleLoggingFunctions as ConsoleLogging import time",
"def addCalibrationStatus(self, calibration_status): \"\"\"Adds the calibration status data to the",
"shields. It demonstrates the 3D orientation and the functionality to",
"= self.pozyx.doPositioning( position, self.dimension, self.height, self.algorithm, remote_id=self.remote_id) if status ==",
"\"/anchor\", [device_list[i], int(anchor_coordinates.x), int(anchor_coordinates.y), int(anchor_coordinates.z)]) sleep(0.025) def printPublishErrorCode(self, operation): \"\"\"Prints",
"transform from the body coordinate system to the world coordinate",
"elapsed, error_string) index += 1 # increment data index #",
"None \"\"\"User input configuration section, comment out to use above",
"OSC message\"\"\" self.msg_builder.add_arg(calibration_status[0] & 0x03) self.msg_builder.add_arg((calibration_status[0] & 0x0C) >> 2)",
"self.addComponentsOSC(sensor_data.quaternion) self.addComponentsOSC(sensor_data.linear_acceleration) self.addComponentsOSC(sensor_data.gravity_vector) def addComponentsOSC(self, component): \"\"\"Adds a sensor data",
"def printPublishErrorCode(self, operation): \"\"\"Prints the Pozyx's error and possibly sends",
"possibly sends it as a OSC packet\"\"\" error_code = SingleRegister()",
"OscMessageBuilder from pythonosc.udp_client import SimpleUDPClient from modules.user_input_config_functions import UserInputConfigFunctions as",
"#!/usr/bin/env python \"\"\" The pozyx ranging demo (c) Pozyx Labs",
"device, required in 2.5D positioning pozyx = PozyxSerial(serial_port) osc_udp_client =",
"FileWriting from modules.console_logging_functions import ConsoleLoggingFunctions as ConsoleLogging import time as",
"status = self.pozyx.clearDevices(self.remote_id) for anchor in self.anchors: status &= self.pozyx.addDevice(anchor,",
"USB and run this script. This demo reads the following",
"be used to transform from the body coordinate system to",
"self.pozyx.clearDevices(self.remote_id) for anchor in self.anchors: status &= self.pozyx.addDevice(anchor, self.remote_id) if",
"its anchor list.\"\"\" print(\"------------POZYX POSITIONING V1.0 -------------\") print(\"NOTES: \") print(\"-",
"sensor data status sensor_data = SensorData() calibration_status = SingleRegister() if",
"remote_id = 0x6110 # remote device network ID remote =",
"message\"\"\" for data in component.data: self.msg_builder.add_arg(float(data)) def addCalibrationStatus(self, calibration_status): \"\"\"Adds",
"remote: # remote_id = None index = 0 previous_cycle_time =",
"remote = UserInput.use_remote() remote_id = UserInput.get_remote_id(remote) to_use_file = UserInput.use_file() filename",
"status = self.pozyx.getAllSensorData(sensor_data, self.remote_id) status &= self.pozyx.getCalibrationStatus(calibration_status, self.remote_id) if status",
"= PozyxSerial(serial_port) osc_udp_client = SimpleUDPClient(ip, network_port) o = Orientation3D(pozyx, osc_udp_client,",
"pass # self.print_publish_error_code(\"positioning\") return \"Error, no data to print for",
"size: {0}\".format(list_size[0])) if list_size[0] != len(self.anchors): self.printPublishErrorCode(\"configuration\") return device_list =",
"error_code = SingleRegister() network_id = self.remote_id if network_id is None:",
"\"/error\", [operation, network_id, error_code[0]]) else: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, couldn't retrieve",
"False filename = None \"\"\"User input configuration section, comment out",
"to find out the port yourself serial_port = get_serial_ports()[0].device remote_id",
"check sensor data status sensor_data = SensorData() calibration_status = SingleRegister()",
"self.pozyx.getDeviceIds(device_list, self.remote_id) print(\"Calibration result:\") print(\"Anchors found: {0}\".format(list_size[0])) print(\"Anchor IDs: \",",
"3D orientation of the device. This can be used to",
"algorithm dimension = POZYX_3D # positioning dimension height = 1000",
"else: pass # self.print_publish_error_code(\"positioning\") return \"Error, no data to print",
"two) pozyx shields. It demonstrates the 3D orientation and the",
"# height of device, required in 2.5D positioning pozyx =",
"data index # this allows Windows users to exit the",
"= Coordinates() status = self.pozyx.getDeviceCoordinates( device_list[i], anchor_coordinates, self.remote_id) print(\"ANCHOR,0x%0.4x, %s\"",
"= OscMessageBuilder(\"/sensordata\") self.msg_builder.add_arg(int(1000 * (time() - self.current_time))) current_time = time()",
"\"0x%0.4x\" % network_id, str(error_code))) if self.osc_udp_client is not None: self.osc_udp_client.send_message(",
"sensor data: - pressure - acceleration - magnetic field strength",
"(time() - self.current_time))) current_time = time() self.addSensorData(sensor_data) self.addCalibrationStatus(calibration_status) self.osc_udp_client.send(self.msg_builder.build()) def",
"data can be viewed in the Processing sketch orientation_3D.pde \"\"\"",
"\") print(\"- No parameters required.\") print() print(\"- System will auto",
"data status sensor_data = SensorData() calibration_status = SingleRegister() if self.remote_id",
"iterate_file didn't return a tuple, it returned an error string",
"# self.print_publish_error_code(\"positioning\") return \"Error, no data to print for this",
"status = self.pozyx.getErrorCode(error_code, self.remote_id) if status == POZYX_SUCCESS: print(\"ERROR %s",
"# algorithm = POZYX_POS_ALG_UWB_ONLY # positioning algorithm to use algorithm",
"self.remote_id) print(\"ANCHOR,0x%0.4x, %s\" % (device_list[i], str(anchor_coordinates))) if self.osc_udp_client is not",
"remote Pozyx. if __name__ == '__main__': # shortcut to not",
"either a local or remote Pozyx\"\"\" def __init__(self, pozyx, osc_udp_client,",
"from modules.file_writing import SensorAndPositionFileWriting as FileWriting from modules.console_logging_functions import ConsoleLoggingFunctions",
"remote_id def setup(self): \"\"\"There is no specific setup functionality\"\"\" self.current_time",
"OSC message\"\"\" self.msg_builder.add_arg(sensor_data.pressure) self.addComponentsOSC(sensor_data.acceleration) self.addComponentsOSC(sensor_data.magnetic) self.addComponentsOSC(sensor_data.angular_vel) self.addComponentsOSC(sensor_data.euler_angles) self.addComponentsOSC(sensor_data.quaternion) self.addComponentsOSC(sensor_data.linear_acceleration) self.addComponentsOSC(sensor_data.gravity_vector)",
"acceleration excluding gravity) - the gravitational vector The data can",
"list_size[0] != len(self.anchors): self.printPublishErrorCode(\"configuration\") return device_list = DeviceList(list_size=list_size[0]) status =",
"current_cycle_time = 0 attributes_to_log = [\"acceleration\"] to_use_file = False filename",
"1, Coordinates(18288, 18288, 2000))] # algorithm = POZYX_POS_ALG_UWB_ONLY # positioning",
"- magnetic field strength - angular velocity - the heading,",
"ConsoleLogging.print_data_error_message(index, elapsed, error_string) index += 1 # increment data index",
"POSITIONING V1.0 --------------\") print() print(\"START Ranging: \") self.pozyx.clearDevices(self.remote_id) self.setAnchorsManual() self.printPublishConfigurationResult()",
"= 0 current_cycle_time = 0 attributes_to_log = [\"acceleration\"] to_use_file =",
"= None \"\"\"User input configuration section, comment out to use",
"from time import sleep from pypozyx import * from pypozyx.definitions.bitmasks",
"the device. This can be used to transform from the",
"= [\"acceleration\"] to_use_file = False filename = None \"\"\"User input",
"code, local error code %s\" % (operation, str(error_code))) if self.osc_udp_client",
"= [DeviceCoordinates(0x6863, 1, Coordinates(0, 0, 2000)), DeviceCoordinates(0x615a, 1, Coordinates(0, 18288,",
"index, elapsed, time_difference, logfile, one_cycle_sensor_data, one_cycle_position) # if the iterate_file",
"the while iterate_file by pressing ctrl+c except KeyboardInterrupt: pass if",
"FileWriting.write_sensor_and_position_header_to_file(logfile) start = ConsoleLogging.get_time() try: while True: # updates elapsed",
"printPublishConfigurationResult(self): \"\"\"Prints and potentially publishes the anchor configuration result in",
"self.dimension = dimension self.height = height self.remote_id = remote_id def",
"Coordinates() status = self.pozyx.doPositioning( position, self.dimension, self.height, self.algorithm, remote_id=self.remote_id) if",
"OSC sensor data package and publishes it\"\"\" self.msg_builder = OscMessageBuilder(\"/sensordata\")",
"'__main__': # shortcut to not have to find out the",
"= 0 previous_cycle_time = 0 current_cycle_time = 0 attributes_to_log =",
"0 attributes_to_log = [\"acceleration\"] to_use_file = False filename = None",
"UserInput.get_multiple_attributes_to_log() use_processing = True ip = \"127.0.0.1\" network_port = 8888",
"status = self.pozyx.getDeviceCoordinates( device_list[i], anchor_coordinates, self.remote_id) print(\"ANCHOR,0x%0.4x, %s\" % (device_list[i],",
"- previous_cycle_time # store iterate_file returns as a tuple or",
"self.printPublishErrorCode(\"configuration\") return device_list = DeviceList(list_size=list_size[0]) status = self.pozyx.getDeviceIds(device_list, self.remote_id) print(\"Calibration",
"SingleRegister() if self.remote_id is not None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) ==",
"sensor data package and publishes it\"\"\" self.msg_builder = OscMessageBuilder(\"/sensordata\") self.msg_builder.add_arg(int(1000",
"as ConsoleLogging import time as t class Orientation3D(object): \"\"\"Reads out",
"logfile, one_cycle_sensor_data, one_cycle_position) # if the iterate_file didn't return a",
"attributes_to_log = UserInput.get_multiple_attributes_to_log() use_processing = True ip = \"127.0.0.1\" network_port",
"the calibration status data to the OSC message\"\"\" self.msg_builder.add_arg(calibration_status[0] &",
"message\"\"\" self.msg_builder.add_arg(sensor_data.pressure) self.addComponentsOSC(sensor_data.acceleration) self.addComponentsOSC(sensor_data.magnetic) self.addComponentsOSC(sensor_data.angular_vel) self.addComponentsOSC(sensor_data.euler_angles) self.addComponentsOSC(sensor_data.quaternion) self.addComponentsOSC(sensor_data.linear_acceleration) self.addComponentsOSC(sensor_data.gravity_vector) def",
"ConsoleLogging import time as t class Orientation3D(object): \"\"\"Reads out all",
"shortcut to not have to find out the port yourself",
"device list one for one.\"\"\" status = self.pozyx.clearDevices(self.remote_id) for anchor",
"self.print_publish_error_code(\"positioning\") return \"Error, no data to print for this line\"",
"0.01) == POZYX_SUCCESS: status = self.pozyx.getAllSensorData(sensor_data, self.remote_id) status &= self.pozyx.getCalibrationStatus(calibration_status,",
"self.dimension, self.height, self.algorithm, remote_id=self.remote_id) if status == POZYX_SUCCESS: # self.print_publish_position(position)",
"o.setup() logfile = None if to_use_file: logfile = open(filename, 'a')",
"one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index, elapsed, formatted_data_dictionary) if to_use_file: FileWriting.write_sensor_and_position_data_to_file( index, elapsed, time_difference,",
"int(anchor_coordinates.x), int(anchor_coordinates.y), int(anchor_coordinates.z)]) sleep(0.025) def printPublishErrorCode(self, operation): \"\"\"Prints the Pozyx's",
"POZYX_INT_MASK_IMU from pythonosc.osc_message_builder import OscMessageBuilder from pythonosc.udp_client import SimpleUDPClient from",
"error code, local error code %s\" % (operation, str(error_code))) if",
"required.\") print() print(\"- System will auto start configuration\") print() print(\"-",
"= UserInput.get_multiple_attributes_to_log() use_processing = True ip = \"127.0.0.1\" network_port =",
"setAnchorsManual(self): \"\"\"Adds the manually measured anchors to the Pozyx's device",
"tracking positioning algorithm dimension = POZYX_3D # positioning dimension height",
"anchor list.\"\"\" print(\"------------POZYX POSITIONING V1.0 -------------\") print(\"NOTES: \") print(\"- No",
"anchor configuration result in a human-readable way.\"\"\" list_size = SingleRegister()",
"a pozyx device. Connect one of the Pozyx devices with",
"magnetic field strength - angular velocity - the heading, roll",
"= algorithm self.dimension = dimension self.height = height self.remote_id =",
"calibration_status): \"\"\"Adds the calibration status data to the OSC message\"\"\"",
"{0}\".format(list_size[0])) print(\"Anchor IDs: \", device_list) for i in range(list_size[0]): anchor_coordinates",
"check position status position = Coordinates() status = self.pozyx.doPositioning( position,",
"happen when not being able to communicate with a remote",
"int(anchor_coordinates.y), int(anchor_coordinates.z)]) sleep(0.025) def printPublishErrorCode(self, operation): \"\"\"Prints the Pozyx's error",
"current_cycle_time current_cycle_time = elapsed time_difference = current_cycle_time - previous_cycle_time #",
"Coordinates() status = self.pozyx.getDeviceCoordinates( device_list[i], anchor_coordinates, self.remote_id) print(\"ANCHOR,0x%0.4x, %s\" %",
"sensor data to the OSC message\"\"\" self.msg_builder.add_arg(sensor_data.pressure) self.addComponentsOSC(sensor_data.acceleration) self.addComponentsOSC(sensor_data.magnetic) self.addComponentsOSC(sensor_data.angular_vel)",
"\"127.0.0.1\" network_port = 8888 anchors = [DeviceCoordinates(0x6863, 1, Coordinates(0, 0,",
"status = self.pozyx.getDeviceListSize(list_size, self.remote_id) print(\"List size: {0}\".format(list_size[0])) if list_size[0] !=",
"= self.pozyx.getErrorCode(error_code, self.remote_id) if status == POZYX_SUCCESS: print(\"ERROR %s on",
"remote Pozyx\"\"\" def __init__(self, pozyx, osc_udp_client, anchors, algorithm=POZYX_POS_ALG_UWB_ONLY, dimension=POZYX_3D, height=1000,",
"calibrating its anchor list.\"\"\" print(\"------------POZYX POSITIONING V1.0 -------------\") print(\"NOTES: \")",
"{0}\".format(list_size[0])) if list_size[0] != len(self.anchors): self.printPublishErrorCode(\"configuration\") return device_list = DeviceList(list_size=list_size[0])",
"t class Orientation3D(object): \"\"\"Reads out all sensor data from either",
"> 4: status &= self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, len(anchors)) return status def printPublishConfigurationResult(self):",
"device_list[i], anchor_coordinates, self.remote_id) print(\"ANCHOR,0x%0.4x, %s\" % (device_list[i], str(anchor_coordinates))) if self.osc_udp_client",
"data in component.data: self.msg_builder.add_arg(float(data)) def addCalibrationStatus(self, calibration_status): \"\"\"Adds the calibration",
"None: self.osc_udp_client.send_message(\"/error\", [operation, 0, -1]) # should only happen when",
"1, Coordinates(0, 18288, 1000)), DeviceCoordinates(0x607c, 1, Coordinates(18288, 0, 1000)), DeviceCoordinates(0x6134,",
"to use algorithm = POZYX_POS_ALG_TRACKING # tracking positioning algorithm dimension",
"one of the Pozyx devices with USB and run this",
"ConsoleLogging.get_time() try: while True: # updates elapsed time and time",
"not remote: # remote_id = None index = 0 previous_cycle_time",
"ip = \"127.0.0.1\" network_port = 8888 anchors = [DeviceCoordinates(0x6863, 1,",
"height of device, required in 2.5D positioning pozyx = PozyxSerial(serial_port)",
"* (time() - self.current_time))) current_time = time() self.addSensorData(sensor_data) self.addCalibrationStatus(calibration_status) self.osc_udp_client.send(self.msg_builder.build())",
"- self.current_time))) current_time = time() self.addSensorData(sensor_data) self.addCalibrationStatus(calibration_status) self.osc_udp_client.send(self.msg_builder.build()) def addSensorData(self,",
"ConsoleLogging.get_elapsed_time(ConsoleLogging, start) previous_cycle_time = current_cycle_time current_cycle_time = elapsed time_difference =",
"this allows Windows users to exit the while iterate_file by",
"ranging demo (c) Pozyx Labs please check out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This",
"parameters required.\") print() print(\"- System will auto start configuration\") print()",
"index = 0 previous_cycle_time = 0 current_cycle_time = 0 attributes_to_log",
"the iterate_file didn't return a tuple, it returned an error",
"component to the OSC message\"\"\" for data in component.data: self.msg_builder.add_arg(float(data))",
"self.current_time = time() \"\"\"Sets up the Pozyx for positioning by",
"able to communicate with a remote Pozyx. if __name__ ==",
"dimension = POZYX_3D # positioning dimension height = 1000 #",
"functionality to remotely read register data from a pozyx device.",
"\") self.pozyx.clearDevices(self.remote_id) self.setAnchorsManual() self.printPublishConfigurationResult() def loop(self): \"\"\"Gets new IMU sensor",
"is no specific setup functionality\"\"\" self.current_time = time() \"\"\"Sets up",
"= get_serial_ports()[0].device remote_id = 0x6110 # remote device network ID",
"Coordinates(0, 18288, 1000)), DeviceCoordinates(0x607c, 1, Coordinates(18288, 0, 1000)), DeviceCoordinates(0x6134, 1,",
"sketch orientation_3D.pde \"\"\" from time import time from time import",
"current_cycle_time = elapsed time_difference = current_cycle_time - previous_cycle_time # store",
"tuple: one_cycle_sensor_data, one_cycle_position = loop_results formatted_data_dictionary = ConsoleLogging.format_sensor_data( one_cycle_sensor_data, attributes_to_log)",
"return device_list = DeviceList(list_size=list_size[0]) status = self.pozyx.getDeviceIds(device_list, self.remote_id) print(\"Calibration result:\")",
"-1]) # should only happen when not being able to",
"use above settings\"\"\" remote = UserInput.use_remote() remote_id = UserInput.get_remote_id(remote) to_use_file",
"# store iterate_file returns as a tuple or an error",
"status sensor_data = SensorData() calibration_status = SingleRegister() if self.remote_id is",
"\"\"\"There is no specific setup functionality\"\"\" self.current_time = time() \"\"\"Sets",
"self.addSensorData(sensor_data) self.addCalibrationStatus(calibration_status) self.osc_udp_client.send(self.msg_builder.build()) def addSensorData(self, sensor_data): \"\"\"Adds the sensor data",
"network_id, error_code[0]]) else: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, couldn't retrieve remote error",
"\"\"\"Sets up the Pozyx for positioning by calibrating its anchor",
"& 0x30) >> 4) self.msg_builder.add_arg((calibration_status[0] & 0xC0) >> 6) def",
"positioning dimension height = 1000 # height of device, required",
"pozyx = PozyxSerial(serial_port) osc_udp_client = SimpleUDPClient(ip, network_port) o = Orientation3D(pozyx,",
"It demonstrates the 3D orientation and the functionality to remotely",
"= 1000 # height of device, required in 2.5D positioning",
"start = ConsoleLogging.get_time() try: while True: # updates elapsed time",
"out to use above settings\"\"\" remote = UserInput.use_remote() remote_id =",
"to_use_file = UserInput.use_file() filename = UserInput.get_filename(to_use_file) attributes_to_log = UserInput.get_multiple_attributes_to_log() use_processing",
"as a tuple or an error message loop_results = o.loop()",
"self.addCalibrationStatus(calibration_status) self.osc_udp_client.send(self.msg_builder.build()) def addSensorData(self, sensor_data): \"\"\"Adds the sensor data to",
"not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, -1]) # should only happen",
"print(\"- System will auto start configuration\") print() print(\"- System will",
"i in range(list_size[0]): anchor_coordinates = Coordinates() status = self.pozyx.getDeviceCoordinates( device_list[i],",
"% network_id, str(error_code))) if self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/error\",",
"print(\"ERROR %s, couldn't retrieve remote error code, local error code",
"system. - the linear acceleration (the acceleration excluding gravity) -",
"the OSC message\"\"\" self.msg_builder.add_arg(calibration_status[0] & 0x03) self.msg_builder.add_arg((calibration_status[0] & 0x0C) >>",
"time() self.addSensorData(sensor_data) self.addCalibrationStatus(calibration_status) self.osc_udp_client.send(self.msg_builder.build()) def addSensorData(self, sensor_data): \"\"\"Adds the sensor",
"str(anchor_coordinates))) if self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/anchor\", [device_list[i], int(anchor_coordinates.x),",
"ConsoleLogging.log_sensor_data_to_console(index, elapsed, formatted_data_dictionary) if to_use_file: FileWriting.write_sensor_and_position_data_to_file( index, elapsed, time_difference, logfile,",
"if to_use_file: FileWriting.write_sensor_and_position_data_to_file( index, elapsed, time_difference, logfile, one_cycle_sensor_data, one_cycle_position) #",
"or remote Pozyx\"\"\" def __init__(self, pozyx, osc_udp_client, anchors, algorithm=POZYX_POS_ALG_UWB_ONLY, dimension=POZYX_3D,",
"= height self.remote_id = remote_id def setup(self): \"\"\"There is no",
"self.pozyx = pozyx self.osc_udp_client = osc_udp_client self.anchors = anchors self.algorithm",
"(device_list[i], str(anchor_coordinates))) if self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/anchor\", [device_list[i],",
"self.anchors = anchors self.algorithm = algorithm self.dimension = dimension self.height",
"\"\"\"Adds the manually measured anchors to the Pozyx's device list",
"print(\"ANCHOR,0x%0.4x, %s\" % (device_list[i], str(anchor_coordinates))) if self.osc_udp_client is not None:",
"self.osc_udp_client.send_message( \"/error\", [operation, network_id, error_code[0]]) else: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, couldn't",
"error message loop_results = o.loop() if type(loop_results) == tuple: one_cycle_sensor_data,",
"\"\"\"Adds the calibration status data to the OSC message\"\"\" self.msg_builder.add_arg(calibration_status[0]",
"&= self.pozyx.addDevice(anchor, self.remote_id) if len(anchors) > 4: status &= self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO,",
"This can be used to transform from the body coordinate",
"%s\" % (operation, str(error_code))) if self.osc_udp_client is not None: self.osc_udp_client.send_message(\"/error\",",
"__init__(self, pozyx, osc_udp_client, anchors, algorithm=POZYX_POS_ALG_UWB_ONLY, dimension=POZYX_3D, height=1000, remote_id=None): self.pozyx =",
"demo (c) Pozyx Labs please check out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This demo",
"this line\" def publishSensorData(self, sensor_data, calibration_status): \"\"\"Makes the OSC sensor",
"index += 1 # increment data index # this allows",
"1 # increment data index # this allows Windows users",
"for anchor in self.anchors: status &= self.pozyx.addDevice(anchor, self.remote_id) if len(anchors)",
"print(\"START Ranging: \") self.pozyx.clearDevices(self.remote_id) self.setAnchorsManual() self.printPublishConfigurationResult() def loop(self): \"\"\"Gets new",
"anchor in self.anchors: status &= self.pozyx.addDevice(anchor, self.remote_id) if len(anchors) >",
"None: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, local error code %s\" % (operation,",
"out https://www.pozyx.io/Documentation/Tutorials/getting_started/Python This demo requires one (or two) pozyx shields.",
"None: self.osc_udp_client.send_message( \"/error\", [operation, network_id, error_code[0]]) else: self.pozyx.getErrorCode(error_code) print(\"ERROR %s,",
"\"\"\"Prints the Pozyx's error and possibly sends it as a",
"sends it as a OSC packet\"\"\" error_code = SingleRegister() network_id",
"Coordinates(0, 0, 2000)), DeviceCoordinates(0x615a, 1, Coordinates(0, 18288, 1000)), DeviceCoordinates(0x607c, 1,",
"current_cycle_time - previous_cycle_time # store iterate_file returns as a tuple",
"OSC message\"\"\" for data in component.data: self.msg_builder.add_arg(float(data)) def addCalibrationStatus(self, calibration_status):",
"dimension self.height = height self.remote_id = remote_id def setup(self): \"\"\"There",
"len(anchors)) return status def printPublishConfigurationResult(self): \"\"\"Prints and potentially publishes the",
"positioning algorithm dimension = POZYX_3D # positioning dimension height =",
"--------------\") print() print(\"START Ranging: \") self.pozyx.clearDevices(self.remote_id) self.setAnchorsManual() self.printPublishConfigurationResult() def loop(self):",
"== dict: formatted_data_dictionary[\"Position\"] = [ \"x:\", one_cycle_position.x, \"y:\", one_cycle_position.y, \"z:\",",
"self.pozyx.getDeviceListSize(list_size, self.remote_id) print(\"List size: {0}\".format(list_size[0])) if list_size[0] != len(self.anchors): self.printPublishErrorCode(\"configuration\")",
"component.data: self.msg_builder.add_arg(float(data)) def addCalibrationStatus(self, calibration_status): \"\"\"Adds the calibration status data",
"message\"\"\" self.msg_builder.add_arg(calibration_status[0] & 0x03) self.msg_builder.add_arg((calibration_status[0] & 0x0C) >> 2) self.msg_builder.add_arg((calibration_status[0]",
"remote = True # whether to use a remote device",
"for this line\" def publishSensorData(self, sensor_data, calibration_status): \"\"\"Makes the OSC",
"pitch - the quaternion rotation describing the 3D orientation of",
"self.algorithm = algorithm self.dimension = dimension self.height = height self.remote_id",
"filename = None \"\"\"User input configuration section, comment out to",
"from time import time from time import sleep from pypozyx",
"None index = 0 previous_cycle_time = 0 current_cycle_time = 0",
"self.publishSensorData(sensor_data, calibration_status) return sensor_data, position else: pass # self.print_publish_error_code(\"positioning\") return",
"in a human-readable way.\"\"\" list_size = SingleRegister() status = self.pozyx.getDeviceListSize(list_size,",
"pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU from pythonosc.osc_message_builder import OscMessageBuilder from pythonosc.udp_client import",
"1, Coordinates(18288, 0, 1000)), DeviceCoordinates(0x6134, 1, Coordinates(18288, 18288, 2000))] #",
"self.addComponentsOSC(sensor_data.gravity_vector) def addComponentsOSC(self, component): \"\"\"Adds a sensor data component to",
"to_use_file: logfile = open(filename, 'a') FileWriting.write_sensor_and_position_header_to_file(logfile) start = ConsoleLogging.get_time() try:",
"addComponentsOSC(self, component): \"\"\"Adds a sensor data component to the OSC",
"to use a remote device # if not remote: #",
"error_string = loop_results ConsoleLogging.print_data_error_message(index, elapsed, error_string) index += 1 #",
"print() print(\"- System will auto start positioning\") print(\"------------POZYX POSITIONING V1.0",
"= UserInput.get_remote_id(remote) to_use_file = UserInput.use_file() filename = UserInput.get_filename(to_use_file) attributes_to_log =",
"result in a human-readable way.\"\"\" list_size = SingleRegister() status =",
"= UserInput.use_remote() remote_id = UserInput.get_remote_id(remote) to_use_file = UserInput.use_file() filename =",
"quaternion rotation describing the 3D orientation of the device. This",
"auto start positioning\") print(\"------------POZYX POSITIONING V1.0 --------------\") print() print(\"START Ranging:",
"self.msg_builder.add_arg(calibration_status[0] & 0x03) self.msg_builder.add_arg((calibration_status[0] & 0x0C) >> 2) self.msg_builder.add_arg((calibration_status[0] &",
"coordinate system. - the linear acceleration (the acceleration excluding gravity)",
"# this allows Windows users to exit the while iterate_file",
"2) self.msg_builder.add_arg((calibration_status[0] & 0x30) >> 4) self.msg_builder.add_arg((calibration_status[0] & 0xC0) >>",
"& 0xC0) >> 6) def setAnchorsManual(self): \"\"\"Adds the manually measured",
"% (operation, str(error_code))) if self.osc_udp_client is not None: self.osc_udp_client.send_message(\"/error\", [operation,",
"\"\"\" The pozyx ranging demo (c) Pozyx Labs please check",
"time difference elapsed = ConsoleLogging.get_elapsed_time(ConsoleLogging, start) previous_cycle_time = current_cycle_time current_cycle_time",
"pozyx device. Connect one of the Pozyx devices with USB",
"body coordinate system to the world coordinate system. - the",
"print(\"Anchors found: {0}\".format(list_size[0])) print(\"Anchor IDs: \", device_list) for i in",
"= self.pozyx.getDeviceCoordinates( device_list[i], anchor_coordinates, self.remote_id) print(\"ANCHOR,0x%0.4x, %s\" % (device_list[i], str(anchor_coordinates)))",
"len(anchors) > 4: status &= self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, len(anchors)) return status def",
"this script. This demo reads the following sensor data: -",
"communicate with a remote Pozyx. if __name__ == '__main__': #",
"remotely read register data from a pozyx device. Connect one",
"if type(formatted_data_dictionary) == dict: formatted_data_dictionary[\"Position\"] = [ \"x:\", one_cycle_position.x, \"y:\",",
"\"Error, no data to print for this line\" def publishSensorData(self,",
"% (device_list[i], str(anchor_coordinates))) if self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/anchor\",",
"as a OSC packet\"\"\" error_code = SingleRegister() network_id = self.remote_id",
"iterate_file by pressing ctrl+c except KeyboardInterrupt: pass if to_use_file: logfile.close()",
"\"\"\"User input configuration section, comment out to use above settings\"\"\"",
"= self.remote_id if network_id is None: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, local",
"= SimpleUDPClient(ip, network_port) o = Orientation3D(pozyx, osc_udp_client, anchors, algorithm, dimension,",
"print for this line\" def publishSensorData(self, sensor_data, calibration_status): \"\"\"Makes the",
"self.addComponentsOSC(sensor_data.euler_angles) self.addComponentsOSC(sensor_data.quaternion) self.addComponentsOSC(sensor_data.linear_acceleration) self.addComponentsOSC(sensor_data.gravity_vector) def addComponentsOSC(self, component): \"\"\"Adds a sensor",
"be viewed in the Processing sketch orientation_3D.pde \"\"\" from time",
"if network_id is None: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, local error code",
"component): \"\"\"Adds a sensor data component to the OSC message\"\"\"",
"acceleration - magnetic field strength - angular velocity - the",
"setup(self): \"\"\"There is no specific setup functionality\"\"\" self.current_time = time()",
"0, 2000)), DeviceCoordinates(0x615a, 1, Coordinates(0, 18288, 1000)), DeviceCoordinates(0x607c, 1, Coordinates(18288,",
"self.osc_udp_client.send(self.msg_builder.build()) def addSensorData(self, sensor_data): \"\"\"Adds the sensor data to the",
"The data can be viewed in the Processing sketch orientation_3D.pde",
"print(\"- No parameters required.\") print() print(\"- System will auto start",
"System will auto start configuration\") print() print(\"- System will auto",
"in self.anchors: status &= self.pozyx.addDevice(anchor, self.remote_id) if len(anchors) > 4:",
"print(\"ERROR %s, local error code %s\" % (operation, str(error_code))) if",
"up the Pozyx for positioning by calibrating its anchor list.\"\"\"",
"tuple, it returned an error string else: error_string = loop_results",
"self.pozyx.addDevice(anchor, self.remote_id) if len(anchors) > 4: status &= self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, len(anchors))",
"%s\" % (operation, \"0x%0.4x\" % network_id, str(error_code))) if self.osc_udp_client is",
"orientation of the device. This can be used to transform",
"to the world coordinate system. - the linear acceleration (the",
">> 2) self.msg_builder.add_arg((calibration_status[0] & 0x30) >> 4) self.msg_builder.add_arg((calibration_status[0] & 0xC0)",
"= current_cycle_time current_cycle_time = elapsed time_difference = current_cycle_time - previous_cycle_time",
"index # this allows Windows users to exit the while",
"Pozyx for positioning by calibrating its anchor list.\"\"\" print(\"------------POZYX POSITIONING",
"start) previous_cycle_time = current_cycle_time current_cycle_time = elapsed time_difference = current_cycle_time",
"one_cycle_position) # if the iterate_file didn't return a tuple, it",
"and the functionality to remotely read register data from a",
"loop(self): \"\"\"Gets new IMU sensor data\"\"\" # check sensor data",
"logfile = None if to_use_file: logfile = open(filename, 'a') FileWriting.write_sensor_and_position_header_to_file(logfile)",
"remote_id=None): self.pozyx = pozyx self.osc_udp_client = osc_udp_client self.anchors = anchors",
"data to the OSC message\"\"\" self.msg_builder.add_arg(sensor_data.pressure) self.addComponentsOSC(sensor_data.acceleration) self.addComponentsOSC(sensor_data.magnetic) self.addComponentsOSC(sensor_data.angular_vel) self.addComponentsOSC(sensor_data.euler_angles)",
"one_cycle_sensor_data, one_cycle_position = loop_results formatted_data_dictionary = ConsoleLogging.format_sensor_data( one_cycle_sensor_data, attributes_to_log) if",
"sensor data\"\"\" # check sensor data status sensor_data = SensorData()",
"self.printPublishConfigurationResult() def loop(self): \"\"\"Gets new IMU sensor data\"\"\" # check",
"%s on ID %s, error code %s\" % (operation, \"0x%0.4x\"",
"if status == POZYX_SUCCESS: print(\"ERROR %s on ID %s, error",
"6) def setAnchorsManual(self): \"\"\"Adds the manually measured anchors to the",
"status position = Coordinates() status = self.pozyx.doPositioning( position, self.dimension, self.height,",
"for positioning by calibrating its anchor list.\"\"\" print(\"------------POZYX POSITIONING V1.0",
"the quaternion rotation describing the 3D orientation of the device.",
"can be viewed in the Processing sketch orientation_3D.pde \"\"\" from",
"= None index = 0 previous_cycle_time = 0 current_cycle_time =",
"- the linear acceleration (the acceleration excluding gravity) - the",
"self.msg_builder.add_arg(int(1000 * (time() - self.current_time))) current_time = time() self.addSensorData(sensor_data) self.addCalibrationStatus(calibration_status)",
"the OSC message\"\"\" for data in component.data: self.msg_builder.add_arg(float(data)) def addCalibrationStatus(self,",
"the 3D orientation and the functionality to remotely read register",
"input configuration section, comment out to use above settings\"\"\" remote",
"and publishes it\"\"\" self.msg_builder = OscMessageBuilder(\"/sensordata\") self.msg_builder.add_arg(int(1000 * (time() -",
"0x0C) >> 2) self.msg_builder.add_arg((calibration_status[0] & 0x30) >> 4) self.msg_builder.add_arg((calibration_status[0] &",
"a sensor data component to the OSC message\"\"\" for data",
"is not None: self.osc_udp_client.send_message( \"/anchor\", [device_list[i], int(anchor_coordinates.x), int(anchor_coordinates.y), int(anchor_coordinates.z)]) sleep(0.025)",
"device network ID remote = True # whether to use",
"to use above settings\"\"\" remote = UserInput.use_remote() remote_id = UserInput.get_remote_id(remote)",
"self.height = height self.remote_id = remote_id def setup(self): \"\"\"There is",
"= False filename = None \"\"\"User input configuration section, comment",
"% (operation, \"0x%0.4x\" % network_id, str(error_code))) if self.osc_udp_client is not",
"POZYX_3D # positioning dimension height = 1000 # height of",
"self.remote_id is not None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) == POZYX_SUCCESS: status",
"remote_id) o.setup() logfile = None if to_use_file: logfile = open(filename,",
"the 3D orientation of the device. This can be used",
"use_processing = True ip = \"127.0.0.1\" network_port = 8888 anchors",
"for data in component.data: self.msg_builder.add_arg(float(data)) def addCalibrationStatus(self, calibration_status): \"\"\"Adds the",
"reads the following sensor data: - pressure - acceleration -",
"a remote Pozyx. if __name__ == '__main__': # shortcut to",
"DeviceCoordinates(0x6134, 1, Coordinates(18288, 18288, 2000))] # algorithm = POZYX_POS_ALG_UWB_ONLY #",
"one for one.\"\"\" status = self.pozyx.clearDevices(self.remote_id) for anchor in self.anchors:",
"self.osc_udp_client.send_message(\"/error\", [operation, 0, error_code[0]]) return status = self.pozyx.getErrorCode(error_code, self.remote_id) if",
"formatted_data_dictionary[\"Position\"] = [ \"x:\", one_cycle_position.x, \"y:\", one_cycle_position.y, \"z:\", one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index,",
"to the OSC message\"\"\" for data in component.data: self.msg_builder.add_arg(float(data)) def",
"will auto start configuration\") print() print(\"- System will auto start",
"= self.pozyx.getDeviceListSize(list_size, self.remote_id) print(\"List size: {0}\".format(list_size[0])) if list_size[0] != len(self.anchors):",
"\"\"\"Adds a sensor data component to the OSC message\"\"\" for",
"sensor_data, calibration_status): \"\"\"Makes the OSC sensor data package and publishes",
"dimension height = 1000 # height of device, required in",
"no data to print for this line\" def publishSensorData(self, sensor_data,",
"for one.\"\"\" status = self.pozyx.clearDevices(self.remote_id) for anchor in self.anchors: status",
"None if to_use_file: logfile = open(filename, 'a') FileWriting.write_sensor_and_position_header_to_file(logfile) start =",
"operation): \"\"\"Prints the Pozyx's error and possibly sends it as",
"if status == POZYX_SUCCESS: # check position status position =",
"configuration\") print() print(\"- System will auto start positioning\") print(\"------------POZYX POSITIONING",
"heading, roll and pitch - the quaternion rotation describing the",
"# should only happen when not being able to communicate",
"True: # updates elapsed time and time difference elapsed =",
"self.pozyx.getAllSensorData(sensor_data, self.remote_id) status &= self.pozyx.getCalibrationStatus(calibration_status, self.remote_id) if status == POZYX_SUCCESS:",
"SensorAndPositionFileWriting as FileWriting from modules.console_logging_functions import ConsoleLoggingFunctions as ConsoleLogging import",
"# tracking positioning algorithm dimension = POZYX_3D # positioning dimension",
"formatted_data_dictionary = ConsoleLogging.format_sensor_data( one_cycle_sensor_data, attributes_to_log) if type(formatted_data_dictionary) == dict: formatted_data_dictionary[\"Position\"]",
"the world coordinate system. - the linear acceleration (the acceleration",
"print(\"NOTES: \") print(\"- No parameters required.\") print() print(\"- System will",
"self.algorithm, remote_id=self.remote_id) if status == POZYX_SUCCESS: # self.print_publish_position(position) self.publishSensorData(sensor_data, calibration_status)",
"in 2.5D positioning pozyx = PozyxSerial(serial_port) osc_udp_client = SimpleUDPClient(ip, network_port)",
"time as t class Orientation3D(object): \"\"\"Reads out all sensor data",
"This demo requires one (or two) pozyx shields. It demonstrates",
"[operation, 0, error_code[0]]) return status = self.pozyx.getErrorCode(error_code, self.remote_id) if status",
"Coordinates(18288, 0, 1000)), DeviceCoordinates(0x6134, 1, Coordinates(18288, 18288, 2000))] # algorithm",
"def publishSensorData(self, sensor_data, calibration_status): \"\"\"Makes the OSC sensor data package",
"from the body coordinate system to the world coordinate system.",
"one_cycle_sensor_data, attributes_to_log) if type(formatted_data_dictionary) == dict: formatted_data_dictionary[\"Position\"] = [ \"x:\",",
"import time from time import sleep from pypozyx import *",
"gravity) - the gravitational vector The data can be viewed",
"will auto start positioning\") print(\"------------POZYX POSITIONING V1.0 --------------\") print() print(\"START",
"# check position status position = Coordinates() status = self.pozyx.doPositioning(",
"if self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/error\", [operation, network_id, error_code[0]])",
"+= 1 # increment data index # this allows Windows",
"= UserInput.use_file() filename = UserInput.get_filename(to_use_file) attributes_to_log = UserInput.get_multiple_attributes_to_log() use_processing =",
"Pozyx's device list one for one.\"\"\" status = self.pozyx.clearDevices(self.remote_id) for",
"angular velocity - the heading, roll and pitch - the",
"list_size = SingleRegister() status = self.pozyx.getDeviceListSize(list_size, self.remote_id) print(\"List size: {0}\".format(list_size[0]))",
"orientation and the functionality to remotely read register data from",
"anchor_coordinates = Coordinates() status = self.pozyx.getDeviceCoordinates( device_list[i], anchor_coordinates, self.remote_id) print(\"ANCHOR,0x%0.4x,",
"18288, 2000))] # algorithm = POZYX_POS_ALG_UWB_ONLY # positioning algorithm to",
"out the port yourself serial_port = get_serial_ports()[0].device remote_id = 0x6110",
"remote device # if not remote: # remote_id = None",
"def printPublishConfigurationResult(self): \"\"\"Prints and potentially publishes the anchor configuration result",
"* from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU from pythonosc.osc_message_builder import OscMessageBuilder from",
"== POZYX_SUCCESS: print(\"ERROR %s on ID %s, error code %s\"",
"measured anchors to the Pozyx's device list one for one.\"\"\"",
"height=1000, remote_id=None): self.pozyx = pozyx self.osc_udp_client = osc_udp_client self.anchors =",
"human-readable way.\"\"\" list_size = SingleRegister() status = self.pozyx.getDeviceListSize(list_size, self.remote_id) print(\"List",
"not None: self.osc_udp_client.send_message( \"/anchor\", [device_list[i], int(anchor_coordinates.x), int(anchor_coordinates.y), int(anchor_coordinates.z)]) sleep(0.025) def",
"str(error_code))) if self.osc_udp_client is not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, error_code[0]])",
"str(error_code))) if self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/error\", [operation, network_id,",
"PozyxSerial(serial_port) osc_udp_client = SimpleUDPClient(ip, network_port) o = Orientation3D(pozyx, osc_udp_client, anchors,",
"of the device. This can be used to transform from",
"one_cycle_position.y, \"z:\", one_cycle_position.z] ConsoleLogging.log_sensor_data_to_console(index, elapsed, formatted_data_dictionary) if to_use_file: FileWriting.write_sensor_and_position_data_to_file( index,",
"the gravitational vector The data can be viewed in the",
"remote_id = None index = 0 previous_cycle_time = 0 current_cycle_time",
"self.print_publish_position(position) self.publishSensorData(sensor_data, calibration_status) return sensor_data, position else: pass # self.print_publish_error_code(\"positioning\")",
"remote error code, local error code %s\" % (operation, str(error_code)))",
"self.msg_builder.add_arg((calibration_status[0] & 0x30) >> 4) self.msg_builder.add_arg((calibration_status[0] & 0xC0) >> 6)",
"IDs: \", device_list) for i in range(list_size[0]): anchor_coordinates = Coordinates()",
"Coordinates(18288, 18288, 2000))] # algorithm = POZYX_POS_ALG_UWB_ONLY # positioning algorithm",
"self.remote_id) if status == POZYX_SUCCESS: print(\"ERROR %s on ID %s,",
"0x03) self.msg_builder.add_arg((calibration_status[0] & 0x0C) >> 2) self.msg_builder.add_arg((calibration_status[0] & 0x30) >>",
"list.\"\"\" print(\"------------POZYX POSITIONING V1.0 -------------\") print(\"NOTES: \") print(\"- No parameters",
"status == POZYX_SUCCESS: # self.print_publish_position(position) self.publishSensorData(sensor_data, calibration_status) return sensor_data, position",
"len(self.anchors): self.printPublishErrorCode(\"configuration\") return device_list = DeviceList(list_size=list_size[0]) status = self.pozyx.getDeviceIds(device_list, self.remote_id)",
"Pozyx. if __name__ == '__main__': # shortcut to not have",
"= True # whether to use a remote device #",
"by calibrating its anchor list.\"\"\" print(\"------------POZYX POSITIONING V1.0 -------------\") print(\"NOTES:",
"and possibly sends it as a OSC packet\"\"\" error_code =",
"orientation_3D.pde \"\"\" from time import time from time import sleep",
"0xC0) >> 6) def setAnchorsManual(self): \"\"\"Adds the manually measured anchors",
"self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/anchor\", [device_list[i], int(anchor_coordinates.x), int(anchor_coordinates.y), int(anchor_coordinates.z)])",
"POZYX_SUCCESS: print(\"ERROR %s on ID %s, error code %s\" %",
"= None if to_use_file: logfile = open(filename, 'a') FileWriting.write_sensor_and_position_header_to_file(logfile) start",
"else: error_string = loop_results ConsoleLogging.print_data_error_message(index, elapsed, error_string) index += 1",
"an error message loop_results = o.loop() if type(loop_results) == tuple:",
"sensor_data, position else: pass # self.print_publish_error_code(\"positioning\") return \"Error, no data",
"anchors to the Pozyx's device list one for one.\"\"\" status",
"%s, error code %s\" % (operation, \"0x%0.4x\" % network_id, str(error_code)))",
"[device_list[i], int(anchor_coordinates.x), int(anchor_coordinates.y), int(anchor_coordinates.z)]) sleep(0.025) def printPublishErrorCode(self, operation): \"\"\"Prints the",
"Pozyx\"\"\" def __init__(self, pozyx, osc_udp_client, anchors, algorithm=POZYX_POS_ALG_UWB_ONLY, dimension=POZYX_3D, height=1000, remote_id=None):",
"error and possibly sends it as a OSC packet\"\"\" error_code",
"updates elapsed time and time difference elapsed = ConsoleLogging.get_elapsed_time(ConsoleLogging, start)",
"or an error message loop_results = o.loop() if type(loop_results) ==",
"loop_results = o.loop() if type(loop_results) == tuple: one_cycle_sensor_data, one_cycle_position =",
"= self.pozyx.clearDevices(self.remote_id) for anchor in self.anchors: status &= self.pozyx.addDevice(anchor, self.remote_id)",
"time() \"\"\"Sets up the Pozyx for positioning by calibrating its",
"= SingleRegister() if self.remote_id is not None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01)",
"= SensorData() calibration_status = SingleRegister() if self.remote_id is not None",
"\", device_list) for i in range(list_size[0]): anchor_coordinates = Coordinates() status",
"register data from a pozyx device. Connect one of the",
"FileWriting.write_sensor_and_position_data_to_file( index, elapsed, time_difference, logfile, one_cycle_sensor_data, one_cycle_position) # if the",
"vector The data can be viewed in the Processing sketch",
"formatted_data_dictionary) if to_use_file: FileWriting.write_sensor_and_position_data_to_file( index, elapsed, time_difference, logfile, one_cycle_sensor_data, one_cycle_position)",
"previous_cycle_time = 0 current_cycle_time = 0 attributes_to_log = [\"acceleration\"] to_use_file",
"sensor_data = SensorData() calibration_status = SingleRegister() if self.remote_id is not",
"= ConsoleLogging.get_elapsed_time(ConsoleLogging, start) previous_cycle_time = current_cycle_time current_cycle_time = elapsed time_difference",
"2000))] # algorithm = POZYX_POS_ALG_UWB_ONLY # positioning algorithm to use",
"4) self.msg_builder.add_arg((calibration_status[0] & 0xC0) >> 6) def setAnchorsManual(self): \"\"\"Adds the",
"time import sleep from pypozyx import * from pypozyx.definitions.bitmasks import",
"pressure - acceleration - magnetic field strength - angular velocity",
"print(\"------------POZYX POSITIONING V1.0 --------------\") print() print(\"START Ranging: \") self.pozyx.clearDevices(self.remote_id) self.setAnchorsManual()",
"error code %s\" % (operation, \"0x%0.4x\" % network_id, str(error_code))) if",
"type(formatted_data_dictionary) == dict: formatted_data_dictionary[\"Position\"] = [ \"x:\", one_cycle_position.x, \"y:\", one_cycle_position.y,",
"The pozyx ranging demo (c) Pozyx Labs please check out",
"following sensor data: - pressure - acceleration - magnetic field",
"def setup(self): \"\"\"There is no specific setup functionality\"\"\" self.current_time =",
"self.remote_id) if len(anchors) > 4: status &= self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, len(anchors)) return",
"# self.print_publish_position(position) self.publishSensorData(sensor_data, calibration_status) return sensor_data, position else: pass #",
"sleep from pypozyx import * from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU from",
"SimpleUDPClient from modules.user_input_config_functions import UserInputConfigFunctions as UserInput from modules.file_writing import",
"4: status &= self.pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, len(anchors)) return status def printPublishConfigurationResult(self): \"\"\"Prints",
"# updates elapsed time and time difference elapsed = ConsoleLogging.get_elapsed_time(ConsoleLogging,",
"addCalibrationStatus(self, calibration_status): \"\"\"Adds the calibration status data to the OSC",
"calibration_status = SingleRegister() if self.remote_id is not None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU,",
"self.osc_udp_client is not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, error_code[0]]) return status",
"print(\"List size: {0}\".format(list_size[0])) if list_size[0] != len(self.anchors): self.printPublishErrorCode(\"configuration\") return device_list",
"out all sensor data from either a local or remote",
"= osc_udp_client self.anchors = anchors self.algorithm = algorithm self.dimension =",
"&= self.pozyx.getCalibrationStatus(calibration_status, self.remote_id) if status == POZYX_SUCCESS: # check position",
"3D orientation and the functionality to remotely read register data",
"describing the 3D orientation of the device. This can be",
"a local or remote Pozyx\"\"\" def __init__(self, pozyx, osc_udp_client, anchors,",
"self.pozyx.doPositioning( position, self.dimension, self.height, self.algorithm, remote_id=self.remote_id) if status == POZYX_SUCCESS:",
"\"\"\"Prints and potentially publishes the anchor configuration result in a",
"line\" def publishSensorData(self, sensor_data, calibration_status): \"\"\"Makes the OSC sensor data",
"data\"\"\" # check sensor data status sensor_data = SensorData() calibration_status",
"self.msg_builder.add_arg(sensor_data.pressure) self.addComponentsOSC(sensor_data.acceleration) self.addComponentsOSC(sensor_data.magnetic) self.addComponentsOSC(sensor_data.angular_vel) self.addComponentsOSC(sensor_data.euler_angles) self.addComponentsOSC(sensor_data.quaternion) self.addComponentsOSC(sensor_data.linear_acceleration) self.addComponentsOSC(sensor_data.gravity_vector) def addComponentsOSC(self,",
"not have to find out the port yourself serial_port =",
"import SimpleUDPClient from modules.user_input_config_functions import UserInputConfigFunctions as UserInput from modules.file_writing",
"in range(list_size[0]): anchor_coordinates = Coordinates() status = self.pozyx.getDeviceCoordinates( device_list[i], anchor_coordinates,",
"exit the while iterate_file by pressing ctrl+c except KeyboardInterrupt: pass",
"for i in range(list_size[0]): anchor_coordinates = Coordinates() status = self.pozyx.getDeviceCoordinates(",
"# remote device network ID remote = True # whether",
"0x6110 # remote device network ID remote = True #",
"V1.0 --------------\") print() print(\"START Ranging: \") self.pozyx.clearDevices(self.remote_id) self.setAnchorsManual() self.printPublishConfigurationResult() def",
"self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) == POZYX_SUCCESS: status = self.pozyx.getAllSensorData(sensor_data, self.remote_id) status &=",
"import SensorAndPositionFileWriting as FileWriting from modules.console_logging_functions import ConsoleLoggingFunctions as ConsoleLogging",
"None: self.osc_udp_client.send_message( \"/anchor\", [device_list[i], int(anchor_coordinates.x), int(anchor_coordinates.y), int(anchor_coordinates.z)]) sleep(0.025) def printPublishErrorCode(self,",
"== POZYX_SUCCESS: # check position status position = Coordinates() status",
"int(anchor_coordinates.z)]) sleep(0.025) def printPublishErrorCode(self, operation): \"\"\"Prints the Pozyx's error and",
"status data to the OSC message\"\"\" self.msg_builder.add_arg(calibration_status[0] & 0x03) self.msg_builder.add_arg((calibration_status[0]",
"network_id, str(error_code))) if self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/error\", [operation,",
"self.osc_udp_client is not None: self.osc_udp_client.send_message(\"/error\", [operation, 0, -1]) # should",
"positioning algorithm to use algorithm = POZYX_POS_ALG_TRACKING # tracking positioning",
"= self.pozyx.getAllSensorData(sensor_data, self.remote_id) status &= self.pozyx.getCalibrationStatus(calibration_status, self.remote_id) if status ==",
"configuration section, comment out to use above settings\"\"\" remote =",
"no specific setup functionality\"\"\" self.current_time = time() \"\"\"Sets up the",
"0x30) >> 4) self.msg_builder.add_arg((calibration_status[0] & 0xC0) >> 6) def setAnchorsManual(self):",
"dict: formatted_data_dictionary[\"Position\"] = [ \"x:\", one_cycle_position.x, \"y:\", one_cycle_position.y, \"z:\", one_cycle_position.z]",
"logfile = open(filename, 'a') FileWriting.write_sensor_and_position_header_to_file(logfile) start = ConsoleLogging.get_time() try: while",
"= elapsed time_difference = current_cycle_time - previous_cycle_time # store iterate_file",
"gravitational vector The data can be viewed in the Processing",
"if self.osc_udp_client is not None: self.osc_udp_client.send_message( \"/anchor\", [device_list[i], int(anchor_coordinates.x), int(anchor_coordinates.y),",
"self.osc_udp_client.send_message(\"/error\", [operation, 0, -1]) # should only happen when not",
"network_id is None: self.pozyx.getErrorCode(error_code) print(\"ERROR %s, local error code %s\"",
"section, comment out to use above settings\"\"\" remote = UserInput.use_remote()",
"viewed in the Processing sketch orientation_3D.pde \"\"\" from time import",
"ConsoleLogging.format_sensor_data( one_cycle_sensor_data, attributes_to_log) if type(formatted_data_dictionary) == dict: formatted_data_dictionary[\"Position\"] = [",
"packet\"\"\" error_code = SingleRegister() network_id = self.remote_id if network_id is",
"self.addComponentsOSC(sensor_data.angular_vel) self.addComponentsOSC(sensor_data.euler_angles) self.addComponentsOSC(sensor_data.quaternion) self.addComponentsOSC(sensor_data.linear_acceleration) self.addComponentsOSC(sensor_data.gravity_vector) def addComponentsOSC(self, component): \"\"\"Adds a",
"\"\"\" from time import time from time import sleep from",
"0, error_code[0]]) return status = self.pozyx.getErrorCode(error_code, self.remote_id) if status ==",
"list one for one.\"\"\" status = self.pozyx.clearDevices(self.remote_id) for anchor in",
"excluding gravity) - the gravitational vector The data can be",
"if self.remote_id is not None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) == POZYX_SUCCESS:",
"device. Connect one of the Pozyx devices with USB and"
] |
[
"e: self.logger.error(u\"ENCOUNTERED AN INTERNAL ERROR: {}\\n\\tTraceback:\\n{}\".format(e, traceback.format_exc())) self.send_error(INTERNAL_ERROR_MSG.format(e)) return None",
"attribute. Usage: @handle_expected_exceptions def fn(self, ...): etc...\"\"\" exceptions_to_handle = tuple(EXPECTED_EXCEPTIONS)",
"suggests something is wrong with LivyClientLib's implementation. @wraps(f) def wrapped(self,",
"LivyClientLib's implementation. @wraps(f) def wrapped(self, *args, **kwargs): try: out =",
"decorator that catches all exceptions from the function f and",
"msg self.status = status # == DECORATORS FOR EXCEPTION HANDLING",
"# # Author: huangnj # Time: 2019/09/27 import traceback from",
"That's because DataFrameParseException # is an internal error that suggests",
"Self can be any object with an \"ipython_display\" attribute. Usage:",
"return None else: return out return wrapped def wrap_unexpected_exceptions(f, execute_if_error=None):",
"\"unexpected\" exceptions, and a request is made to the user",
"None if execute_if_error is None, or else returns the output",
"*args, **kwargs) except Exception as e: self.logger.error(u\"ENCOUNTERED AN INTERNAL ERROR:",
"etc...\"\"\" exceptions_to_handle = tuple(EXPECTED_EXCEPTIONS) # Notice that we're NOT handling",
"import EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG from hdfs.util import HdfsError # == EXCEPTIONS",
"None if execute_if_error is None else execute_if_error() else: return out",
"HdfsError # == EXCEPTIONS == class SessionManagementException(Exception): pass class CommandNotAllowedException(Exception):",
"as e: self.logger.error(u\"ENCOUNTERED AN INTERNAL ERROR: {}\\n\\tTraceback:\\n{}\".format(e, traceback.format_exc())) self.send_error(INTERNAL_ERROR_MSG.format(e)) return",
"# option parse Error class OptionParsingError(RuntimeError): pass class OptionParsingExit(Exception): def",
"OptionParsingError] def handle_expected_exceptions(f): \"\"\"A decorator that handles expected exceptions. Self",
"== class SessionManagementException(Exception): pass class CommandNotAllowedException(Exception): pass class CommandExecuteException(Exception): pass",
"None, or else returns the output of the function execute_if_error.",
"..etc \"\"\" @wraps(f) def wrapped(self, *args, **kwargs): try: out =",
"not log! as some messages may contain private client information",
"== EXCEPTIONS == class SessionManagementException(Exception): pass class CommandNotAllowedException(Exception): pass class",
"execute_if_error=None): \"\"\"A decorator that catches all exceptions from the function",
"= tuple(EXPECTED_EXCEPTIONS) # Notice that we're NOT handling e.DataFrameParseException here.",
"Usage: @wrap_unexpected_exceptions def fn(self, ...): ..etc \"\"\" @wraps(f) def wrapped(self,",
"a \"ipython_display\" attribute. All exceptions are logged as \"unexpected\" exceptions,",
"a request is made to the user to file an",
"def fn(self, ...): ..etc \"\"\" @wraps(f) def wrapped(self, *args, **kwargs):",
"AN INTERNAL ERROR: {}\\n\\tTraceback:\\n{}\".format(e, traceback.format_exc())) self.send_error(INTERNAL_ERROR_MSG.format(e)) return None if execute_if_error",
"from the function f and alerts the user about them.",
"the function execute_if_error. Usage: @wrap_unexpected_exceptions def fn(self, ...): ..etc \"\"\"",
"def __init__(self, status, msg): self.msg = msg self.status = status",
"== EXPECTED_EXCEPTIONS = [HdfsError, SessionManagementException, CommandNotAllowedException, CommandExecuteException, OptionParsingExit, OptionParsingError] def",
"error that suggests something is wrong with LivyClientLib's implementation. @wraps(f)",
"def wrap_unexpected_exceptions(f, execute_if_error=None): \"\"\"A decorator that catches all exceptions from",
"self.msg = msg self.status = status # == DECORATORS FOR",
"object with a \"logger\" attribute and a \"ipython_display\" attribute. All",
"hdfs_kernel.constants import EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG from hdfs.util import HdfsError # ==",
"= [HdfsError, SessionManagementException, CommandNotAllowedException, CommandExecuteException, OptionParsingExit, OptionParsingError] def handle_expected_exceptions(f): \"\"\"A",
"*args, **kwargs): try: out = f(self, *args, **kwargs) except Exception",
"class SessionManagementException(Exception): pass class CommandNotAllowedException(Exception): pass class CommandExecuteException(Exception): pass #",
"\"logger\" attribute and a \"ipython_display\" attribute. All exceptions are logged",
"[HdfsError, SessionManagementException, CommandNotAllowedException, CommandExecuteException, OptionParsingExit, OptionParsingError] def handle_expected_exceptions(f): \"\"\"A decorator",
"coding=utf-8 -*- # # Author: huangnj # Time: 2019/09/27 import",
"handle_expected_exceptions(f): \"\"\"A decorator that handles expected exceptions. Self can be",
"to the user to file an issue at the Github",
"request is made to the user to file an issue",
"an issue at the Github repository. If there is an",
"pass class OptionParsingExit(Exception): def __init__(self, status, msg): self.msg = msg",
"All exceptions are logged as \"unexpected\" exceptions, and a request",
"from hdfs.util import HdfsError # == EXCEPTIONS == class SessionManagementException(Exception):",
"def handle_expected_exceptions(f): \"\"\"A decorator that handles expected exceptions. Self can",
"handling e.DataFrameParseException here. That's because DataFrameParseException # is an internal",
"and a \"ipython_display\" attribute. All exceptions are logged as \"unexpected\"",
"attribute. All exceptions are logged as \"unexpected\" exceptions, and a",
"there is an error, returns None if execute_if_error is None,",
"CommandNotAllowedException(Exception): pass class CommandExecuteException(Exception): pass # option parse Error class",
"some messages may contain private client information self.send_error(EXPECTED_ERROR_MSG.format(err)) return None",
"OptionParsingExit(Exception): def __init__(self, status, msg): self.msg = msg self.status =",
"messages may contain private client information self.send_error(EXPECTED_ERROR_MSG.format(err)) return None else:",
"exceptions, and a request is made to the user to",
"if execute_if_error is None else execute_if_error() else: return out return",
"<reponame>Jasper912/jupyter-hdfs-kernel #!/usr/bin/env python # -*- coding=utf-8 -*- # # Author:",
"hdfs.util import HdfsError # == EXCEPTIONS == class SessionManagementException(Exception): pass",
"is an error, returns None if execute_if_error is None, or",
"*args, **kwargs): try: out = f(self, *args, **kwargs) except exceptions_to_handle",
"out return wrapped def wrap_unexpected_exceptions(f, execute_if_error=None): \"\"\"A decorator that catches",
"\"ipython_display\" attribute. All exceptions are logged as \"unexpected\" exceptions, and",
"# Do not log! as some messages may contain private",
"exceptions are logged as \"unexpected\" exceptions, and a request is",
"traceback from functools import wraps from hdfs_kernel.constants import EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG",
"= msg self.status = status # == DECORATORS FOR EXCEPTION",
"# == DECORATORS FOR EXCEPTION HANDLING == EXPECTED_EXCEPTIONS = [HdfsError,",
"from hdfs_kernel.constants import EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG from hdfs.util import HdfsError #",
"except exceptions_to_handle as err: # Do not log! as some",
"__init__(self, status, msg): self.msg = msg self.status = status #",
"file an issue at the Github repository. If there is",
"def fn(self, ...): etc...\"\"\" exceptions_to_handle = tuple(EXPECTED_EXCEPTIONS) # Notice that",
"is None, or else returns the output of the function",
"self.logger.error(u\"ENCOUNTERED AN INTERNAL ERROR: {}\\n\\tTraceback:\\n{}\".format(e, traceback.format_exc())) self.send_error(INTERNAL_ERROR_MSG.format(e)) return None if",
"2019/09/27 import traceback from functools import wraps from hdfs_kernel.constants import",
"of the function execute_if_error. Usage: @wrap_unexpected_exceptions def fn(self, ...): ..etc",
"at the Github repository. If there is an error, returns",
"Exception as e: self.logger.error(u\"ENCOUNTERED AN INTERNAL ERROR: {}\\n\\tTraceback:\\n{}\".format(e, traceback.format_exc())) self.send_error(INTERNAL_ERROR_MSG.format(e))",
"wrapped(self, *args, **kwargs): try: out = f(self, *args, **kwargs) except",
"def wrapped(self, *args, **kwargs): try: out = f(self, *args, **kwargs)",
"an error, returns None if execute_if_error is None, or else",
"wrap_unexpected_exceptions(f, execute_if_error=None): \"\"\"A decorator that catches all exceptions from the",
"made to the user to file an issue at the",
"function execute_if_error. Usage: @wrap_unexpected_exceptions def fn(self, ...): ..etc \"\"\" @wraps(f)",
"except Exception as e: self.logger.error(u\"ENCOUNTERED AN INTERNAL ERROR: {}\\n\\tTraceback:\\n{}\".format(e, traceback.format_exc()))",
"be any object with a \"logger\" attribute and a \"ipython_display\"",
"DECORATORS FOR EXCEPTION HANDLING == EXPECTED_EXCEPTIONS = [HdfsError, SessionManagementException, CommandNotAllowedException,",
"out = f(self, *args, **kwargs) except exceptions_to_handle as err: #",
"\"\"\" @wraps(f) def wrapped(self, *args, **kwargs): try: out = f(self,",
"information self.send_error(EXPECTED_ERROR_MSG.format(err)) return None else: return out return wrapped def",
"something is wrong with LivyClientLib's implementation. @wraps(f) def wrapped(self, *args,",
"returns None if execute_if_error is None, or else returns the",
"import HdfsError # == EXCEPTIONS == class SessionManagementException(Exception): pass class",
"them. Self can be any object with a \"logger\" attribute",
"and a request is made to the user to file",
"and alerts the user about them. Self can be any",
"Do not log! as some messages may contain private client",
"return wrapped def wrap_unexpected_exceptions(f, execute_if_error=None): \"\"\"A decorator that catches all",
"expected exceptions. Self can be any object with an \"ipython_display\"",
"wrapped def wrap_unexpected_exceptions(f, execute_if_error=None): \"\"\"A decorator that catches all exceptions",
"catches all exceptions from the function f and alerts the",
"about them. Self can be any object with a \"logger\"",
"err: # Do not log! as some messages may contain",
"we're NOT handling e.DataFrameParseException here. That's because DataFrameParseException # is",
"HANDLING == EXPECTED_EXCEPTIONS = [HdfsError, SessionManagementException, CommandNotAllowedException, CommandExecuteException, OptionParsingExit, OptionParsingError]",
"any object with an \"ipython_display\" attribute. Usage: @handle_expected_exceptions def fn(self,",
"try: out = f(self, *args, **kwargs) except exceptions_to_handle as err:",
"INTERNAL_ERROR_MSG from hdfs.util import HdfsError # == EXCEPTIONS == class",
"pass # option parse Error class OptionParsingError(RuntimeError): pass class OptionParsingExit(Exception):",
"e.DataFrameParseException here. That's because DataFrameParseException # is an internal error",
"can be any object with a \"logger\" attribute and a",
"the user to file an issue at the Github repository.",
"out = f(self, *args, **kwargs) except Exception as e: self.logger.error(u\"ENCOUNTERED",
"Time: 2019/09/27 import traceback from functools import wraps from hdfs_kernel.constants",
"that handles expected exceptions. Self can be any object with",
"handles expected exceptions. Self can be any object with an",
"a \"logger\" attribute and a \"ipython_display\" attribute. All exceptions are",
"= f(self, *args, **kwargs) except Exception as e: self.logger.error(u\"ENCOUNTERED AN",
"return None if execute_if_error is None else execute_if_error() else: return",
"# Time: 2019/09/27 import traceback from functools import wraps from",
"with LivyClientLib's implementation. @wraps(f) def wrapped(self, *args, **kwargs): try: out",
"== DECORATORS FOR EXCEPTION HANDLING == EXPECTED_EXCEPTIONS = [HdfsError, SessionManagementException,",
"parse Error class OptionParsingError(RuntimeError): pass class OptionParsingExit(Exception): def __init__(self, status,",
"logged as \"unexpected\" exceptions, and a request is made to",
"# -*- coding=utf-8 -*- # # Author: huangnj # Time:",
"with an \"ipython_display\" attribute. Usage: @handle_expected_exceptions def fn(self, ...): etc...\"\"\"",
"contain private client information self.send_error(EXPECTED_ERROR_MSG.format(err)) return None else: return out",
"function f and alerts the user about them. Self can",
"try: out = f(self, *args, **kwargs) except Exception as e:",
"exceptions from the function f and alerts the user about",
"tuple(EXPECTED_EXCEPTIONS) # Notice that we're NOT handling e.DataFrameParseException here. That's",
"**kwargs): try: out = f(self, *args, **kwargs) except exceptions_to_handle as",
"as some messages may contain private client information self.send_error(EXPECTED_ERROR_MSG.format(err)) return",
"= status # == DECORATORS FOR EXCEPTION HANDLING == EXPECTED_EXCEPTIONS",
"here. That's because DataFrameParseException # is an internal error that",
"issue at the Github repository. If there is an error,",
"ERROR: {}\\n\\tTraceback:\\n{}\".format(e, traceback.format_exc())) self.send_error(INTERNAL_ERROR_MSG.format(e)) return None if execute_if_error is None",
"*args, **kwargs) except exceptions_to_handle as err: # Do not log!",
"exceptions_to_handle = tuple(EXPECTED_EXCEPTIONS) # Notice that we're NOT handling e.DataFrameParseException",
"repository. If there is an error, returns None if execute_if_error",
"else: return out return wrapped def wrap_unexpected_exceptions(f, execute_if_error=None): \"\"\"A decorator",
"that we're NOT handling e.DataFrameParseException here. That's because DataFrameParseException #",
"the output of the function execute_if_error. Usage: @wrap_unexpected_exceptions def fn(self,",
"status # == DECORATORS FOR EXCEPTION HANDLING == EXPECTED_EXCEPTIONS =",
"internal error that suggests something is wrong with LivyClientLib's implementation.",
"with a \"logger\" attribute and a \"ipython_display\" attribute. All exceptions",
"-*- coding=utf-8 -*- # # Author: huangnj # Time: 2019/09/27",
"as err: # Do not log! as some messages may",
"object with an \"ipython_display\" attribute. Usage: @handle_expected_exceptions def fn(self, ...):",
"# Notice that we're NOT handling e.DataFrameParseException here. That's because",
"Notice that we're NOT handling e.DataFrameParseException here. That's because DataFrameParseException",
"is an internal error that suggests something is wrong with",
"log! as some messages may contain private client information self.send_error(EXPECTED_ERROR_MSG.format(err))",
"\"\"\"A decorator that catches all exceptions from the function f",
"returns the output of the function execute_if_error. Usage: @wrap_unexpected_exceptions def",
"...): ..etc \"\"\" @wraps(f) def wrapped(self, *args, **kwargs): try: out",
"CommandExecuteException(Exception): pass # option parse Error class OptionParsingError(RuntimeError): pass class",
"attribute and a \"ipython_display\" attribute. All exceptions are logged as",
"pass class CommandExecuteException(Exception): pass # option parse Error class OptionParsingError(RuntimeError):",
"EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG from hdfs.util import HdfsError # == EXCEPTIONS ==",
"-*- # # Author: huangnj # Time: 2019/09/27 import traceback",
"that catches all exceptions from the function f and alerts",
"self.send_error(INTERNAL_ERROR_MSG.format(e)) return None if execute_if_error is None else execute_if_error() else:",
"f(self, *args, **kwargs) except exceptions_to_handle as err: # Do not",
"class CommandExecuteException(Exception): pass # option parse Error class OptionParsingError(RuntimeError): pass",
"all exceptions from the function f and alerts the user",
"f(self, *args, **kwargs) except Exception as e: self.logger.error(u\"ENCOUNTERED AN INTERNAL",
"CommandNotAllowedException, CommandExecuteException, OptionParsingExit, OptionParsingError] def handle_expected_exceptions(f): \"\"\"A decorator that handles",
"functools import wraps from hdfs_kernel.constants import EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG from hdfs.util",
"an \"ipython_display\" attribute. Usage: @handle_expected_exceptions def fn(self, ...): etc...\"\"\" exceptions_to_handle",
"are logged as \"unexpected\" exceptions, and a request is made",
"python # -*- coding=utf-8 -*- # # Author: huangnj #",
"\"ipython_display\" attribute. Usage: @handle_expected_exceptions def fn(self, ...): etc...\"\"\" exceptions_to_handle =",
"Usage: @handle_expected_exceptions def fn(self, ...): etc...\"\"\" exceptions_to_handle = tuple(EXPECTED_EXCEPTIONS) #",
"import wraps from hdfs_kernel.constants import EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG from hdfs.util import",
"may contain private client information self.send_error(EXPECTED_ERROR_MSG.format(err)) return None else: return",
"self.status = status # == DECORATORS FOR EXCEPTION HANDLING ==",
"self.send_error(EXPECTED_ERROR_MSG.format(err)) return None else: return out return wrapped def wrap_unexpected_exceptions(f,",
"wraps from hdfs_kernel.constants import EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG from hdfs.util import HdfsError",
"EXPECTED_EXCEPTIONS = [HdfsError, SessionManagementException, CommandNotAllowedException, CommandExecuteException, OptionParsingExit, OptionParsingError] def handle_expected_exceptions(f):",
"exceptions. Self can be any object with an \"ipython_display\" attribute.",
"option parse Error class OptionParsingError(RuntimeError): pass class OptionParsingExit(Exception): def __init__(self,",
"{}\\n\\tTraceback:\\n{}\".format(e, traceback.format_exc())) self.send_error(INTERNAL_ERROR_MSG.format(e)) return None if execute_if_error is None else",
"execute_if_error is None else execute_if_error() else: return out return wrapped",
"implementation. @wraps(f) def wrapped(self, *args, **kwargs): try: out = f(self,",
"@wrap_unexpected_exceptions def fn(self, ...): ..etc \"\"\" @wraps(f) def wrapped(self, *args,",
"class OptionParsingError(RuntimeError): pass class OptionParsingExit(Exception): def __init__(self, status, msg): self.msg",
"**kwargs) except Exception as e: self.logger.error(u\"ENCOUNTERED AN INTERNAL ERROR: {}\\n\\tTraceback:\\n{}\".format(e,",
"the Github repository. If there is an error, returns None",
"execute_if_error. Usage: @wrap_unexpected_exceptions def fn(self, ...): ..etc \"\"\" @wraps(f) def",
"# == EXCEPTIONS == class SessionManagementException(Exception): pass class CommandNotAllowedException(Exception): pass",
"msg): self.msg = msg self.status = status # == DECORATORS",
"# is an internal error that suggests something is wrong",
"**kwargs): try: out = f(self, *args, **kwargs) except Exception as",
"OptionParsingError(RuntimeError): pass class OptionParsingExit(Exception): def __init__(self, status, msg): self.msg =",
"#!/usr/bin/env python # -*- coding=utf-8 -*- # # Author: huangnj",
"**kwargs) except exceptions_to_handle as err: # Do not log! as",
"decorator that handles expected exceptions. Self can be any object",
"= f(self, *args, **kwargs) except exceptions_to_handle as err: # Do",
"f and alerts the user about them. Self can be",
"or else returns the output of the function execute_if_error. Usage:",
"error, returns None if execute_if_error is None, or else returns",
"traceback.format_exc())) self.send_error(INTERNAL_ERROR_MSG.format(e)) return None if execute_if_error is None else execute_if_error()",
"is made to the user to file an issue at",
"else returns the output of the function execute_if_error. Usage: @wrap_unexpected_exceptions",
"Author: huangnj # Time: 2019/09/27 import traceback from functools import",
"because DataFrameParseException # is an internal error that suggests something",
"@handle_expected_exceptions def fn(self, ...): etc...\"\"\" exceptions_to_handle = tuple(EXPECTED_EXCEPTIONS) # Notice",
"is wrong with LivyClientLib's implementation. @wraps(f) def wrapped(self, *args, **kwargs):",
"None else: return out return wrapped def wrap_unexpected_exceptions(f, execute_if_error=None): \"\"\"A",
"alerts the user about them. Self can be any object",
"user to file an issue at the Github repository. If",
"@wraps(f) def wrapped(self, *args, **kwargs): try: out = f(self, *args,",
"to file an issue at the Github repository. If there",
"EXCEPTION HANDLING == EXPECTED_EXCEPTIONS = [HdfsError, SessionManagementException, CommandNotAllowedException, CommandExecuteException, OptionParsingExit,",
"SessionManagementException, CommandNotAllowedException, CommandExecuteException, OptionParsingExit, OptionParsingError] def handle_expected_exceptions(f): \"\"\"A decorator that",
"if execute_if_error is None, or else returns the output of",
"private client information self.send_error(EXPECTED_ERROR_MSG.format(err)) return None else: return out return",
"huangnj # Time: 2019/09/27 import traceback from functools import wraps",
"If there is an error, returns None if execute_if_error is",
"any object with a \"logger\" attribute and a \"ipython_display\" attribute.",
"output of the function execute_if_error. Usage: @wrap_unexpected_exceptions def fn(self, ...):",
"class OptionParsingExit(Exception): def __init__(self, status, msg): self.msg = msg self.status",
"NOT handling e.DataFrameParseException here. That's because DataFrameParseException # is an",
"FOR EXCEPTION HANDLING == EXPECTED_EXCEPTIONS = [HdfsError, SessionManagementException, CommandNotAllowedException, CommandExecuteException,",
"CommandExecuteException, OptionParsingExit, OptionParsingError] def handle_expected_exceptions(f): \"\"\"A decorator that handles expected",
"OptionParsingExit, OptionParsingError] def handle_expected_exceptions(f): \"\"\"A decorator that handles expected exceptions.",
"INTERNAL ERROR: {}\\n\\tTraceback:\\n{}\".format(e, traceback.format_exc())) self.send_error(INTERNAL_ERROR_MSG.format(e)) return None if execute_if_error is",
"...): etc...\"\"\" exceptions_to_handle = tuple(EXPECTED_EXCEPTIONS) # Notice that we're NOT",
"Error class OptionParsingError(RuntimeError): pass class OptionParsingExit(Exception): def __init__(self, status, msg):",
"EXCEPTIONS == class SessionManagementException(Exception): pass class CommandNotAllowedException(Exception): pass class CommandExecuteException(Exception):",
"can be any object with an \"ipython_display\" attribute. Usage: @handle_expected_exceptions",
"be any object with an \"ipython_display\" attribute. Usage: @handle_expected_exceptions def",
"fn(self, ...): etc...\"\"\" exceptions_to_handle = tuple(EXPECTED_EXCEPTIONS) # Notice that we're",
"that suggests something is wrong with LivyClientLib's implementation. @wraps(f) def",
"an internal error that suggests something is wrong with LivyClientLib's",
"Self can be any object with a \"logger\" attribute and",
"return out return wrapped def wrap_unexpected_exceptions(f, execute_if_error=None): \"\"\"A decorator that",
"Github repository. If there is an error, returns None if",
"fn(self, ...): ..etc \"\"\" @wraps(f) def wrapped(self, *args, **kwargs): try:",
"# Author: huangnj # Time: 2019/09/27 import traceback from functools",
"as \"unexpected\" exceptions, and a request is made to the",
"status, msg): self.msg = msg self.status = status # ==",
"class CommandNotAllowedException(Exception): pass class CommandExecuteException(Exception): pass # option parse Error",
"import traceback from functools import wraps from hdfs_kernel.constants import EXPECTED_ERROR_MSG,",
"execute_if_error is None, or else returns the output of the",
"from functools import wraps from hdfs_kernel.constants import EXPECTED_ERROR_MSG, INTERNAL_ERROR_MSG from",
"client information self.send_error(EXPECTED_ERROR_MSG.format(err)) return None else: return out return wrapped",
"\"\"\"A decorator that handles expected exceptions. Self can be any",
"user about them. Self can be any object with a",
"DataFrameParseException # is an internal error that suggests something is",
"the user about them. Self can be any object with",
"the function f and alerts the user about them. Self",
"exceptions_to_handle as err: # Do not log! as some messages",
"pass class CommandNotAllowedException(Exception): pass class CommandExecuteException(Exception): pass # option parse",
"wrong with LivyClientLib's implementation. @wraps(f) def wrapped(self, *args, **kwargs): try:",
"SessionManagementException(Exception): pass class CommandNotAllowedException(Exception): pass class CommandExecuteException(Exception): pass # option"
] |
[
"\"\"\" platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_zanata_fedora.platform_slug ) self.assertEqual(platform_engine, 'zanata') platform_engine =",
"import NamedDataStyle from fixture.django_testcase import FixtureTestCase from dashboard.managers.inventory import InventoryManager",
"def test_get_locale_alias(self): \"\"\" Test get_locale_alias \"\"\" locale_alias = self.inventory_manager.get_locale_alias('fr_FR') self.assertEqual(locale_alias,",
"get_transplatform_slug_url \"\"\" slug_url_tuple = self.inventory_manager.get_transplatform_slug_url() self.assertTupleEqual(slug_url_tuple, (('MSRCPUB', 'https://cloud.memsource.com/web'), ('ZNTAFED', 'https://fedora.zanata.org'),",
"platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_zanata_fedora.platform_slug ) self.assertEqual(platform_engine, 'zanata') platform_engine = self.inventory_manager.get_engine_from_slug(",
"'f27-set'], 'ru_RU': ['f27-set'], 'ko_KR': []}) def test_get_translation_platforms(self): \"\"\" Test get_translation_platforms",
"self.inventory_manager.get_locale_lang_tuple() self.assertEqual(len(locale_lang_tuple), 3) locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR', 'ru_RU']) self.assertEqual(len(locale_lang_tuple), 2) self.assertTupleEqual(locale_lang_tuple[0],",
"Test get_relbranch_locales \"\"\" relbranch_locales = self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\") self.assertFalse(relbranch_locales) relbranch_locales = self.inventory_manager.get_relbranch_locales('fedora-27')",
"the License. from mock import patch from fixture import DjangoFixture",
"self.assertEqual(ciplatforms[0].api_url, 'https://cloud.memsource.com/web') self.assertEqual(ciplatforms[0].platform_slug, 'MSRCPUB') def test_get_transplatforms_set(self): \"\"\" Test get_transplatforms_set \"\"\"",
"0) def test_get_engine_from_slug(self): \"\"\" Test get_engine_from_slug \"\"\" platform_engine = self.inventory_manager.get_engine_from_slug(",
"'ru_RU': ['f27-set'], 'ko_KR': []}) def test_get_translation_platforms(self): \"\"\" Test get_translation_platforms \"\"\"",
"self.inventory_manager.get_alias_locale('fr') self.assertEqual(alias_locale, 'fr_FR') alias_locale = self.inventory_manager.get_alias_locale('de_DE') self.assertEqual(alias_locale, 'de_DE') def test_get_locales_set(self):",
"\"\"\" Test get_locales \"\"\" japanese_locale = self.inventory_manager.get_locales(pick_locales=['ja_JP']) self.assertEqual(len(japanese_locale), 1) self.assertEqual(japanese_locale[0].lang_name,",
"'fr') locale_alias = self.inventory_manager.get_locale_alias('de_DE') self.assertEqual(locale_alias, 'de_DE') def test_get_alias_locale(self): \"\"\" Test",
"Test get_all_locales_groups \"\"\" groups_of_all_locales = self.inventory_manager.get_all_locales_groups() self.assertDictEqual(groups_of_all_locales, {'ja_JP': ['custom-set', 'f27-set'],",
"Test get_transplatforms_set \"\"\" active_platforms, inactive_platforms = self.inventory_manager.get_transplatforms_set() self.assertEqual(len(active_platforms), 3) self.assertEqual(len(inactive_platforms),",
"= self.inventory_manager.get_relbranch_locales('fedora-27') self.assertListEqual(relbranch_locales, ['ja_JP', 'fr_FR', 'ru_RU']) def test_get_release_streams(self): \"\"\" Test",
"= self.inventory_manager.get_active_locales_count() self.assertEqual(active_locales, 3) def test_get_locale_alias(self): \"\"\" Test get_locale_alias \"\"\"",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"specific language governing permissions and limitations # under the License.",
"# not use this file except in compliance with the",
"self.inventory_manager.get_translation_platforms(engine='zanata') self.assertEqual(transplatforms[1].api_url, 'https://translate.zanata.org') self.assertEqual(transplatforms[1].platform_slug, 'ZNTAPUB') def test_get_ci_platforms(self): \"\"\" Test get_translation_platforms",
"get_locales_set \"\"\" active_locales, inactive_locales, aliases = \\ self.inventory_manager.get_locales_set() self.assertEqual(len(active_locales), 3)",
"'https://translate.zanata.org') self.assertEqual(transplatforms[1].platform_slug, 'ZNTAPUB') def test_get_ci_platforms(self): \"\"\" Test get_translation_platforms \"\"\" ciplatforms",
"2017 Red Hat, Inc. # All Rights Reserved. # #",
"self.assertEqual(len(lang_sets), 2) self.assertNotIn('lang_set_color', vars(lang_sets[0])) self.assertListEqual(lang_sets[0].locale_ids, ['fr_FR', 'ja_JP']) def test_get_locale_groups(self): \"\"\"",
"'fr_FR', 'ru_RU']) def test_get_release_streams(self): \"\"\" Test get_release_streams \"\"\" relstream_fedora =",
"License. from mock import patch from fixture import DjangoFixture from",
"in compliance with the License. You may obtain # a",
"get_transplatforms_set \"\"\" active_platforms, inactive_platforms = self.inventory_manager.get_transplatforms_set() self.assertEqual(len(active_platforms), 3) self.assertEqual(len(inactive_platforms), 0)",
"self.assertEqual(len(release_streams), 1) self.assertIn(relstream_fedora, release_streams) def test_get_relstream_slug_name(self): \"\"\" Test get_relstream_slug_name \"\"\"",
"self.assertEqual(len(release_streams), 1) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(only_active=True) self.assertEqual(len(release_streams), 1) self.assertIn(relstream_fedora,",
"japanese_locale = self.inventory_manager.get_locales(pick_locales=['ja_JP']) self.assertEqual(len(japanese_locale), 1) self.assertEqual(japanese_locale[0].lang_name, 'Japanese') self.assertEqual(japanese_locale[0].locale_alias, 'ja') self.assertEqual(japanese_locale[0].locale_script,",
"test_get_all_locales_groups(self): \"\"\" Test get_all_locales_groups \"\"\" groups_of_all_locales = self.inventory_manager.get_all_locales_groups() self.assertDictEqual(groups_of_all_locales, {'ja_JP':",
"\"\"\" japanese_locale = self.inventory_manager.get_locales(pick_locales=['ja_JP']) self.assertEqual(len(japanese_locale), 1) self.assertEqual(japanese_locale[0].lang_name, 'Japanese') self.assertEqual(japanese_locale[0].locale_alias, 'ja')",
"You may obtain # a copy of the License at",
"self.inventory_manager.get_engine_from_slug( PlatformData.platform_zanata_fedora.platform_slug ) self.assertEqual(platform_engine, 'zanata') platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_memsource_cloud.platform_slug )",
"get_relstream_slug_name \"\"\" relstream_slug_name_tuple = self.inventory_manager.get_relstream_slug_name() self.assertEqual(len(relstream_slug_name_tuple), 1) self.assertTupleEqual(relstream_slug_name_tuple[0], ('fedora', 'Fedora'))",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"self.assertEqual(locale_alias, 'fr') locale_alias = self.inventory_manager.get_locale_alias('de_DE') self.assertEqual(locale_alias, 'de_DE') def test_get_alias_locale(self): \"\"\"",
"slug_url_tuple = self.inventory_manager.get_transplatform_slug_url() self.assertTupleEqual(slug_url_tuple, (('MSRCPUB', 'https://cloud.memsource.com/web'), ('ZNTAFED', 'https://fedora.zanata.org'), ('ZNTAPUB', 'https://translate.zanata.org')))",
"self.assertEqual(len(relstream_slug_name_tuple), 1) self.assertTupleEqual(relstream_slug_name_tuple[0], ('fedora', 'Fedora')) def test_get_relstream_build_tags(self): \"\"\" Test get_relstream_build_tags",
"self.assertTupleEqual(relstream_slug_name_tuple[0], ('fedora', 'Fedora')) def test_get_relstream_build_tags(self): \"\"\" Test get_relstream_build_tags \"\"\" tags",
"Test get_relstream_slug_name \"\"\" relstream_slug_name_tuple = self.inventory_manager.get_relstream_slug_name() self.assertEqual(len(relstream_slug_name_tuple), 1) self.assertTupleEqual(relstream_slug_name_tuple[0], ('fedora',",
"under the License is distributed on an \"AS IS\" BASIS,",
"class InventoryManagerTest(FixtureTestCase): inventory_manager = InventoryManager() fixture = db_fixture datasets =",
"self.inventory_manager.get_locale_alias('fr_FR') self.assertEqual(locale_alias, 'fr') locale_alias = self.inventory_manager.get_locale_alias('de_DE') self.assertEqual(locale_alias, 'de_DE') def test_get_alias_locale(self):",
"'Peru') def test_get_langsets(self): \"\"\" Test get_langsets \"\"\" lang_sets = self.inventory_manager.get_langsets(",
"\"\"\" Test get_locales_set \"\"\" active_locales, inactive_locales, aliases = \\ self.inventory_manager.get_locales_set()",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"def test_get_alias_locale(self): \"\"\" Test get_alias_locale \"\"\" alias_locale = self.inventory_manager.get_alias_locale('fr') self.assertEqual(alias_locale,",
"def test_get_relbranch_locales(self): \"\"\" Test get_relbranch_locales \"\"\" relbranch_locales = self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\") self.assertFalse(relbranch_locales)",
"self.assertEqual(platform_engine, 'zanata') platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_memsource_cloud.platform_slug ) self.assertEqual(platform_engine, 'memsource') def",
"test_get_locale_lang_tuple(self): \"\"\" Test get_locale_lang_tuple \"\"\" ru_tuple = ('ru_RU', 'Russian') fr_tuple",
"db_fixture datasets = [LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData] def test_get_locales(self):",
"this file except in compliance with the License. You may",
"language governing permissions and limitations # under the License. from",
"InventoryManager() fixture = db_fixture datasets = [LanguageData, LanguageSetData, PlatformData, ProductData,",
"alias_locale = self.inventory_manager.get_alias_locale('fr') self.assertEqual(alias_locale, 'fr_FR') alias_locale = self.inventory_manager.get_alias_locale('de_DE') self.assertEqual(alias_locale, 'de_DE')",
"relstream_fedora = Product.objects.get(product_name='Fedora') relstream_rhel = Product.objects.get(product_name='RHEL') release_streams = self.inventory_manager.get_release_streams() self.assertEqual(len(release_streams),",
"self.inventory_manager.get_locales_set() self.assertEqual(len(active_locales), 3) self.assertEqual(len(inactive_locales), 1) self.assertEqual(len(aliases), 4) def test_get_locale_lang_tuple(self): \"\"\"",
"dashboard.models import Product from dashboard.tests.testdata.db_fixtures import ( LanguageData, LanguageSetData, PlatformData,",
"software # distributed under the License is distributed on an",
"(the \"License\"); you may # not use this file except",
"3) def test_get_locale_alias(self): \"\"\" Test get_locale_alias \"\"\" locale_alias = self.inventory_manager.get_locale_alias('fr_FR')",
"get_all_locales_groups \"\"\" groups_of_all_locales = self.inventory_manager.get_all_locales_groups() self.assertDictEqual(groups_of_all_locales, {'ja_JP': ['custom-set', 'f27-set'], 'fr_FR':",
"from dashboard.models import Product from dashboard.tests.testdata.db_fixtures import ( LanguageData, LanguageSetData,",
"'ru_RU']) self.assertEqual(len(locale_lang_tuple), 2) self.assertTupleEqual(locale_lang_tuple[0], ru_tuple) self.assertTupleEqual(locale_lang_tuple[1], fr_tuple) def test_get_langset(self): \"\"\"",
"self.assertEqual(alias_locale, 'de_DE') def test_get_locales_set(self): \"\"\" Test get_locales_set \"\"\" active_locales, inactive_locales,",
"= self.inventory_manager.get_release_streams() self.assertEqual(len(release_streams), 2) self.assertIn(relstream_fedora, release_streams) self.assertIn(relstream_rhel, release_streams) release_streams =",
"= self.inventory_manager.get_engine_from_slug( PlatformData.platform_memsource_cloud.platform_slug ) self.assertEqual(platform_engine, 'memsource') def test_get_transplatform_slug_url(self): \"\"\" test",
"PlatformData.platform_memsource_cloud.platform_slug ) self.assertEqual(platform_engine, 'memsource') def test_get_transplatform_slug_url(self): \"\"\" test get_transplatform_slug_url \"\"\"",
"{'ja_JP': ['custom-set', 'f27-set']}) def test_get_all_locales_groups(self): \"\"\" Test get_all_locales_groups \"\"\" groups_of_all_locales",
"('ZNTAFED', 'https://fedora.zanata.org'), ('ZNTAPUB', 'https://translate.zanata.org'))) def test_get_relbranch_locales(self): \"\"\" Test get_relbranch_locales \"\"\"",
"Test get_langsets \"\"\" lang_sets = self.inventory_manager.get_langsets( fields=['lang_set_name', 'locale_ids'] ) self.assertEqual(len(lang_sets),",
"test_get_transplatforms_set(self): \"\"\" Test get_transplatforms_set \"\"\" active_platforms, inactive_platforms = self.inventory_manager.get_transplatforms_set() self.assertEqual(len(active_platforms),",
"file except in compliance with the License. You may obtain",
"locale_alias = self.inventory_manager.get_locale_alias('de_DE') self.assertEqual(locale_alias, 'de_DE') def test_get_alias_locale(self): \"\"\" Test get_alias_locale",
"self.assertEqual(len(inactive_platforms), 0) def test_get_engine_from_slug(self): \"\"\" Test get_engine_from_slug \"\"\" platform_engine =",
"\"\"\" alias_locale = self.inventory_manager.get_alias_locale('fr') self.assertEqual(alias_locale, 'fr_FR') alias_locale = self.inventory_manager.get_alias_locale('de_DE') self.assertEqual(alias_locale,",
"\"\"\" locale_groups = self.inventory_manager.get_locale_groups('ja_JP') self.assertDictEqual(locale_groups, {'ja_JP': ['custom-set', 'f27-set']}) def test_get_all_locales_groups(self):",
"locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR', 'ru_RU']) self.assertEqual(len(locale_lang_tuple), 2) self.assertTupleEqual(locale_lang_tuple[0], ru_tuple) self.assertTupleEqual(locale_lang_tuple[1], fr_tuple)",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"the specific language governing permissions and limitations # under the",
"\"\"\" tags = self.inventory_manager.get_relstream_build_tags(stream_slug='fedora') self.assertIsInstance(tags, dict) self.assertDictEqual(tags, {'fedora': ['f28', 'f29',",
"self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(stream_slug='RHEL') self.assertEqual(len(release_streams), 1) self.assertIn(relstream_rhel, release_streams) release_streams",
"under the Apache License, Version 2.0 (the \"License\"); you may",
"under the License. from mock import patch from fixture import",
"\"\"\" lang_sets = self.inventory_manager.get_langsets( fields=['lang_set_name', 'locale_ids'] ) self.assertEqual(len(lang_sets), 2) self.assertNotIn('lang_set_color',",
"= self.inventory_manager.get_locale_groups('ja_JP') self.assertDictEqual(locale_groups, {'ja_JP': ['custom-set', 'f27-set']}) def test_get_all_locales_groups(self): \"\"\" Test",
"ru_tuple) self.assertTupleEqual(locale_lang_tuple[1], fr_tuple) def test_get_langset(self): \"\"\" Test get_get_langset \"\"\" lang_set",
"platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_memsource_cloud.platform_slug ) self.assertEqual(platform_engine, 'memsource') def test_get_transplatform_slug_url(self): \"\"\"",
"\"\"\" relstream_slug_name_tuple = self.inventory_manager.get_relstream_slug_name() self.assertEqual(len(relstream_slug_name_tuple), 1) self.assertTupleEqual(relstream_slug_name_tuple[0], ('fedora', 'Fedora')) def",
"LanguageSetData, PlatformData, ProductData, ReleaseData ) db_fixture = DjangoFixture(style=NamedDataStyle()) class InventoryManagerTest(FixtureTestCase):",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"Test get_locale_alias \"\"\" locale_alias = self.inventory_manager.get_locale_alias('fr_FR') self.assertEqual(locale_alias, 'fr') locale_alias =",
"import patch from fixture import DjangoFixture from fixture.style import NamedDataStyle",
"fr_tuple) def test_get_langset(self): \"\"\" Test get_get_langset \"\"\" lang_set = self.inventory_manager.get_langset(langset_slug='custom-set')",
"Product.objects.get(product_name='RHEL') release_streams = self.inventory_manager.get_release_streams() self.assertEqual(len(release_streams), 2) self.assertIn(relstream_fedora, release_streams) self.assertIn(relstream_rhel, release_streams)",
"\"\"\" Test get_langsets \"\"\" lang_sets = self.inventory_manager.get_langsets( fields=['lang_set_name', 'locale_ids'] )",
"get_locale_alias \"\"\" locale_alias = self.inventory_manager.get_locale_alias('fr_FR') self.assertEqual(locale_alias, 'fr') locale_alias = self.inventory_manager.get_locale_alias('de_DE')",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"self.inventory_manager.get_langset(langset_slug='custom-set') self.assertEqual(lang_set.lang_set_name, 'Custom Set') self.assertEqual(lang_set.lang_set_color, 'Peru') def test_get_langsets(self): \"\"\" Test",
"lang_sets = self.inventory_manager.get_langsets( fields=['lang_set_name', 'locale_ids'] ) self.assertEqual(len(lang_sets), 2) self.assertNotIn('lang_set_color', vars(lang_sets[0]))",
"to in writing, software # distributed under the License is",
"datasets = [LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData] def test_get_locales(self): \"\"\"",
"InventoryManager from dashboard.models import Product from dashboard.tests.testdata.db_fixtures import ( LanguageData,",
"vars(lang_sets[0])) self.assertListEqual(lang_sets[0].locale_ids, ['fr_FR', 'ja_JP']) def test_get_locale_groups(self): \"\"\" Test get_locale_groups \"\"\"",
"self.assertListEqual(relbranch_locales, ['ja_JP', 'fr_FR', 'ru_RU']) def test_get_release_streams(self): \"\"\" Test get_release_streams \"\"\"",
"or agreed to in writing, software # distributed under the",
"def test_get_all_locales_groups(self): \"\"\" Test get_all_locales_groups \"\"\" groups_of_all_locales = self.inventory_manager.get_all_locales_groups() self.assertDictEqual(groups_of_all_locales,",
"required by applicable law or agreed to in writing, software",
"groups_of_all_locales = self.inventory_manager.get_all_locales_groups() self.assertDictEqual(groups_of_all_locales, {'ja_JP': ['custom-set', 'f27-set'], 'fr_FR': ['custom-set', 'f27-set'],",
"self.inventory_manager.get_all_locales_groups() self.assertDictEqual(groups_of_all_locales, {'ja_JP': ['custom-set', 'f27-set'], 'fr_FR': ['custom-set', 'f27-set'], 'ru_RU': ['f27-set'],",
"get_translation_platforms \"\"\" transplatforms = self.inventory_manager.get_translation_platforms(engine='zanata') self.assertEqual(transplatforms[1].api_url, 'https://translate.zanata.org') self.assertEqual(transplatforms[1].platform_slug, 'ZNTAPUB') def",
"or implied. See the # License for the specific language",
"'ZNTAPUB') def test_get_ci_platforms(self): \"\"\" Test get_translation_platforms \"\"\" ciplatforms = self.inventory_manager.get_translation_platforms(ci=True)",
"InventoryManagerTest(FixtureTestCase): inventory_manager = InventoryManager() fixture = db_fixture datasets = [LanguageData,",
"Product from dashboard.tests.testdata.db_fixtures import ( LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData",
"self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(only_active=True) self.assertEqual(len(release_streams), 1) self.assertIn(relstream_fedora, release_streams) def",
"Apache License, Version 2.0 (the \"License\"); you may # not",
"ru_tuple = ('ru_RU', 'Russian') fr_tuple = ('fr_FR', 'French') locale_lang_tuple =",
"import Product from dashboard.tests.testdata.db_fixtures import ( LanguageData, LanguageSetData, PlatformData, ProductData,",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"= DjangoFixture(style=NamedDataStyle()) class InventoryManagerTest(FixtureTestCase): inventory_manager = InventoryManager() fixture = db_fixture",
"distributed under the License is distributed on an \"AS IS\"",
"def test_get_transplatform_slug_url(self): \"\"\" test get_transplatform_slug_url \"\"\" slug_url_tuple = self.inventory_manager.get_transplatform_slug_url() self.assertTupleEqual(slug_url_tuple,",
"dashboard.managers.inventory import InventoryManager from dashboard.models import Product from dashboard.tests.testdata.db_fixtures import",
"\"\"\" active_locales = self.inventory_manager.get_active_locales_count() self.assertEqual(active_locales, 3) def test_get_locale_alias(self): \"\"\" Test",
"self.inventory_manager.get_active_locales_count() self.assertEqual(active_locales, 3) def test_get_locale_alias(self): \"\"\" Test get_locale_alias \"\"\" locale_alias",
"License, Version 2.0 (the \"License\"); you may # not use",
"CONDITIONS OF ANY KIND, either express or implied. See the",
"def test_get_locale_lang_tuple(self): \"\"\" Test get_locale_lang_tuple \"\"\" ru_tuple = ('ru_RU', 'Russian')",
"self.assertEqual(len(active_platforms), 3) self.assertEqual(len(inactive_platforms), 0) def test_get_engine_from_slug(self): \"\"\" Test get_engine_from_slug \"\"\"",
"\"\"\" lang_set = self.inventory_manager.get_langset(langset_slug='custom-set') self.assertEqual(lang_set.lang_set_name, 'Custom Set') self.assertEqual(lang_set.lang_set_color, 'Peru') def",
"= self.inventory_manager.get_translation_platforms(engine='zanata') self.assertEqual(transplatforms[1].api_url, 'https://translate.zanata.org') self.assertEqual(transplatforms[1].platform_slug, 'ZNTAPUB') def test_get_ci_platforms(self): \"\"\" Test",
"not use this file except in compliance with the License.",
"= self.inventory_manager.get_locale_alias('de_DE') self.assertEqual(locale_alias, 'de_DE') def test_get_alias_locale(self): \"\"\" Test get_alias_locale \"\"\"",
"\"\"\" Test get_locale_groups \"\"\" locale_groups = self.inventory_manager.get_locale_groups('ja_JP') self.assertDictEqual(locale_groups, {'ja_JP': ['custom-set',",
"self.inventory_manager.get_release_streams(only_active=True) self.assertEqual(len(release_streams), 1) self.assertIn(relstream_fedora, release_streams) def test_get_relstream_slug_name(self): \"\"\" Test get_relstream_slug_name",
"self.assertListEqual(lang_sets[0].locale_ids, ['fr_FR', 'ja_JP']) def test_get_locale_groups(self): \"\"\" Test get_locale_groups \"\"\" locale_groups",
"writing, software # distributed under the License is distributed on",
"get_relstream_build_tags \"\"\" tags = self.inventory_manager.get_relstream_build_tags(stream_slug='fedora') self.assertIsInstance(tags, dict) self.assertDictEqual(tags, {'fedora': ['f28',",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"= Product.objects.get(product_name='Fedora') relstream_rhel = Product.objects.get(product_name='RHEL') release_streams = self.inventory_manager.get_release_streams() self.assertEqual(len(release_streams), 2)",
"inactive_platforms = self.inventory_manager.get_transplatforms_set() self.assertEqual(len(active_platforms), 3) self.assertEqual(len(inactive_platforms), 0) def test_get_engine_from_slug(self): \"\"\"",
"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",
"self.assertEqual(platform_engine, 'memsource') def test_get_transplatform_slug_url(self): \"\"\" test get_transplatform_slug_url \"\"\" slug_url_tuple =",
"Set') self.assertEqual(lang_set.lang_set_color, 'Peru') def test_get_langsets(self): \"\"\" Test get_langsets \"\"\" lang_sets",
"from mock import patch from fixture import DjangoFixture from fixture.style",
"\"\"\" relbranch_locales = self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\") self.assertFalse(relbranch_locales) relbranch_locales = self.inventory_manager.get_relbranch_locales('fedora-27') self.assertListEqual(relbranch_locales, ['ja_JP',",
"Test get_engine_from_slug \"\"\" platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_zanata_fedora.platform_slug ) self.assertEqual(platform_engine, 'zanata')",
"('fr_FR', 'French') locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple() self.assertEqual(len(locale_lang_tuple), 3) locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR',",
"1) self.assertEqual(japanese_locale[0].lang_name, 'Japanese') self.assertEqual(japanese_locale[0].locale_alias, 'ja') self.assertEqual(japanese_locale[0].locale_script, 'Hani') def test_get_active_locales_count(self): \"\"\"",
"['ja_JP', 'fr_FR', 'ru_RU']) def test_get_release_streams(self): \"\"\" Test get_release_streams \"\"\" relstream_fedora",
"self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR', 'ru_RU']) self.assertEqual(len(locale_lang_tuple), 2) self.assertTupleEqual(locale_lang_tuple[0], ru_tuple) self.assertTupleEqual(locale_lang_tuple[1], fr_tuple) def test_get_langset(self):",
"4) def test_get_locale_lang_tuple(self): \"\"\" Test get_locale_lang_tuple \"\"\" ru_tuple = ('ru_RU',",
"def test_get_langset(self): \"\"\" Test get_get_langset \"\"\" lang_set = self.inventory_manager.get_langset(langset_slug='custom-set') self.assertEqual(lang_set.lang_set_name,",
"PlatformData, ProductData, ReleaseData] def test_get_locales(self): \"\"\" Test get_locales \"\"\" japanese_locale",
"Inc. # All Rights Reserved. # # Licensed under the",
"License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"KIND, either express or implied. See the # License for",
"= self.inventory_manager.get_engine_from_slug( PlatformData.platform_zanata_fedora.platform_slug ) self.assertEqual(platform_engine, 'zanata') platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_memsource_cloud.platform_slug",
"from dashboard.tests.testdata.db_fixtures import ( LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData )",
"\"License\"); you may # not use this file except in",
"self.assertEqual(alias_locale, 'fr_FR') alias_locale = self.inventory_manager.get_alias_locale('de_DE') self.assertEqual(alias_locale, 'de_DE') def test_get_locales_set(self): \"\"\"",
"def test_get_relstream_slug_name(self): \"\"\" Test get_relstream_slug_name \"\"\" relstream_slug_name_tuple = self.inventory_manager.get_relstream_slug_name() self.assertEqual(len(relstream_slug_name_tuple),",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
") self.assertEqual(platform_engine, 'zanata') platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_memsource_cloud.platform_slug ) self.assertEqual(platform_engine, 'memsource')",
"express or implied. See the # License for the specific",
"2) self.assertNotIn('lang_set_color', vars(lang_sets[0])) self.assertListEqual(lang_sets[0].locale_ids, ['fr_FR', 'ja_JP']) def test_get_locale_groups(self): \"\"\" Test",
"locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple() self.assertEqual(len(locale_lang_tuple), 3) locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR', 'ru_RU']) self.assertEqual(len(locale_lang_tuple),",
"test_get_translation_platforms(self): \"\"\" Test get_translation_platforms \"\"\" transplatforms = self.inventory_manager.get_translation_platforms(engine='zanata') self.assertEqual(transplatforms[1].api_url, 'https://translate.zanata.org')",
"the Apache License, Version 2.0 (the \"License\"); you may #",
"= Product.objects.get(product_name='RHEL') release_streams = self.inventory_manager.get_release_streams() self.assertEqual(len(release_streams), 2) self.assertIn(relstream_fedora, release_streams) self.assertIn(relstream_rhel,",
"def test_get_release_streams(self): \"\"\" Test get_release_streams \"\"\" relstream_fedora = Product.objects.get(product_name='Fedora') relstream_rhel",
"3) self.assertEqual(len(inactive_locales), 1) self.assertEqual(len(aliases), 4) def test_get_locale_lang_tuple(self): \"\"\" Test get_locale_lang_tuple",
"['f27-set'], 'ko_KR': []}) def test_get_translation_platforms(self): \"\"\" Test get_translation_platforms \"\"\" transplatforms",
"See the # License for the specific language governing permissions",
"# Copyright 2017 Red Hat, Inc. # All Rights Reserved.",
"'ja_JP']) def test_get_locale_groups(self): \"\"\" Test get_locale_groups \"\"\" locale_groups = self.inventory_manager.get_locale_groups('ja_JP')",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"Test get_active_locales_count \"\"\" active_locales = self.inventory_manager.get_active_locales_count() self.assertEqual(active_locales, 3) def test_get_locale_alias(self):",
"import DjangoFixture from fixture.style import NamedDataStyle from fixture.django_testcase import FixtureTestCase",
"get_active_locales_count \"\"\" active_locales = self.inventory_manager.get_active_locales_count() self.assertEqual(active_locales, 3) def test_get_locale_alias(self): \"\"\"",
"self.inventory_manager.get_locale_groups('ja_JP') self.assertDictEqual(locale_groups, {'ja_JP': ['custom-set', 'f27-set']}) def test_get_all_locales_groups(self): \"\"\" Test get_all_locales_groups",
"test_get_langset(self): \"\"\" Test get_get_langset \"\"\" lang_set = self.inventory_manager.get_langset(langset_slug='custom-set') self.assertEqual(lang_set.lang_set_name, 'Custom",
"\"\"\" test get_transplatform_slug_url \"\"\" slug_url_tuple = self.inventory_manager.get_transplatform_slug_url() self.assertTupleEqual(slug_url_tuple, (('MSRCPUB', 'https://cloud.memsource.com/web'),",
"law or agreed to in writing, software # distributed under",
"self.inventory_manager.get_langsets( fields=['lang_set_name', 'locale_ids'] ) self.assertEqual(len(lang_sets), 2) self.assertNotIn('lang_set_color', vars(lang_sets[0])) self.assertListEqual(lang_sets[0].locale_ids, ['fr_FR',",
"self.assertTupleEqual(slug_url_tuple, (('MSRCPUB', 'https://cloud.memsource.com/web'), ('ZNTAFED', 'https://fedora.zanata.org'), ('ZNTAPUB', 'https://translate.zanata.org'))) def test_get_relbranch_locales(self): \"\"\"",
"self.inventory_manager.get_release_streams() self.assertEqual(len(release_streams), 2) self.assertIn(relstream_fedora, release_streams) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(stream_slug='RHEL')",
"1) self.assertIn(relstream_fedora, release_streams) def test_get_relstream_slug_name(self): \"\"\" Test get_relstream_slug_name \"\"\" relstream_slug_name_tuple",
"implied. See the # License for the specific language governing",
"self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\") self.assertFalse(relbranch_locales) relbranch_locales = self.inventory_manager.get_relbranch_locales('fedora-27') self.assertListEqual(relbranch_locales, ['ja_JP', 'fr_FR', 'ru_RU']) def",
"Test get_locales_set \"\"\" active_locales, inactive_locales, aliases = \\ self.inventory_manager.get_locales_set() self.assertEqual(len(active_locales),",
"'Fedora')) def test_get_relstream_build_tags(self): \"\"\" Test get_relstream_build_tags \"\"\" tags = self.inventory_manager.get_relstream_build_tags(stream_slug='fedora')",
") self.assertEqual(platform_engine, 'memsource') def test_get_transplatform_slug_url(self): \"\"\" test get_transplatform_slug_url \"\"\" slug_url_tuple",
"self.assertFalse(relbranch_locales) relbranch_locales = self.inventory_manager.get_relbranch_locales('fedora-27') self.assertListEqual(relbranch_locales, ['ja_JP', 'fr_FR', 'ru_RU']) def test_get_release_streams(self):",
"\"\"\" Test get_locale_alias \"\"\" locale_alias = self.inventory_manager.get_locale_alias('fr_FR') self.assertEqual(locale_alias, 'fr') locale_alias",
"'Russian') fr_tuple = ('fr_FR', 'French') locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple() self.assertEqual(len(locale_lang_tuple), 3)",
"get_engine_from_slug \"\"\" platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_zanata_fedora.platform_slug ) self.assertEqual(platform_engine, 'zanata') platform_engine",
"self.assertEqual(lang_set.lang_set_color, 'Peru') def test_get_langsets(self): \"\"\" Test get_langsets \"\"\" lang_sets =",
"get_locale_groups \"\"\" locale_groups = self.inventory_manager.get_locale_groups('ja_JP') self.assertDictEqual(locale_groups, {'ja_JP': ['custom-set', 'f27-set']}) def",
"mock import patch from fixture import DjangoFixture from fixture.style import",
"ProductData, ReleaseData] def test_get_locales(self): \"\"\" Test get_locales \"\"\" japanese_locale =",
"def test_get_relstream_build_tags(self): \"\"\" Test get_relstream_build_tags \"\"\" tags = self.inventory_manager.get_relstream_build_tags(stream_slug='fedora') self.assertIsInstance(tags,",
"release_streams) release_streams = self.inventory_manager.get_release_streams(stream_slug='RHEL') self.assertEqual(len(release_streams), 1) self.assertIn(relstream_rhel, release_streams) release_streams =",
"fields=['lang_set_name', 'locale_ids'] ) self.assertEqual(len(lang_sets), 2) self.assertNotIn('lang_set_color', vars(lang_sets[0])) self.assertListEqual(lang_sets[0].locale_ids, ['fr_FR', 'ja_JP'])",
"alias_locale = self.inventory_manager.get_alias_locale('de_DE') self.assertEqual(alias_locale, 'de_DE') def test_get_locales_set(self): \"\"\" Test get_locales_set",
"DjangoFixture from fixture.style import NamedDataStyle from fixture.django_testcase import FixtureTestCase from",
"inactive_locales, aliases = \\ self.inventory_manager.get_locales_set() self.assertEqual(len(active_locales), 3) self.assertEqual(len(inactive_locales), 1) self.assertEqual(len(aliases),",
"{'ja_JP': ['custom-set', 'f27-set'], 'fr_FR': ['custom-set', 'f27-set'], 'ru_RU': ['f27-set'], 'ko_KR': []})",
"['custom-set', 'f27-set']}) def test_get_all_locales_groups(self): \"\"\" Test get_all_locales_groups \"\"\" groups_of_all_locales =",
"\"\"\" Test get_locale_lang_tuple \"\"\" ru_tuple = ('ru_RU', 'Russian') fr_tuple =",
"self.assertEqual(transplatforms[1].platform_slug, 'ZNTAPUB') def test_get_ci_platforms(self): \"\"\" Test get_translation_platforms \"\"\" ciplatforms =",
"self.inventory_manager.get_alias_locale('de_DE') self.assertEqual(alias_locale, 'de_DE') def test_get_locales_set(self): \"\"\" Test get_locales_set \"\"\" active_locales,",
"3) self.assertEqual(len(inactive_platforms), 0) def test_get_engine_from_slug(self): \"\"\" Test get_engine_from_slug \"\"\" platform_engine",
"= self.inventory_manager.get_langsets( fields=['lang_set_name', 'locale_ids'] ) self.assertEqual(len(lang_sets), 2) self.assertNotIn('lang_set_color', vars(lang_sets[0])) self.assertListEqual(lang_sets[0].locale_ids,",
"def test_get_transplatforms_set(self): \"\"\" Test get_transplatforms_set \"\"\" active_platforms, inactive_platforms = self.inventory_manager.get_transplatforms_set()",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"= [LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData] def test_get_locales(self): \"\"\" Test",
"LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData ) db_fixture = DjangoFixture(style=NamedDataStyle()) class",
"(('MSRCPUB', 'https://cloud.memsource.com/web'), ('ZNTAFED', 'https://fedora.zanata.org'), ('ZNTAPUB', 'https://translate.zanata.org'))) def test_get_relbranch_locales(self): \"\"\" Test",
"# # Licensed under the Apache License, Version 2.0 (the",
"release_streams) def test_get_relstream_slug_name(self): \"\"\" Test get_relstream_slug_name \"\"\" relstream_slug_name_tuple = self.inventory_manager.get_relstream_slug_name()",
"from fixture.django_testcase import FixtureTestCase from dashboard.managers.inventory import InventoryManager from dashboard.models",
"'de_DE') def test_get_locales_set(self): \"\"\" Test get_locales_set \"\"\" active_locales, inactive_locales, aliases",
"NamedDataStyle from fixture.django_testcase import FixtureTestCase from dashboard.managers.inventory import InventoryManager from",
"self.assertDictEqual(groups_of_all_locales, {'ja_JP': ['custom-set', 'f27-set'], 'fr_FR': ['custom-set', 'f27-set'], 'ru_RU': ['f27-set'], 'ko_KR':",
"FixtureTestCase from dashboard.managers.inventory import InventoryManager from dashboard.models import Product from",
"('ru_RU', 'Russian') fr_tuple = ('fr_FR', 'French') locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple() self.assertEqual(len(locale_lang_tuple),",
"Red Hat, Inc. # All Rights Reserved. # # Licensed",
"'fr_FR': ['custom-set', 'f27-set'], 'ru_RU': ['f27-set'], 'ko_KR': []}) def test_get_translation_platforms(self): \"\"\"",
"= self.inventory_manager.get_release_streams(stream_slug='RHEL') self.assertEqual(len(release_streams), 1) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(only_active=True) self.assertEqual(len(release_streams),",
"= self.inventory_manager.get_all_locales_groups() self.assertDictEqual(groups_of_all_locales, {'ja_JP': ['custom-set', 'f27-set'], 'fr_FR': ['custom-set', 'f27-set'], 'ru_RU':",
"= self.inventory_manager.get_locale_alias('fr_FR') self.assertEqual(locale_alias, 'fr') locale_alias = self.inventory_manager.get_locale_alias('de_DE') self.assertEqual(locale_alias, 'de_DE') def",
"Product.objects.get(product_name='Fedora') relstream_rhel = Product.objects.get(product_name='RHEL') release_streams = self.inventory_manager.get_release_streams() self.assertEqual(len(release_streams), 2) self.assertIn(relstream_fedora,",
"obtain # a copy of the License at # #",
"self.assertEqual(len(japanese_locale), 1) self.assertEqual(japanese_locale[0].lang_name, 'Japanese') self.assertEqual(japanese_locale[0].locale_alias, 'ja') self.assertEqual(japanese_locale[0].locale_script, 'Hani') def test_get_active_locales_count(self):",
"'f27-set']}) def test_get_all_locales_groups(self): \"\"\" Test get_all_locales_groups \"\"\" groups_of_all_locales = self.inventory_manager.get_all_locales_groups()",
"= self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\") self.assertFalse(relbranch_locales) relbranch_locales = self.inventory_manager.get_relbranch_locales('fedora-27') self.assertListEqual(relbranch_locales, ['ja_JP', 'fr_FR', 'ru_RU'])",
"Version 2.0 (the \"License\"); you may # not use this",
"'ko_KR': []}) def test_get_translation_platforms(self): \"\"\" Test get_translation_platforms \"\"\" transplatforms =",
"self.assertIn(relstream_fedora, release_streams) def test_get_relstream_slug_name(self): \"\"\" Test get_relstream_slug_name \"\"\" relstream_slug_name_tuple =",
"'locale_ids'] ) self.assertEqual(len(lang_sets), 2) self.assertNotIn('lang_set_color', vars(lang_sets[0])) self.assertListEqual(lang_sets[0].locale_ids, ['fr_FR', 'ja_JP']) def",
"def test_get_locale_groups(self): \"\"\" Test get_locale_groups \"\"\" locale_groups = self.inventory_manager.get_locale_groups('ja_JP') self.assertDictEqual(locale_groups,",
"1) self.assertTupleEqual(relstream_slug_name_tuple[0], ('fedora', 'Fedora')) def test_get_relstream_build_tags(self): \"\"\" Test get_relstream_build_tags \"\"\"",
"'ru_RU']) def test_get_release_streams(self): \"\"\" Test get_release_streams \"\"\" relstream_fedora = Product.objects.get(product_name='Fedora')",
"self.assertNotIn('lang_set_color', vars(lang_sets[0])) self.assertListEqual(lang_sets[0].locale_ids, ['fr_FR', 'ja_JP']) def test_get_locale_groups(self): \"\"\" Test get_locale_groups",
"\"\"\" locale_alias = self.inventory_manager.get_locale_alias('fr_FR') self.assertEqual(locale_alias, 'fr') locale_alias = self.inventory_manager.get_locale_alias('de_DE') self.assertEqual(locale_alias,",
"= self.inventory_manager.get_translation_platforms(ci=True) self.assertEqual(ciplatforms[0].api_url, 'https://cloud.memsource.com/web') self.assertEqual(ciplatforms[0].platform_slug, 'MSRCPUB') def test_get_transplatforms_set(self): \"\"\" Test",
"self.assertEqual(len(inactive_locales), 1) self.assertEqual(len(aliases), 4) def test_get_locale_lang_tuple(self): \"\"\" Test get_locale_lang_tuple \"\"\"",
"Test get_translation_platforms \"\"\" ciplatforms = self.inventory_manager.get_translation_platforms(ci=True) self.assertEqual(ciplatforms[0].api_url, 'https://cloud.memsource.com/web') self.assertEqual(ciplatforms[0].platform_slug, 'MSRCPUB')",
"'French') locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple() self.assertEqual(len(locale_lang_tuple), 3) locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR', 'ru_RU'])",
"def test_get_translation_platforms(self): \"\"\" Test get_translation_platforms \"\"\" transplatforms = self.inventory_manager.get_translation_platforms(engine='zanata') self.assertEqual(transplatforms[1].api_url,",
"License for the specific language governing permissions and limitations #",
"self.inventory_manager.get_relstream_slug_name() self.assertEqual(len(relstream_slug_name_tuple), 1) self.assertTupleEqual(relstream_slug_name_tuple[0], ('fedora', 'Fedora')) def test_get_relstream_build_tags(self): \"\"\" Test",
"LanguageSetData, PlatformData, ProductData, ReleaseData] def test_get_locales(self): \"\"\" Test get_locales \"\"\"",
"= self.inventory_manager.get_transplatform_slug_url() self.assertTupleEqual(slug_url_tuple, (('MSRCPUB', 'https://cloud.memsource.com/web'), ('ZNTAFED', 'https://fedora.zanata.org'), ('ZNTAPUB', 'https://translate.zanata.org'))) def",
"= self.inventory_manager.get_langset(langset_slug='custom-set') self.assertEqual(lang_set.lang_set_name, 'Custom Set') self.assertEqual(lang_set.lang_set_color, 'Peru') def test_get_langsets(self): \"\"\"",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"= self.inventory_manager.get_locales(pick_locales=['ja_JP']) self.assertEqual(len(japanese_locale), 1) self.assertEqual(japanese_locale[0].lang_name, 'Japanese') self.assertEqual(japanese_locale[0].locale_alias, 'ja') self.assertEqual(japanese_locale[0].locale_script, 'Hani')",
"self.assertDictEqual(locale_groups, {'ja_JP': ['custom-set', 'f27-set']}) def test_get_all_locales_groups(self): \"\"\" Test get_all_locales_groups \"\"\"",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"test_get_relbranch_locales(self): \"\"\" Test get_relbranch_locales \"\"\" relbranch_locales = self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\") self.assertFalse(relbranch_locales) relbranch_locales",
"from fixture import DjangoFixture from fixture.style import NamedDataStyle from fixture.django_testcase",
"= db_fixture datasets = [LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData] def",
"lang_set = self.inventory_manager.get_langset(langset_slug='custom-set') self.assertEqual(lang_set.lang_set_name, 'Custom Set') self.assertEqual(lang_set.lang_set_color, 'Peru') def test_get_langsets(self):",
"active_platforms, inactive_platforms = self.inventory_manager.get_transplatforms_set() self.assertEqual(len(active_platforms), 3) self.assertEqual(len(inactive_platforms), 0) def test_get_engine_from_slug(self):",
"Rights Reserved. # # Licensed under the Apache License, Version",
"PlatformData, ProductData, ReleaseData ) db_fixture = DjangoFixture(style=NamedDataStyle()) class InventoryManagerTest(FixtureTestCase): inventory_manager",
"governing permissions and limitations # under the License. from mock",
"test_get_ci_platforms(self): \"\"\" Test get_translation_platforms \"\"\" ciplatforms = self.inventory_manager.get_translation_platforms(ci=True) self.assertEqual(ciplatforms[0].api_url, 'https://cloud.memsource.com/web')",
"patch from fixture import DjangoFixture from fixture.style import NamedDataStyle from",
"2) self.assertIn(relstream_fedora, release_streams) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(stream_slug='RHEL') self.assertEqual(len(release_streams), 1)",
"\\ self.inventory_manager.get_locales_set() self.assertEqual(len(active_locales), 3) self.assertEqual(len(inactive_locales), 1) self.assertEqual(len(aliases), 4) def test_get_locale_lang_tuple(self):",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"'zanata') platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_memsource_cloud.platform_slug ) self.assertEqual(platform_engine, 'memsource') def test_get_transplatform_slug_url(self):",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"'de_DE') def test_get_alias_locale(self): \"\"\" Test get_alias_locale \"\"\" alias_locale = self.inventory_manager.get_alias_locale('fr')",
"= ('ru_RU', 'Russian') fr_tuple = ('fr_FR', 'French') locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple()",
"test_get_locales(self): \"\"\" Test get_locales \"\"\" japanese_locale = self.inventory_manager.get_locales(pick_locales=['ja_JP']) self.assertEqual(len(japanese_locale), 1)",
"self.assertEqual(active_locales, 3) def test_get_locale_alias(self): \"\"\" Test get_locale_alias \"\"\" locale_alias =",
"('ZNTAPUB', 'https://translate.zanata.org'))) def test_get_relbranch_locales(self): \"\"\" Test get_relbranch_locales \"\"\" relbranch_locales =",
"ProductData, ReleaseData ) db_fixture = DjangoFixture(style=NamedDataStyle()) class InventoryManagerTest(FixtureTestCase): inventory_manager =",
"= InventoryManager() fixture = db_fixture datasets = [LanguageData, LanguageSetData, PlatformData,",
"test_get_locale_alias(self): \"\"\" Test get_locale_alias \"\"\" locale_alias = self.inventory_manager.get_locale_alias('fr_FR') self.assertEqual(locale_alias, 'fr')",
"self.assertEqual(transplatforms[1].api_url, 'https://translate.zanata.org') self.assertEqual(transplatforms[1].platform_slug, 'ZNTAPUB') def test_get_ci_platforms(self): \"\"\" Test get_translation_platforms \"\"\"",
"fr_tuple = ('fr_FR', 'French') locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple() self.assertEqual(len(locale_lang_tuple), 3) locale_lang_tuple",
"\"\"\" Test get_relstream_build_tags \"\"\" tags = self.inventory_manager.get_relstream_build_tags(stream_slug='fedora') self.assertIsInstance(tags, dict) self.assertDictEqual(tags,",
"limitations # under the License. from mock import patch from",
"compliance with the License. You may obtain # a copy",
") self.assertEqual(len(lang_sets), 2) self.assertNotIn('lang_set_color', vars(lang_sets[0])) self.assertListEqual(lang_sets[0].locale_ids, ['fr_FR', 'ja_JP']) def test_get_locale_groups(self):",
"test_get_relstream_slug_name(self): \"\"\" Test get_relstream_slug_name \"\"\" relstream_slug_name_tuple = self.inventory_manager.get_relstream_slug_name() self.assertEqual(len(relstream_slug_name_tuple), 1)",
"relstream_slug_name_tuple = self.inventory_manager.get_relstream_slug_name() self.assertEqual(len(relstream_slug_name_tuple), 1) self.assertTupleEqual(relstream_slug_name_tuple[0], ('fedora', 'Fedora')) def test_get_relstream_build_tags(self):",
"\"\"\" slug_url_tuple = self.inventory_manager.get_transplatform_slug_url() self.assertTupleEqual(slug_url_tuple, (('MSRCPUB', 'https://cloud.memsource.com/web'), ('ZNTAFED', 'https://fedora.zanata.org'), ('ZNTAPUB',",
"the # License for the specific language governing permissions and",
"Hat, Inc. # All Rights Reserved. # # Licensed under",
"# # Unless required by applicable law or agreed to",
"self.assertEqual(len(release_streams), 2) self.assertIn(relstream_fedora, release_streams) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(stream_slug='RHEL') self.assertEqual(len(release_streams),",
"from fixture.style import NamedDataStyle from fixture.django_testcase import FixtureTestCase from dashboard.managers.inventory",
"\"\"\" ciplatforms = self.inventory_manager.get_translation_platforms(ci=True) self.assertEqual(ciplatforms[0].api_url, 'https://cloud.memsource.com/web') self.assertEqual(ciplatforms[0].platform_slug, 'MSRCPUB') def test_get_transplatforms_set(self):",
"release_streams = self.inventory_manager.get_release_streams(only_active=True) self.assertEqual(len(release_streams), 1) self.assertIn(relstream_fedora, release_streams) def test_get_relstream_slug_name(self): \"\"\"",
"get_alias_locale \"\"\" alias_locale = self.inventory_manager.get_alias_locale('fr') self.assertEqual(alias_locale, 'fr_FR') alias_locale = self.inventory_manager.get_alias_locale('de_DE')",
"test_get_transplatform_slug_url(self): \"\"\" test get_transplatform_slug_url \"\"\" slug_url_tuple = self.inventory_manager.get_transplatform_slug_url() self.assertTupleEqual(slug_url_tuple, (('MSRCPUB',",
"self.assertTupleEqual(locale_lang_tuple[0], ru_tuple) self.assertTupleEqual(locale_lang_tuple[1], fr_tuple) def test_get_langset(self): \"\"\" Test get_get_langset \"\"\"",
"get_locale_lang_tuple \"\"\" ru_tuple = ('ru_RU', 'Russian') fr_tuple = ('fr_FR', 'French')",
"\"\"\" Test get_active_locales_count \"\"\" active_locales = self.inventory_manager.get_active_locales_count() self.assertEqual(active_locales, 3) def",
"'memsource') def test_get_transplatform_slug_url(self): \"\"\" test get_transplatform_slug_url \"\"\" slug_url_tuple = self.inventory_manager.get_transplatform_slug_url()",
"= self.inventory_manager.get_relstream_slug_name() self.assertEqual(len(relstream_slug_name_tuple), 1) self.assertTupleEqual(relstream_slug_name_tuple[0], ('fedora', 'Fedora')) def test_get_relstream_build_tags(self): \"\"\"",
"fixture.django_testcase import FixtureTestCase from dashboard.managers.inventory import InventoryManager from dashboard.models import",
"'https://cloud.memsource.com/web') self.assertEqual(ciplatforms[0].platform_slug, 'MSRCPUB') def test_get_transplatforms_set(self): \"\"\" Test get_transplatforms_set \"\"\" active_platforms,",
"self.assertEqual(locale_alias, 'de_DE') def test_get_alias_locale(self): \"\"\" Test get_alias_locale \"\"\" alias_locale =",
"2.0 (the \"License\"); you may # not use this file",
"get_locales \"\"\" japanese_locale = self.inventory_manager.get_locales(pick_locales=['ja_JP']) self.assertEqual(len(japanese_locale), 1) self.assertEqual(japanese_locale[0].lang_name, 'Japanese') self.assertEqual(japanese_locale[0].locale_alias,",
"self.assertEqual(len(locale_lang_tuple), 3) locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR', 'ru_RU']) self.assertEqual(len(locale_lang_tuple), 2) self.assertTupleEqual(locale_lang_tuple[0], ru_tuple)",
"release_streams = self.inventory_manager.get_release_streams() self.assertEqual(len(release_streams), 2) self.assertIn(relstream_fedora, release_streams) self.assertIn(relstream_rhel, release_streams) release_streams",
"['fr_FR', 'ja_JP']) def test_get_locale_groups(self): \"\"\" Test get_locale_groups \"\"\" locale_groups =",
"\"\"\" Test get_relbranch_locales \"\"\" relbranch_locales = self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\") self.assertFalse(relbranch_locales) relbranch_locales =",
"by applicable law or agreed to in writing, software #",
"self.assertEqual(ciplatforms[0].platform_slug, 'MSRCPUB') def test_get_transplatforms_set(self): \"\"\" Test get_transplatforms_set \"\"\" active_platforms, inactive_platforms",
"# under the License. from mock import patch from fixture",
"get_get_langset \"\"\" lang_set = self.inventory_manager.get_langset(langset_slug='custom-set') self.assertEqual(lang_set.lang_set_name, 'Custom Set') self.assertEqual(lang_set.lang_set_color, 'Peru')",
"['custom-set', 'f27-set'], 'fr_FR': ['custom-set', 'f27-set'], 'ru_RU': ['f27-set'], 'ko_KR': []}) def",
"\"\"\" Test get_all_locales_groups \"\"\" groups_of_all_locales = self.inventory_manager.get_all_locales_groups() self.assertDictEqual(groups_of_all_locales, {'ja_JP': ['custom-set',",
"test_get_engine_from_slug(self): \"\"\" Test get_engine_from_slug \"\"\" platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_zanata_fedora.platform_slug )",
"import InventoryManager from dashboard.models import Product from dashboard.tests.testdata.db_fixtures import (",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"\"\"\" relstream_fedora = Product.objects.get(product_name='Fedora') relstream_rhel = Product.objects.get(product_name='RHEL') release_streams = self.inventory_manager.get_release_streams()",
"3) locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR', 'ru_RU']) self.assertEqual(len(locale_lang_tuple), 2) self.assertTupleEqual(locale_lang_tuple[0], ru_tuple) self.assertTupleEqual(locale_lang_tuple[1],",
"get_langsets \"\"\" lang_sets = self.inventory_manager.get_langsets( fields=['lang_set_name', 'locale_ids'] ) self.assertEqual(len(lang_sets), 2)",
"'ja') self.assertEqual(japanese_locale[0].locale_script, 'Hani') def test_get_active_locales_count(self): \"\"\" Test get_active_locales_count \"\"\" active_locales",
"Test get_get_langset \"\"\" lang_set = self.inventory_manager.get_langset(langset_slug='custom-set') self.assertEqual(lang_set.lang_set_name, 'Custom Set') self.assertEqual(lang_set.lang_set_color,",
"def test_get_locales(self): \"\"\" Test get_locales \"\"\" japanese_locale = self.inventory_manager.get_locales(pick_locales=['ja_JP']) self.assertEqual(len(japanese_locale),",
"db_fixture = DjangoFixture(style=NamedDataStyle()) class InventoryManagerTest(FixtureTestCase): inventory_manager = InventoryManager() fixture =",
"locale_alias = self.inventory_manager.get_locale_alias('fr_FR') self.assertEqual(locale_alias, 'fr') locale_alias = self.inventory_manager.get_locale_alias('de_DE') self.assertEqual(locale_alias, 'de_DE')",
"Test get_locale_groups \"\"\" locale_groups = self.inventory_manager.get_locale_groups('ja_JP') self.assertDictEqual(locale_groups, {'ja_JP': ['custom-set', 'f27-set']})",
"self.inventory_manager.get_locale_alias('de_DE') self.assertEqual(locale_alias, 'de_DE') def test_get_alias_locale(self): \"\"\" Test get_alias_locale \"\"\" alias_locale",
"\"\"\" active_locales, inactive_locales, aliases = \\ self.inventory_manager.get_locales_set() self.assertEqual(len(active_locales), 3) self.assertEqual(len(inactive_locales),",
"\"\"\" Test get_transplatforms_set \"\"\" active_platforms, inactive_platforms = self.inventory_manager.get_transplatforms_set() self.assertEqual(len(active_platforms), 3)",
"self.inventory_manager.get_transplatform_slug_url() self.assertTupleEqual(slug_url_tuple, (('MSRCPUB', 'https://cloud.memsource.com/web'), ('ZNTAFED', 'https://fedora.zanata.org'), ('ZNTAPUB', 'https://translate.zanata.org'))) def test_get_relbranch_locales(self):",
"self.assertEqual(lang_set.lang_set_name, 'Custom Set') self.assertEqual(lang_set.lang_set_color, 'Peru') def test_get_langsets(self): \"\"\" Test get_langsets",
"may obtain # a copy of the License at #",
"# All Rights Reserved. # # Licensed under the Apache",
"'https://fedora.zanata.org'), ('ZNTAPUB', 'https://translate.zanata.org'))) def test_get_relbranch_locales(self): \"\"\" Test get_relbranch_locales \"\"\" relbranch_locales",
"ReleaseData] def test_get_locales(self): \"\"\" Test get_locales \"\"\" japanese_locale = self.inventory_manager.get_locales(pick_locales=['ja_JP'])",
"test_get_relstream_build_tags(self): \"\"\" Test get_relstream_build_tags \"\"\" tags = self.inventory_manager.get_relstream_build_tags(stream_slug='fedora') self.assertIsInstance(tags, dict)",
"Unless required by applicable law or agreed to in writing,",
"\"\"\" transplatforms = self.inventory_manager.get_translation_platforms(engine='zanata') self.assertEqual(transplatforms[1].api_url, 'https://translate.zanata.org') self.assertEqual(transplatforms[1].platform_slug, 'ZNTAPUB') def test_get_ci_platforms(self):",
"1) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(only_active=True) self.assertEqual(len(release_streams), 1) self.assertIn(relstream_fedora, release_streams)",
"self.assertEqual(len(active_locales), 3) self.assertEqual(len(inactive_locales), 1) self.assertEqual(len(aliases), 4) def test_get_locale_lang_tuple(self): \"\"\" Test",
"fixture import DjangoFixture from fixture.style import NamedDataStyle from fixture.django_testcase import",
"inventory_manager = InventoryManager() fixture = db_fixture datasets = [LanguageData, LanguageSetData,",
"( LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData ) db_fixture = DjangoFixture(style=NamedDataStyle())",
"get_relbranch_locales \"\"\" relbranch_locales = self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\") self.assertFalse(relbranch_locales) relbranch_locales = self.inventory_manager.get_relbranch_locales('fedora-27') self.assertListEqual(relbranch_locales,",
"import FixtureTestCase from dashboard.managers.inventory import InventoryManager from dashboard.models import Product",
"= self.inventory_manager.get_alias_locale('fr') self.assertEqual(alias_locale, 'fr_FR') alias_locale = self.inventory_manager.get_alias_locale('de_DE') self.assertEqual(alias_locale, 'de_DE') def",
"DjangoFixture(style=NamedDataStyle()) class InventoryManagerTest(FixtureTestCase): inventory_manager = InventoryManager() fixture = db_fixture datasets",
"self.assertIn(relstream_fedora, release_streams) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(stream_slug='RHEL') self.assertEqual(len(release_streams), 1) self.assertIn(relstream_rhel,",
"applicable law or agreed to in writing, software # distributed",
"self.assertEqual(len(aliases), 4) def test_get_locale_lang_tuple(self): \"\"\" Test get_locale_lang_tuple \"\"\" ru_tuple =",
"test_get_locale_groups(self): \"\"\" Test get_locale_groups \"\"\" locale_groups = self.inventory_manager.get_locale_groups('ja_JP') self.assertDictEqual(locale_groups, {'ja_JP':",
"Test get_relstream_build_tags \"\"\" tags = self.inventory_manager.get_relstream_build_tags(stream_slug='fedora') self.assertIsInstance(tags, dict) self.assertDictEqual(tags, {'fedora':",
"\"\"\" Test get_translation_platforms \"\"\" ciplatforms = self.inventory_manager.get_translation_platforms(ci=True) self.assertEqual(ciplatforms[0].api_url, 'https://cloud.memsource.com/web') self.assertEqual(ciplatforms[0].platform_slug,",
"OF ANY KIND, either express or implied. See the #",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"in writing, software # distributed under the License is distributed",
"transplatforms = self.inventory_manager.get_translation_platforms(engine='zanata') self.assertEqual(transplatforms[1].api_url, 'https://translate.zanata.org') self.assertEqual(transplatforms[1].platform_slug, 'ZNTAPUB') def test_get_ci_platforms(self): \"\"\"",
"release_streams) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(stream_slug='RHEL') self.assertEqual(len(release_streams), 1) self.assertIn(relstream_rhel, release_streams)",
"release_streams = self.inventory_manager.get_release_streams(stream_slug='RHEL') self.assertEqual(len(release_streams), 1) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(only_active=True)",
"('fedora', 'Fedora')) def test_get_relstream_build_tags(self): \"\"\" Test get_relstream_build_tags \"\"\" tags =",
"'f27-set'], 'fr_FR': ['custom-set', 'f27-set'], 'ru_RU': ['f27-set'], 'ko_KR': []}) def test_get_translation_platforms(self):",
"def test_get_ci_platforms(self): \"\"\" Test get_translation_platforms \"\"\" ciplatforms = self.inventory_manager.get_translation_platforms(ci=True) self.assertEqual(ciplatforms[0].api_url,",
"'https://translate.zanata.org'))) def test_get_relbranch_locales(self): \"\"\" Test get_relbranch_locales \"\"\" relbranch_locales = self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\")",
"tags = self.inventory_manager.get_relstream_build_tags(stream_slug='fedora') self.assertIsInstance(tags, dict) self.assertDictEqual(tags, {'fedora': ['f28', 'f29', 'rawhide']})",
"self.assertEqual(japanese_locale[0].locale_alias, 'ja') self.assertEqual(japanese_locale[0].locale_script, 'Hani') def test_get_active_locales_count(self): \"\"\" Test get_active_locales_count \"\"\"",
"= self.inventory_manager.get_alias_locale('de_DE') self.assertEqual(alias_locale, 'de_DE') def test_get_locales_set(self): \"\"\" Test get_locales_set \"\"\"",
"\"\"\" Test get_relstream_slug_name \"\"\" relstream_slug_name_tuple = self.inventory_manager.get_relstream_slug_name() self.assertEqual(len(relstream_slug_name_tuple), 1) self.assertTupleEqual(relstream_slug_name_tuple[0],",
"self.assertEqual(len(locale_lang_tuple), 2) self.assertTupleEqual(locale_lang_tuple[0], ru_tuple) self.assertTupleEqual(locale_lang_tuple[1], fr_tuple) def test_get_langset(self): \"\"\" Test",
"= self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR', 'ru_RU']) self.assertEqual(len(locale_lang_tuple), 2) self.assertTupleEqual(locale_lang_tuple[0], ru_tuple) self.assertTupleEqual(locale_lang_tuple[1], fr_tuple) def",
"from dashboard.managers.inventory import InventoryManager from dashboard.models import Product from dashboard.tests.testdata.db_fixtures",
"2) self.assertTupleEqual(locale_lang_tuple[0], ru_tuple) self.assertTupleEqual(locale_lang_tuple[1], fr_tuple) def test_get_langset(self): \"\"\" Test get_get_langset",
"import ( LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData ) db_fixture =",
"'https://cloud.memsource.com/web'), ('ZNTAFED', 'https://fedora.zanata.org'), ('ZNTAPUB', 'https://translate.zanata.org'))) def test_get_relbranch_locales(self): \"\"\" Test get_relbranch_locales",
"get_translation_platforms \"\"\" ciplatforms = self.inventory_manager.get_translation_platforms(ci=True) self.assertEqual(ciplatforms[0].api_url, 'https://cloud.memsource.com/web') self.assertEqual(ciplatforms[0].platform_slug, 'MSRCPUB') def",
"test_get_alias_locale(self): \"\"\" Test get_alias_locale \"\"\" alias_locale = self.inventory_manager.get_alias_locale('fr') self.assertEqual(alias_locale, 'fr_FR')",
"either express or implied. See the # License for the",
"def test_get_langsets(self): \"\"\" Test get_langsets \"\"\" lang_sets = self.inventory_manager.get_langsets( fields=['lang_set_name',",
"['custom-set', 'f27-set'], 'ru_RU': ['f27-set'], 'ko_KR': []}) def test_get_translation_platforms(self): \"\"\" Test",
"def test_get_locales_set(self): \"\"\" Test get_locales_set \"\"\" active_locales, inactive_locales, aliases =",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"dashboard.tests.testdata.db_fixtures import ( LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData ) db_fixture",
"may # not use this file except in compliance with",
"test_get_release_streams(self): \"\"\" Test get_release_streams \"\"\" relstream_fedora = Product.objects.get(product_name='Fedora') relstream_rhel =",
"# License for the specific language governing permissions and limitations",
"with the License. You may obtain # a copy of",
"fixture.style import NamedDataStyle from fixture.django_testcase import FixtureTestCase from dashboard.managers.inventory import",
"\"\"\" Test get_translation_platforms \"\"\" transplatforms = self.inventory_manager.get_translation_platforms(engine='zanata') self.assertEqual(transplatforms[1].api_url, 'https://translate.zanata.org') self.assertEqual(transplatforms[1].platform_slug,",
"you may # not use this file except in compliance",
"PlatformData.platform_zanata_fedora.platform_slug ) self.assertEqual(platform_engine, 'zanata') platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_memsource_cloud.platform_slug ) self.assertEqual(platform_engine,",
"aliases = \\ self.inventory_manager.get_locales_set() self.assertEqual(len(active_locales), 3) self.assertEqual(len(inactive_locales), 1) self.assertEqual(len(aliases), 4)",
"\"\"\" groups_of_all_locales = self.inventory_manager.get_all_locales_groups() self.assertDictEqual(groups_of_all_locales, {'ja_JP': ['custom-set', 'f27-set'], 'fr_FR': ['custom-set',",
"self.inventory_manager.get_engine_from_slug( PlatformData.platform_memsource_cloud.platform_slug ) self.assertEqual(platform_engine, 'memsource') def test_get_transplatform_slug_url(self): \"\"\" test get_transplatform_slug_url",
"self.assertTupleEqual(locale_lang_tuple[1], fr_tuple) def test_get_langset(self): \"\"\" Test get_get_langset \"\"\" lang_set =",
"test_get_locales_set(self): \"\"\" Test get_locales_set \"\"\" active_locales, inactive_locales, aliases = \\",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"\"\"\" active_platforms, inactive_platforms = self.inventory_manager.get_transplatforms_set() self.assertEqual(len(active_platforms), 3) self.assertEqual(len(inactive_platforms), 0) def",
"self.inventory_manager.get_relbranch_locales('fedora-27') self.assertListEqual(relbranch_locales, ['ja_JP', 'fr_FR', 'ru_RU']) def test_get_release_streams(self): \"\"\" Test get_release_streams",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"\"\"\" Test get_alias_locale \"\"\" alias_locale = self.inventory_manager.get_alias_locale('fr') self.assertEqual(alias_locale, 'fr_FR') alias_locale",
"relbranch_locales = self.inventory_manager.get_relbranch_locales(\"nonexisting-relbranch\") self.assertFalse(relbranch_locales) relbranch_locales = self.inventory_manager.get_relbranch_locales('fedora-27') self.assertListEqual(relbranch_locales, ['ja_JP', 'fr_FR',",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"= ('fr_FR', 'French') locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple() self.assertEqual(len(locale_lang_tuple), 3) locale_lang_tuple =",
"'MSRCPUB') def test_get_transplatforms_set(self): \"\"\" Test get_transplatforms_set \"\"\" active_platforms, inactive_platforms =",
"release_streams) release_streams = self.inventory_manager.get_release_streams(only_active=True) self.assertEqual(len(release_streams), 1) self.assertIn(relstream_fedora, release_streams) def test_get_relstream_slug_name(self):",
"'Hani') def test_get_active_locales_count(self): \"\"\" Test get_active_locales_count \"\"\" active_locales = self.inventory_manager.get_active_locales_count()",
"self.assertEqual(japanese_locale[0].lang_name, 'Japanese') self.assertEqual(japanese_locale[0].locale_alias, 'ja') self.assertEqual(japanese_locale[0].locale_script, 'Hani') def test_get_active_locales_count(self): \"\"\" Test",
"Test get_translation_platforms \"\"\" transplatforms = self.inventory_manager.get_translation_platforms(engine='zanata') self.assertEqual(transplatforms[1].api_url, 'https://translate.zanata.org') self.assertEqual(transplatforms[1].platform_slug, 'ZNTAPUB')",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"ciplatforms = self.inventory_manager.get_translation_platforms(ci=True) self.assertEqual(ciplatforms[0].api_url, 'https://cloud.memsource.com/web') self.assertEqual(ciplatforms[0].platform_slug, 'MSRCPUB') def test_get_transplatforms_set(self): \"\"\"",
"self.inventory_manager.get_translation_platforms(ci=True) self.assertEqual(ciplatforms[0].api_url, 'https://cloud.memsource.com/web') self.assertEqual(ciplatforms[0].platform_slug, 'MSRCPUB') def test_get_transplatforms_set(self): \"\"\" Test get_transplatforms_set",
"'Japanese') self.assertEqual(japanese_locale[0].locale_alias, 'ja') self.assertEqual(japanese_locale[0].locale_script, 'Hani') def test_get_active_locales_count(self): \"\"\" Test get_active_locales_count",
"for the specific language governing permissions and limitations # under",
"test_get_active_locales_count(self): \"\"\" Test get_active_locales_count \"\"\" active_locales = self.inventory_manager.get_active_locales_count() self.assertEqual(active_locales, 3)",
"1) self.assertEqual(len(aliases), 4) def test_get_locale_lang_tuple(self): \"\"\" Test get_locale_lang_tuple \"\"\" ru_tuple",
"locale_groups = self.inventory_manager.get_locale_groups('ja_JP') self.assertDictEqual(locale_groups, {'ja_JP': ['custom-set', 'f27-set']}) def test_get_all_locales_groups(self): \"\"\"",
"Test get_locale_lang_tuple \"\"\" ru_tuple = ('ru_RU', 'Russian') fr_tuple = ('fr_FR',",
"and limitations # under the License. from mock import patch",
"Test get_alias_locale \"\"\" alias_locale = self.inventory_manager.get_alias_locale('fr') self.assertEqual(alias_locale, 'fr_FR') alias_locale =",
"except in compliance with the License. You may obtain #",
"self.assertEqual(japanese_locale[0].locale_script, 'Hani') def test_get_active_locales_count(self): \"\"\" Test get_active_locales_count \"\"\" active_locales =",
"active_locales = self.inventory_manager.get_active_locales_count() self.assertEqual(active_locales, 3) def test_get_locale_alias(self): \"\"\" Test get_locale_alias",
"\"\"\" Test get_release_streams \"\"\" relstream_fedora = Product.objects.get(product_name='Fedora') relstream_rhel = Product.objects.get(product_name='RHEL')",
"active_locales, inactive_locales, aliases = \\ self.inventory_manager.get_locales_set() self.assertEqual(len(active_locales), 3) self.assertEqual(len(inactive_locales), 1)",
"def test_get_engine_from_slug(self): \"\"\" Test get_engine_from_slug \"\"\" platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_zanata_fedora.platform_slug",
") db_fixture = DjangoFixture(style=NamedDataStyle()) class InventoryManagerTest(FixtureTestCase): inventory_manager = InventoryManager() fixture",
"License. You may obtain # a copy of the License",
"\"\"\" ru_tuple = ('ru_RU', 'Russian') fr_tuple = ('fr_FR', 'French') locale_lang_tuple",
"relstream_rhel = Product.objects.get(product_name='RHEL') release_streams = self.inventory_manager.get_release_streams() self.assertEqual(len(release_streams), 2) self.assertIn(relstream_fedora, release_streams)",
"Copyright 2017 Red Hat, Inc. # All Rights Reserved. #",
"ANY KIND, either express or implied. See the # License",
"# distributed under the License is distributed on an \"AS",
"fixture = db_fixture datasets = [LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData]",
"= self.inventory_manager.get_locale_lang_tuple() self.assertEqual(len(locale_lang_tuple), 3) locale_lang_tuple = self.inventory_manager.get_locale_lang_tuple(locales=['fr_FR', 'ru_RU']) self.assertEqual(len(locale_lang_tuple), 2)",
"relbranch_locales = self.inventory_manager.get_relbranch_locales('fedora-27') self.assertListEqual(relbranch_locales, ['ja_JP', 'fr_FR', 'ru_RU']) def test_get_release_streams(self): \"\"\"",
"# Unless required by applicable law or agreed to in",
"self.inventory_manager.get_locales(pick_locales=['ja_JP']) self.assertEqual(len(japanese_locale), 1) self.assertEqual(japanese_locale[0].lang_name, 'Japanese') self.assertEqual(japanese_locale[0].locale_alias, 'ja') self.assertEqual(japanese_locale[0].locale_script, 'Hani') def",
"ReleaseData ) db_fixture = DjangoFixture(style=NamedDataStyle()) class InventoryManagerTest(FixtureTestCase): inventory_manager = InventoryManager()",
"= \\ self.inventory_manager.get_locales_set() self.assertEqual(len(active_locales), 3) self.assertEqual(len(inactive_locales), 1) self.assertEqual(len(aliases), 4) def",
"def test_get_active_locales_count(self): \"\"\" Test get_active_locales_count \"\"\" active_locales = self.inventory_manager.get_active_locales_count() self.assertEqual(active_locales,",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"\"\"\" Test get_engine_from_slug \"\"\" platform_engine = self.inventory_manager.get_engine_from_slug( PlatformData.platform_zanata_fedora.platform_slug ) self.assertEqual(platform_engine,",
"permissions and limitations # under the License. from mock import",
"[]}) def test_get_translation_platforms(self): \"\"\" Test get_translation_platforms \"\"\" transplatforms = self.inventory_manager.get_translation_platforms(engine='zanata')",
"[LanguageData, LanguageSetData, PlatformData, ProductData, ReleaseData] def test_get_locales(self): \"\"\" Test get_locales",
"Test get_release_streams \"\"\" relstream_fedora = Product.objects.get(product_name='Fedora') relstream_rhel = Product.objects.get(product_name='RHEL') release_streams",
"\"\"\" Test get_get_langset \"\"\" lang_set = self.inventory_manager.get_langset(langset_slug='custom-set') self.assertEqual(lang_set.lang_set_name, 'Custom Set')",
"self.inventory_manager.get_transplatforms_set() self.assertEqual(len(active_platforms), 3) self.assertEqual(len(inactive_platforms), 0) def test_get_engine_from_slug(self): \"\"\" Test get_engine_from_slug",
"get_release_streams \"\"\" relstream_fedora = Product.objects.get(product_name='Fedora') relstream_rhel = Product.objects.get(product_name='RHEL') release_streams =",
"= self.inventory_manager.get_release_streams(only_active=True) self.assertEqual(len(release_streams), 1) self.assertIn(relstream_fedora, release_streams) def test_get_relstream_slug_name(self): \"\"\" Test",
"= self.inventory_manager.get_transplatforms_set() self.assertEqual(len(active_platforms), 3) self.assertEqual(len(inactive_platforms), 0) def test_get_engine_from_slug(self): \"\"\" Test",
"test get_transplatform_slug_url \"\"\" slug_url_tuple = self.inventory_manager.get_transplatform_slug_url() self.assertTupleEqual(slug_url_tuple, (('MSRCPUB', 'https://cloud.memsource.com/web'), ('ZNTAFED',",
"Test get_locales \"\"\" japanese_locale = self.inventory_manager.get_locales(pick_locales=['ja_JP']) self.assertEqual(len(japanese_locale), 1) self.assertEqual(japanese_locale[0].lang_name, 'Japanese')",
"'fr_FR') alias_locale = self.inventory_manager.get_alias_locale('de_DE') self.assertEqual(alias_locale, 'de_DE') def test_get_locales_set(self): \"\"\" Test",
"test_get_langsets(self): \"\"\" Test get_langsets \"\"\" lang_sets = self.inventory_manager.get_langsets( fields=['lang_set_name', 'locale_ids']",
"self.inventory_manager.get_release_streams(stream_slug='RHEL') self.assertEqual(len(release_streams), 1) self.assertIn(relstream_rhel, release_streams) release_streams = self.inventory_manager.get_release_streams(only_active=True) self.assertEqual(len(release_streams), 1)",
"'Custom Set') self.assertEqual(lang_set.lang_set_color, 'Peru') def test_get_langsets(self): \"\"\" Test get_langsets \"\"\""
] |
[
"code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def GetWorkflow(self, request, context): try: return self._server.get_workflow(request) except",
"info forked_from = '' if workflow.forked_from: forked_from = Workflow.query.get(workflow.forked_from).name return",
"2.0 (the \"License\"); # you may not use this file",
"e: return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e:",
"False self._server = None self._app = None def start(self, app):",
"return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('UpdateWorkflowState",
"import threading from concurrent import futures import grpc from fedlearner_webconsole.proto",
"in project_config.participants: if party.domain_name == auth_info.source_domain: source_party = party if",
"!= auth_info.target_domain: raise UnauthorizedException('Invalid domain') source_party = None for party",
"logging.debug('auth_info: %s', auth_info) project = Project.query.filter_by( name=auth_info.project_name).first() if project is",
"status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), config=config, jobs=jobs, state=workflow.state.value, target_state=workflow.target_state.value, transaction_state=workflow.transaction_state.value, forkable=workflow.forkable, forked_from=forked_from, reuse_job_names=workflow.get_reuse_job_names(),",
"= request.workflow_name state = WorkflowState(request.state) target_state = WorkflowState(request.target_state) transaction_state =",
"msg=repr(e))) class RpcServer(object): def __init__(self): self._lock = threading.Lock() self._started =",
"jobs = [service_pb2.JobDetail( name=job.name, state=job.get_state_for_front()) for job in workflow.get_jobs()] #",
"db from fedlearner_webconsole.project.models import Project from fedlearner_webconsole.workflow.models import ( Workflow,",
"i in var_list: workflow.variables.append(i) for job_def in workflow.job_definitions: var_list =",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"verification # if project_config.token != auth_info.auth_token: # raise UnauthorizedException('Invalid token')",
"server error: %s', repr(e)) return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) class",
"peer-readable and peer-writable variables if workflow is None: return var_list",
"self._started, \"Already started\" self._app = app listen_port = app.config.get('GRPC_LISTEN_PORT', 1999)",
"WorkflowState(request.state) target_state = WorkflowState(request.target_state) transaction_state = TransactionState(request.transaction_state) workflow = Workflow.query.filter_by(",
"workflow.ClearField('variables') for i in var_list: workflow.variables.append(i) for job_def in workflow.job_definitions:",
"= WorkflowState(request.state) target_state = WorkflowState(request.target_state) transaction_state = TransactionState(request.transaction_state) workflow =",
"as e: return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as",
"UnauthorizedException as e: return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception",
"TODO: fix token verification # if project_config.token != auth_info.auth_token: #",
"status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def GetWorkflow(self, request, context): try: return self._server.get_workflow(request)",
"use this file except in compliance with the License. #",
"e: logging.error('GetWorkflow rpc server error: %s', repr(e)) return service_pb2.GetWorkflowResponse( status=common_pb2.Status(",
"msg=repr(e))) def GetWorkflow(self, request, context): try: return self._server.get_workflow(request) except UnauthorizedException",
"def start(self, app): assert not self._started, \"Already started\" self._app =",
"[service_pb2.JobDetail( name=job.name, state=job.get_state_for_front()) for job in workflow.get_jobs()] # fork info",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"db.session.commit() return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), transaction_state=workflow.transaction_state.value) def _filter_workflow(self, workflow, modes):",
"self._app = None def start(self, app): assert not self._started, \"Already",
"in modes] job_def.ClearField('variables') for i in var_list: job_def.variables.append(i) def get_workflow(self,",
"License. # You may obtain a copy of the License",
"if project_config.domain_name != auth_info.target_domain: raise UnauthorizedException('Invalid domain') source_party = None",
"except UnauthorizedException as e: return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except",
"auth_info.target_domain: raise UnauthorizedException('Invalid domain') source_party = None for party in",
"under the License is distributed on an \"AS IS\" BASIS,",
"# raise UnauthorizedException('Invalid token') if project_config.domain_name != auth_info.target_domain: raise UnauthorizedException('Invalid",
"License for the specific language governing permissions and # limitations",
"UnauthorizedException('Invalid domain') return project, source_party def check_connection(self, request): with self._app.app_context():",
"job_def in workflow.job_definitions: var_list = [ i for i in",
"app): assert not self._started, \"Already started\" self._app = app listen_port",
"is None: raise UnauthorizedException('Invalid domain') return project, source_party def check_connection(self,",
"job in workflow.get_jobs()] # fork info forked_from = '' if",
"rpc server error: %s', repr(e)) return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e)))",
"return with self._lock: self._server.stop(None).wait() del self._server self._started = False def",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"error: %s', repr(e)) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def UpdateWorkflowState(self,",
"update_workflow_state from %s: %s', party.domain_name, request) name = request.workflow_name state",
"assert state == WorkflowState.NEW assert target_state == WorkflowState.READY workflow =",
"2020 The FedLearner Authors. All Rights Reserved. # # Licensed",
"= WorkflowState(request.target_state) transaction_state = TransactionState(request.transaction_state) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first()",
"= workflow.get_config() self._filter_workflow( config, [ common_pb2.Variable.PEER_READABLE, common_pb2.Variable.PEER_WRITABLE ]) # job",
"request) name = request.workflow_name state = WorkflowState(request.state) target_state = WorkflowState(request.target_state)",
"and peer-writable variables if workflow is None: return var_list =",
"self._started = True def stop(self): if not self._started: return with",
"return service_pb2.GetWorkflowResponse( name=request.workflow_name, status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), config=config, jobs=jobs, state=workflow.state.value, target_state=workflow.target_state.value, transaction_state=workflow.transaction_state.value,",
"utf-8 # pylint: disable=broad-except, cyclic-import import logging import threading from",
"Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() if workflow is None: assert state ==",
"service_pb2_grpc, common_pb2 ) from fedlearner_webconsole.db import db from fedlearner_webconsole.project.models import",
"= False self._server = None self._app = None def start(self,",
"modes] job_def.ClearField('variables') for i in var_list: job_def.variables.append(i) def get_workflow(self, request):",
"assert target_state == WorkflowState.READY workflow = Workflow( name=name, project_id=project.id, state=state,",
"for i in workflow.variables if i.access_mode in modes] workflow.ClearField('variables') for",
"in compliance with the License. # You may obtain a",
"[ i for i in workflow.variables if i.access_mode in modes]",
"as e: return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as",
"software # distributed under the License is distributed on an",
"status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('GetWorkflow rpc server",
"transaction_state=transaction_state) db.session.add(workflow) db.session.commit() db.session.refresh(workflow) workflow.update_state( state, target_state, transaction_state) db.session.commit() return",
"service_pb2, service_pb2_grpc, common_pb2 ) from fedlearner_webconsole.db import db from fedlearner_webconsole.project.models",
"None def start(self, app): assert not self._started, \"Already started\" self._app",
"for i in var_list: job_def.variables.append(i) def get_workflow(self, request): with self._app.app_context():",
"request, context): try: return self._server.update_workflow_state(request) except UnauthorizedException as e: return",
"source_party def check_connection(self, request): with self._app.app_context(): _, party = self.check_auth_info(request.auth_info)",
"state=workflow.state.value, target_state=workflow.target_state.value, transaction_state=workflow.transaction_state.value, forkable=workflow.forkable, forked_from=forked_from, reuse_job_names=workflow.get_reuse_job_names(), peer_reuse_job_names=workflow.get_peer_reuse_job_names(), fork_proposal_config=workflow.get_fork_proposal_config() ) rpc_server",
"TransactionState ) from fedlearner_webconsole.exceptions import ( UnauthorizedException ) class RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer):",
"self._started = False def check_auth_info(self, auth_info): logging.debug('auth_info: %s', auth_info) project",
"is None: return var_list = [ i for i in",
"self._server.update_workflow_state(request) except UnauthorizedException as e: return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e)))",
"in var_list: workflow.variables.append(i) for job_def in workflow.job_definitions: var_list = [",
"check_connection(self, request): with self._app.app_context(): _, party = self.check_auth_info(request.auth_info) logging.debug( 'received",
"name=auth_info.project_name).first() if project is None: raise UnauthorizedException('Invalid project') project_config =",
"= [ i for i in workflow.variables if i.access_mode in",
"e: logging.error('UpdateWorkflowState rpc server error: %s', repr(e)) return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status(",
"= Project.query.filter_by( name=auth_info.project_name).first() if project is None: raise UnauthorizedException('Invalid project')",
"%s', party.domain_name, request) name = request.workflow_name state = WorkflowState(request.state) target_state",
"fedlearner_webconsole.workflow.models import ( Workflow, WorkflowState, TransactionState ) from fedlearner_webconsole.exceptions import",
"project_config.token != auth_info.auth_token: # raise UnauthorizedException('Invalid token') if project_config.domain_name !=",
"disable=broad-except, cyclic-import import logging import threading from concurrent import futures",
"None self._app = None def start(self, app): assert not self._started,",
"e: return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e:",
"service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('UpdateWorkflowState rpc",
"config = workflow.get_config() self._filter_workflow( config, [ common_pb2.Variable.PEER_READABLE, common_pb2.Variable.PEER_WRITABLE ]) #",
"from fedlearner_webconsole.project.models import Project from fedlearner_webconsole.workflow.models import ( Workflow, WorkflowState,",
"service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('CheckConnection rpc",
"None: return var_list = [ i for i in workflow.variables",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS)) def update_workflow_state(self, request): with self._app.app_context(): project, party =",
"service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), transaction_state=workflow.transaction_state.value) def _filter_workflow(self, workflow, modes): # filter",
"return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def GetWorkflow(self, request, context): try:",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"project_id=project.id).first() assert workflow is not None config = workflow.get_config() self._filter_workflow(",
"fedlearner_webconsole.proto import ( service_pb2, service_pb2_grpc, common_pb2 ) from fedlearner_webconsole.db import",
"from fedlearner_webconsole.db import db from fedlearner_webconsole.project.models import Project from fedlearner_webconsole.workflow.models",
"UnauthorizedException('Invalid token') if project_config.domain_name != auth_info.target_domain: raise UnauthorizedException('Invalid domain') source_party",
"name = request.workflow_name state = WorkflowState(request.state) target_state = WorkflowState(request.target_state) transaction_state",
"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",
"[ i for i in job_def.variables if i.access_mode in modes]",
"raise UnauthorizedException('Invalid domain') source_party = None for party in project_config.participants:",
"project, party = self.check_auth_info(request.auth_info) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() assert",
"try: return self._server.check_connection(request) except UnauthorizedException as e: return service_pb2.CheckConnectionResponse( status=common_pb2.Status(",
"to in writing, software # distributed under the License is",
"self._lock = threading.Lock() self._started = False self._server = None self._app",
"# See the License for the specific language governing permissions",
"and # limitations under the License. # coding: utf-8 #",
"in modes] workflow.ClearField('variables') for i in var_list: workflow.variables.append(i) for job_def",
"def __init__(self): self._lock = threading.Lock() self._started = False self._server =",
"= self.check_auth_info(request.auth_info) logging.debug( 'received update_workflow_state from %s: %s', party.domain_name, request)",
"project_id=project.id).first() if workflow is None: assert state == WorkflowState.NEW assert",
"language governing permissions and # limitations under the License. #",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"target_state, transaction_state) db.session.commit() return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), transaction_state=workflow.transaction_state.value) def _filter_workflow(self,",
"state == WorkflowState.NEW assert target_state == WorkflowState.READY workflow = Workflow(",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"if not self._started: return with self._lock: self._server.stop(None).wait() del self._server self._started",
"msg=repr(e))) except Exception as e: logging.error('GetWorkflow rpc server error: %s',",
"with the License. # You may obtain a copy of",
"futures.ThreadPoolExecutor(max_workers=10)) service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server( RPCServerServicer(self), self._server) self._server.add_insecure_port('[::]:%d' % listen_port) self._server.start() self._started =",
"UnauthorizedException as e: return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception",
"= None for party in project_config.participants: if party.domain_name == auth_info.source_domain:",
"except UnauthorizedException as e: return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except",
"import db from fedlearner_webconsole.project.models import Project from fedlearner_webconsole.workflow.models import (",
"project_id=project.id, state=state, target_state=target_state, transaction_state=transaction_state) db.session.add(workflow) db.session.commit() db.session.refresh(workflow) workflow.update_state( state, target_state,",
"var_list: job_def.variables.append(i) def get_workflow(self, request): with self._app.app_context(): project, party =",
"if i.access_mode in modes] job_def.ClearField('variables') for i in var_list: job_def.variables.append(i)",
"UnauthorizedException ) class RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer): def __init__(self, server): self._server = server",
"compliance with the License. # You may obtain a copy",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"error: %s', repr(e)) return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def GetWorkflow(self,",
"if workflow is None: assert state == WorkflowState.NEW assert target_state",
"def update_workflow_state(self, request): with self._app.app_context(): project, party = self.check_auth_info(request.auth_info) logging.debug(",
"with self._app.app_context(): _, party = self.check_auth_info(request.auth_info) logging.debug( 'received check_connection from",
"distributed under the License is distributed on an \"AS IS\"",
"Workflow.query.get(workflow.forked_from).name return service_pb2.GetWorkflowResponse( name=request.workflow_name, status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), config=config, jobs=jobs, state=workflow.state.value, target_state=workflow.target_state.value,",
"var_list = [ i for i in workflow.variables if i.access_mode",
"self._filter_workflow( config, [ common_pb2.Variable.PEER_READABLE, common_pb2.Variable.PEER_WRITABLE ]) # job details jobs",
"project, source_party def check_connection(self, request): with self._app.app_context(): _, party =",
"WorkflowState(request.target_state) transaction_state = TransactionState(request.transaction_state) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() if",
"under the License. # coding: utf-8 # pylint: disable=broad-except, cyclic-import",
"Workflow, WorkflowState, TransactionState ) from fedlearner_webconsole.exceptions import ( UnauthorizedException )",
"return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('GetWorkflow",
"= self.check_auth_info(request.auth_info) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() assert workflow is",
"express or implied. # See the License for the specific",
"except in compliance with the License. # You may obtain",
"app.config.get('GRPC_LISTEN_PORT', 1999) with self._lock: self._server = grpc.server( futures.ThreadPoolExecutor(max_workers=10)) service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server( RPCServerServicer(self),",
"project = Project.query.filter_by( name=auth_info.project_name).first() if project is None: raise UnauthorizedException('Invalid",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"self.check_auth_info(request.auth_info) logging.debug( 'received check_connection from %s', party.domain_name) return service_pb2.CheckConnectionResponse( status=common_pb2.Status(",
"not use this file except in compliance with the License.",
"request, context): try: return self._server.check_connection(request) except UnauthorizedException as e: return",
"None: assert state == WorkflowState.NEW assert target_state == WorkflowState.READY workflow",
"service_pb2.GetWorkflowResponse( name=request.workflow_name, status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), config=config, jobs=jobs, state=workflow.state.value, target_state=workflow.target_state.value, transaction_state=workflow.transaction_state.value, forkable=workflow.forkable,",
"# pylint: disable=broad-except, cyclic-import import logging import threading from concurrent",
"party.domain_name, request) name = request.workflow_name state = WorkflowState(request.state) target_state =",
"writing, software # distributed under the License is distributed on",
"def stop(self): if not self._started: return with self._lock: self._server.stop(None).wait() del",
"None: raise UnauthorizedException('Invalid domain') return project, source_party def check_connection(self, request):",
"you may not use this file except in compliance with",
"limitations under the License. # coding: utf-8 # pylint: disable=broad-except,",
"= party if source_party is None: raise UnauthorizedException('Invalid domain') return",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"if workflow is None: return var_list = [ i for",
"party = self.check_auth_info(request.auth_info) logging.debug( 'received check_connection from %s', party.domain_name) return",
"code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) class RpcServer(object): def __init__(self): self._lock = threading.Lock() self._started",
"as e: logging.error('GetWorkflow rpc server error: %s', repr(e)) return service_pb2.GetWorkflowResponse(",
"RpcServer(object): def __init__(self): self._lock = threading.Lock() self._started = False self._server",
"target_state = WorkflowState(request.target_state) transaction_state = TransactionState(request.transaction_state) workflow = Workflow.query.filter_by( name=request.workflow_name,",
"def UpdateWorkflowState(self, request, context): try: return self._server.update_workflow_state(request) except UnauthorizedException as",
"state, target_state, transaction_state) db.session.commit() return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), transaction_state=workflow.transaction_state.value) def",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"threading.Lock() self._started = False self._server = None self._app = None",
"e: return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e:",
"code=common_pb2.STATUS_SUCCESS), transaction_state=workflow.transaction_state.value) def _filter_workflow(self, workflow, modes): # filter peer-readable and",
"project_config.participants: if party.domain_name == auth_info.source_domain: source_party = party if source_party",
"import Project from fedlearner_webconsole.workflow.models import ( Workflow, WorkflowState, TransactionState )",
"WorkflowState, TransactionState ) from fedlearner_webconsole.exceptions import ( UnauthorizedException ) class",
"governing permissions and # limitations under the License. # coding:",
"Project from fedlearner_webconsole.workflow.models import ( Workflow, WorkflowState, TransactionState ) from",
"service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS)) def update_workflow_state(self, request): with self._app.app_context(): project, party",
"pylint: disable=broad-except, cyclic-import import logging import threading from concurrent import",
"= [service_pb2.JobDetail( name=job.name, state=job.get_state_for_front()) for job in workflow.get_jobs()] # fork",
"self._server = None self._app = None def start(self, app): assert",
"WorkflowState.READY workflow = Workflow( name=name, project_id=project.id, state=state, target_state=target_state, transaction_state=transaction_state) db.session.add(workflow)",
"Workflow( name=name, project_id=project.id, state=state, target_state=target_state, transaction_state=transaction_state) db.session.add(workflow) db.session.commit() db.session.refresh(workflow) workflow.update_state(",
"def CheckConnection(self, request, context): try: return self._server.check_connection(request) except UnauthorizedException as",
"auth_info.source_domain: source_party = party if source_party is None: raise UnauthorizedException('Invalid",
"GetWorkflow(self, request, context): try: return self._server.get_workflow(request) except UnauthorizedException as e:",
"def __init__(self, server): self._server = server def CheckConnection(self, request, context):",
"code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('CheckConnection rpc server error:",
"in var_list: job_def.variables.append(i) def get_workflow(self, request): with self._app.app_context(): project, party",
"status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) class RpcServer(object): def __init__(self): self._lock = threading.Lock()",
"self._server = server def CheckConnection(self, request, context): try: return self._server.check_connection(request)",
"code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def UpdateWorkflowState(self, request, context): try: return self._server.update_workflow_state(request) except",
"fedlearner_webconsole.db import db from fedlearner_webconsole.project.models import Project from fedlearner_webconsole.workflow.models import",
"UnauthorizedException('Invalid project') project_config = project.get_config() # TODO: fix token verification",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"= Workflow( name=name, project_id=project.id, state=state, target_state=target_state, transaction_state=transaction_state) db.session.add(workflow) db.session.commit() db.session.refresh(workflow)",
"return var_list = [ i for i in workflow.variables if",
"the License is distributed on an \"AS IS\" BASIS, #",
"request): with self._app.app_context(): project, party = self.check_auth_info(request.auth_info) workflow = Workflow.query.filter_by(",
"name=job.name, state=job.get_state_for_front()) for job in workflow.get_jobs()] # fork info forked_from",
"repr(e)) return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def GetWorkflow(self, request, context):",
"if i.access_mode in modes] workflow.ClearField('variables') for i in var_list: workflow.variables.append(i)",
"None config = workflow.get_config() self._filter_workflow( config, [ common_pb2.Variable.PEER_READABLE, common_pb2.Variable.PEER_WRITABLE ])",
"self._server.get_workflow(request) except UnauthorizedException as e: return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e)))",
"party.domain_name == auth_info.source_domain: source_party = party if source_party is None:",
"return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) class RpcServer(object): def __init__(self): self._lock",
"UpdateWorkflowState(self, request, context): try: return self._server.update_workflow_state(request) except UnauthorizedException as e:",
") from fedlearner_webconsole.db import db from fedlearner_webconsole.project.models import Project from",
"as e: logging.error('CheckConnection rpc server error: %s', repr(e)) return service_pb2.CheckConnectionResponse(",
"service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server( RPCServerServicer(self), self._server) self._server.add_insecure_port('[::]:%d' % listen_port) self._server.start() self._started = True",
"with self._app.app_context(): project, party = self.check_auth_info(request.auth_info) logging.debug( 'received update_workflow_state from",
"target_state=workflow.target_state.value, transaction_state=workflow.transaction_state.value, forkable=workflow.forkable, forked_from=forked_from, reuse_job_names=workflow.get_reuse_job_names(), peer_reuse_job_names=workflow.get_peer_reuse_job_names(), fork_proposal_config=workflow.get_fork_proposal_config() ) rpc_server =",
"repr(e)) return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) class RpcServer(object): def __init__(self):",
"= self.check_auth_info(request.auth_info) logging.debug( 'received check_connection from %s', party.domain_name) return service_pb2.CheckConnectionResponse(",
"with self._app.app_context(): project, party = self.check_auth_info(request.auth_info) workflow = Workflow.query.filter_by( name=request.workflow_name,",
"return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def UpdateWorkflowState(self, request, context): try:",
"__init__(self, server): self._server = server def CheckConnection(self, request, context): try:",
"check_connection from %s', party.domain_name) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS)) def update_workflow_state(self,",
"workflow.get_config() self._filter_workflow( config, [ common_pb2.Variable.PEER_READABLE, common_pb2.Variable.PEER_WRITABLE ]) # job details",
"i for i in workflow.variables if i.access_mode in modes] workflow.ClearField('variables')",
"# fork info forked_from = '' if workflow.forked_from: forked_from =",
"self.check_auth_info(request.auth_info) logging.debug( 'received update_workflow_state from %s: %s', party.domain_name, request) name",
"source_party = party if source_party is None: raise UnauthorizedException('Invalid domain')",
"msg=repr(e))) except Exception as e: logging.error('UpdateWorkflowState rpc server error: %s',",
"= '' if workflow.forked_from: forked_from = Workflow.query.get(workflow.forked_from).name return service_pb2.GetWorkflowResponse( name=request.workflow_name,",
"law or agreed to in writing, software # distributed under",
"= Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() if workflow is None: assert state",
"RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer): def __init__(self, server): self._server = server def CheckConnection(self, request,",
"%s', repr(e)) return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def GetWorkflow(self, request,",
"workflow is not None config = workflow.get_config() self._filter_workflow( config, [",
"'received update_workflow_state from %s: %s', party.domain_name, request) name = request.workflow_name",
"concurrent import futures import grpc from fedlearner_webconsole.proto import ( service_pb2,",
"modes] workflow.ClearField('variables') for i in var_list: workflow.variables.append(i) for job_def in",
"self._started = False self._server = None self._app = None def",
"jobs=jobs, state=workflow.state.value, target_state=workflow.target_state.value, transaction_state=workflow.transaction_state.value, forkable=workflow.forkable, forked_from=forked_from, reuse_job_names=workflow.get_reuse_job_names(), peer_reuse_job_names=workflow.get_peer_reuse_job_names(), fork_proposal_config=workflow.get_fork_proposal_config() )",
"== auth_info.source_domain: source_party = party if source_party is None: raise",
"request.workflow_name state = WorkflowState(request.state) target_state = WorkflowState(request.target_state) transaction_state = TransactionState(request.transaction_state)",
"with self._lock: self._server.stop(None).wait() del self._server self._started = False def check_auth_info(self,",
"workflow.forked_from: forked_from = Workflow.query.get(workflow.forked_from).name return service_pb2.GetWorkflowResponse( name=request.workflow_name, status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), config=config,",
"1999) with self._lock: self._server = grpc.server( futures.ThreadPoolExecutor(max_workers=10)) service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server( RPCServerServicer(self), self._server)",
"i in workflow.variables if i.access_mode in modes] workflow.ClearField('variables') for i",
"project is None: raise UnauthorizedException('Invalid project') project_config = project.get_config() #",
"Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() assert workflow is not None config =",
"self._server.add_insecure_port('[::]:%d' % listen_port) self._server.start() self._started = True def stop(self): if",
"[ common_pb2.Variable.PEER_READABLE, common_pb2.Variable.PEER_WRITABLE ]) # job details jobs = [service_pb2.JobDetail(",
"may obtain a copy of the License at # #",
"import futures import grpc from fedlearner_webconsole.proto import ( service_pb2, service_pb2_grpc,",
"code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('GetWorkflow rpc server error:",
"check_auth_info(self, auth_info): logging.debug('auth_info: %s', auth_info) project = Project.query.filter_by( name=auth_info.project_name).first() if",
"server error: %s', repr(e)) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def",
"TransactionState(request.transaction_state) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() if workflow is None:",
"transaction_state) db.session.commit() return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), transaction_state=workflow.transaction_state.value) def _filter_workflow(self, workflow,",
"= [ i for i in job_def.variables if i.access_mode in",
"self._server.check_connection(request) except UnauthorizedException as e: return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e)))",
"del self._server self._started = False def check_auth_info(self, auth_info): logging.debug('auth_info: %s',",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"try: return self._server.get_workflow(request) except UnauthorizedException as e: return service_pb2.GetWorkflowResponse( status=common_pb2.Status(",
"project.get_config() # TODO: fix token verification # if project_config.token !=",
"job_def.variables.append(i) def get_workflow(self, request): with self._app.app_context(): project, party = self.check_auth_info(request.auth_info)",
"may not use this file except in compliance with the",
"start(self, app): assert not self._started, \"Already started\" self._app = app",
"listen_port = app.config.get('GRPC_LISTEN_PORT', 1999) with self._lock: self._server = grpc.server( futures.ThreadPoolExecutor(max_workers=10))",
"code=common_pb2.STATUS_SUCCESS), config=config, jobs=jobs, state=workflow.state.value, target_state=workflow.target_state.value, transaction_state=workflow.transaction_state.value, forkable=workflow.forkable, forked_from=forked_from, reuse_job_names=workflow.get_reuse_job_names(), peer_reuse_job_names=workflow.get_peer_reuse_job_names(),",
"request, context): try: return self._server.get_workflow(request) except UnauthorizedException as e: return",
"= app listen_port = app.config.get('GRPC_LISTEN_PORT', 1999) with self._lock: self._server =",
"'received check_connection from %s', party.domain_name) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS)) def",
"in workflow.variables if i.access_mode in modes] workflow.ClearField('variables') for i in",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"as e: logging.error('UpdateWorkflowState rpc server error: %s', repr(e)) return service_pb2.UpdateWorkflowStateResponse(",
"logging.error('GetWorkflow rpc server error: %s', repr(e)) return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR,",
"self._server.start() self._started = True def stop(self): if not self._started: return",
"this file except in compliance with the License. # You",
"workflow.get_jobs()] # fork info forked_from = '' if workflow.forked_from: forked_from",
"= True def stop(self): if not self._started: return with self._lock:",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"i in job_def.variables if i.access_mode in modes] job_def.ClearField('variables') for i",
"return project, source_party def check_connection(self, request): with self._app.app_context(): _, party",
"self._lock: self._server.stop(None).wait() del self._server self._started = False def check_auth_info(self, auth_info):",
"threading from concurrent import futures import grpc from fedlearner_webconsole.proto import",
"# # Licensed under the Apache License, Version 2.0 (the",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) class RpcServer(object): def __init__(self): self._lock =",
"is None: raise UnauthorizedException('Invalid project') project_config = project.get_config() # TODO:",
"grpc from fedlearner_webconsole.proto import ( service_pb2, service_pb2_grpc, common_pb2 ) from",
"# filter peer-readable and peer-writable variables if workflow is None:",
"forked_from = '' if workflow.forked_from: forked_from = Workflow.query.get(workflow.forked_from).name return service_pb2.GetWorkflowResponse(",
"!= auth_info.auth_token: # raise UnauthorizedException('Invalid token') if project_config.domain_name != auth_info.target_domain:",
"self._app.app_context(): project, party = self.check_auth_info(request.auth_info) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first()",
"repr(e)) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def UpdateWorkflowState(self, request, context):",
"_, party = self.check_auth_info(request.auth_info) logging.debug( 'received check_connection from %s', party.domain_name)",
"name=request.workflow_name, status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), config=config, jobs=jobs, state=workflow.state.value, target_state=workflow.target_state.value, transaction_state=workflow.transaction_state.value, forkable=workflow.forkable, forked_from=forked_from,",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"== WorkflowState.READY workflow = Workflow( name=name, project_id=project.id, state=state, target_state=target_state, transaction_state=transaction_state)",
"except Exception as e: logging.error('GetWorkflow rpc server error: %s', repr(e))",
"variables if workflow is None: return var_list = [ i",
"from concurrent import futures import grpc from fedlearner_webconsole.proto import (",
"= TransactionState(request.transaction_state) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() if workflow is",
"source_party is None: raise UnauthorizedException('Invalid domain') return project, source_party def",
"Project.query.filter_by( name=auth_info.project_name).first() if project is None: raise UnauthorizedException('Invalid project') project_config",
"state=state, target_state=target_state, transaction_state=transaction_state) db.session.add(workflow) db.session.commit() db.session.refresh(workflow) workflow.update_state( state, target_state, transaction_state)",
"self._server self._started = False def check_auth_info(self, auth_info): logging.debug('auth_info: %s', auth_info)",
"Exception as e: logging.error('GetWorkflow rpc server error: %s', repr(e)) return",
"server error: %s', repr(e)) return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def",
"from fedlearner_webconsole.workflow.models import ( Workflow, WorkflowState, TransactionState ) from fedlearner_webconsole.exceptions",
"request): with self._app.app_context(): _, party = self.check_auth_info(request.auth_info) logging.debug( 'received check_connection",
"logging.error('CheckConnection rpc server error: %s', repr(e)) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR,",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"context): try: return self._server.get_workflow(request) except UnauthorizedException as e: return service_pb2.GetWorkflowResponse(",
"stop(self): if not self._started: return with self._lock: self._server.stop(None).wait() del self._server",
"return self._server.get_workflow(request) except UnauthorizedException as e: return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED,",
"%s', auth_info) project = Project.query.filter_by( name=auth_info.project_name).first() if project is None:",
"app listen_port = app.config.get('GRPC_LISTEN_PORT', 1999) with self._lock: self._server = grpc.server(",
") from fedlearner_webconsole.exceptions import ( UnauthorizedException ) class RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer): def",
"party = self.check_auth_info(request.auth_info) logging.debug( 'received update_workflow_state from %s: %s', party.domain_name,",
"or implied. # See the License for the specific language",
"]) # job details jobs = [service_pb2.JobDetail( name=job.name, state=job.get_state_for_front()) for",
"Rights Reserved. # # Licensed under the Apache License, Version",
"= Workflow.query.get(workflow.forked_from).name return service_pb2.GetWorkflowResponse( name=request.workflow_name, status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), config=config, jobs=jobs, state=workflow.state.value,",
"( UnauthorizedException ) class RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer): def __init__(self, server): self._server =",
"workflow.variables.append(i) for job_def in workflow.job_definitions: var_list = [ i for",
"True def stop(self): if not self._started: return with self._lock: self._server.stop(None).wait()",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"party.domain_name) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS)) def update_workflow_state(self, request): with self._app.app_context():",
"common_pb2.Variable.PEER_WRITABLE ]) # job details jobs = [service_pb2.JobDetail( name=job.name, state=job.get_state_for_front())",
"workflow is None: assert state == WorkflowState.NEW assert target_state ==",
"except Exception as e: logging.error('UpdateWorkflowState rpc server error: %s', repr(e))",
"def check_auth_info(self, auth_info): logging.debug('auth_info: %s', auth_info) project = Project.query.filter_by( name=auth_info.project_name).first()",
"%s: %s', party.domain_name, request) name = request.workflow_name state = WorkflowState(request.state)",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS)) def update_workflow_state(self, request): with self._app.app_context(): project,",
"i.access_mode in modes] job_def.ClearField('variables') for i in var_list: job_def.variables.append(i) def",
"%s', repr(e)) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def UpdateWorkflowState(self, request,",
"logging import threading from concurrent import futures import grpc from",
"workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() assert workflow is not None",
"for party in project_config.participants: if party.domain_name == auth_info.source_domain: source_party =",
"%s', repr(e)) return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) class RpcServer(object): def",
"error: %s', repr(e)) return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) class RpcServer(object):",
"workflow = Workflow( name=name, project_id=project.id, state=state, target_state=target_state, transaction_state=transaction_state) db.session.add(workflow) db.session.commit()",
"target_state=target_state, transaction_state=transaction_state) db.session.add(workflow) db.session.commit() db.session.refresh(workflow) workflow.update_state( state, target_state, transaction_state) db.session.commit()",
"project, party = self.check_auth_info(request.auth_info) logging.debug( 'received update_workflow_state from %s: %s',",
"workflow, modes): # filter peer-readable and peer-writable variables if workflow",
"permissions and # limitations under the License. # coding: utf-8",
"class RpcServer(object): def __init__(self): self._lock = threading.Lock() self._started = False",
"(the \"License\"); # you may not use this file except",
"def get_workflow(self, request): with self._app.app_context(): project, party = self.check_auth_info(request.auth_info) workflow",
"status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('CheckConnection rpc server",
"# you may not use this file except in compliance",
"db.session.commit() db.session.refresh(workflow) workflow.update_state( state, target_state, transaction_state) db.session.commit() return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status(",
"job_def.ClearField('variables') for i in var_list: job_def.variables.append(i) def get_workflow(self, request): with",
"rpc server error: %s', repr(e)) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e)))",
"= project.get_config() # TODO: fix token verification # if project_config.token",
"License. # coding: utf-8 # pylint: disable=broad-except, cyclic-import import logging",
"Exception as e: logging.error('CheckConnection rpc server error: %s', repr(e)) return",
"grpc.server( futures.ThreadPoolExecutor(max_workers=10)) service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server( RPCServerServicer(self), self._server) self._server.add_insecure_port('[::]:%d' % listen_port) self._server.start() self._started",
"= None self._app = None def start(self, app): assert not",
"project') project_config = project.get_config() # TODO: fix token verification #",
"var_list: workflow.variables.append(i) for job_def in workflow.job_definitions: var_list = [ i",
"= server def CheckConnection(self, request, context): try: return self._server.check_connection(request) except",
"False def check_auth_info(self, auth_info): logging.debug('auth_info: %s', auth_info) project = Project.query.filter_by(",
"from fedlearner_webconsole.exceptions import ( UnauthorizedException ) class RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer): def __init__(self,",
"# # Unless required by applicable law or agreed to",
"server def CheckConnection(self, request, context): try: return self._server.check_connection(request) except UnauthorizedException",
"from fedlearner_webconsole.proto import ( service_pb2, service_pb2_grpc, common_pb2 ) from fedlearner_webconsole.db",
"transaction_state = TransactionState(request.transaction_state) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() if workflow",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"cyclic-import import logging import threading from concurrent import futures import",
"rpc server error: %s', repr(e)) return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e)))",
"source_party = None for party in project_config.participants: if party.domain_name ==",
"logging.debug( 'received check_connection from %s', party.domain_name) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS))",
"Version 2.0 (the \"License\"); # you may not use this",
"party in project_config.participants: if party.domain_name == auth_info.source_domain: source_party = party",
"details jobs = [service_pb2.JobDetail( name=job.name, state=job.get_state_for_front()) for job in workflow.get_jobs()]",
"import ( service_pb2, service_pb2_grpc, common_pb2 ) from fedlearner_webconsole.db import db",
"name=name, project_id=project.id, state=state, target_state=target_state, transaction_state=transaction_state) db.session.add(workflow) db.session.commit() db.session.refresh(workflow) workflow.update_state( state,",
"config, [ common_pb2.Variable.PEER_READABLE, common_pb2.Variable.PEER_WRITABLE ]) # job details jobs =",
"# coding: utf-8 # pylint: disable=broad-except, cyclic-import import logging import",
"raise UnauthorizedException('Invalid domain') return project, source_party def check_connection(self, request): with",
"= threading.Lock() self._started = False self._server = None self._app =",
"listen_port) self._server.start() self._started = True def stop(self): if not self._started:",
"with self._lock: self._server = grpc.server( futures.ThreadPoolExecutor(max_workers=10)) service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server( RPCServerServicer(self), self._server) self._server.add_insecure_port('[::]:%d'",
"implied. # See the License for the specific language governing",
"UnauthorizedException as e: return service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"coding: utf-8 # pylint: disable=broad-except, cyclic-import import logging import threading",
"( service_pb2, service_pb2_grpc, common_pb2 ) from fedlearner_webconsole.db import db from",
"as e: return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as",
"i.access_mode in modes] workflow.ClearField('variables') for i in var_list: workflow.variables.append(i) for",
"peer-writable variables if workflow is None: return var_list = [",
"class RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer): def __init__(self, server): self._server = server def CheckConnection(self,",
"context): try: return self._server.update_workflow_state(request) except UnauthorizedException as e: return service_pb2.UpdateWorkflowStateResponse(",
"msg=repr(e))) def UpdateWorkflowState(self, request, context): try: return self._server.update_workflow_state(request) except UnauthorizedException",
"if party.domain_name == auth_info.source_domain: source_party = party if source_party is",
"by applicable law or agreed to in writing, software #",
"started\" self._app = app listen_port = app.config.get('GRPC_LISTEN_PORT', 1999) with self._lock:",
"# if project_config.token != auth_info.auth_token: # raise UnauthorizedException('Invalid token') if",
"not None config = workflow.get_config() self._filter_workflow( config, [ common_pb2.Variable.PEER_READABLE, common_pb2.Variable.PEER_WRITABLE",
"fedlearner_webconsole.project.models import Project from fedlearner_webconsole.workflow.models import ( Workflow, WorkflowState, TransactionState",
"service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def UpdateWorkflowState(self, request, context): try: return",
"RPCServerServicer(self), self._server) self._server.add_insecure_port('[::]:%d' % listen_port) self._server.start() self._started = True def",
"# job details jobs = [service_pb2.JobDetail( name=job.name, state=job.get_state_for_front()) for job",
"= Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() assert workflow is not None config",
"( Workflow, WorkflowState, TransactionState ) from fedlearner_webconsole.exceptions import ( UnauthorizedException",
"self._server) self._server.add_insecure_port('[::]:%d' % listen_port) self._server.start() self._started = True def stop(self):",
"futures import grpc from fedlearner_webconsole.proto import ( service_pb2, service_pb2_grpc, common_pb2",
"The FedLearner Authors. All Rights Reserved. # # Licensed under",
"for i in job_def.variables if i.access_mode in modes] job_def.ClearField('variables') for",
"forked_from = Workflow.query.get(workflow.forked_from).name return service_pb2.GetWorkflowResponse( name=request.workflow_name, status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), config=config, jobs=jobs,",
"assert workflow is not None config = workflow.get_config() self._filter_workflow( config,",
"assert not self._started, \"Already started\" self._app = app listen_port =",
"i for i in job_def.variables if i.access_mode in modes] job_def.ClearField('variables')",
"except Exception as e: logging.error('CheckConnection rpc server error: %s', repr(e))",
"filter peer-readable and peer-writable variables if workflow is None: return",
"for job_def in workflow.job_definitions: var_list = [ i for i",
"# TODO: fix token verification # if project_config.token != auth_info.auth_token:",
"db.session.add(workflow) db.session.commit() db.session.refresh(workflow) workflow.update_state( state, target_state, transaction_state) db.session.commit() return service_pb2.UpdateWorkflowStateResponse(",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), transaction_state=workflow.transaction_state.value) def _filter_workflow(self, workflow, modes): # filter peer-readable",
"\"Already started\" self._app = app listen_port = app.config.get('GRPC_LISTEN_PORT', 1999) with",
"raise UnauthorizedException('Invalid project') project_config = project.get_config() # TODO: fix token",
"self._app.app_context(): project, party = self.check_auth_info(request.auth_info) logging.debug( 'received update_workflow_state from %s:",
"def check_connection(self, request): with self._app.app_context(): _, party = self.check_auth_info(request.auth_info) logging.debug(",
"the specific language governing permissions and # limitations under the",
"fix token verification # if project_config.token != auth_info.auth_token: # raise",
"logging.error('UpdateWorkflowState rpc server error: %s', repr(e)) return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR,",
"db.session.refresh(workflow) workflow.update_state( state, target_state, transaction_state) db.session.commit() return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS),",
"applicable law or agreed to in writing, software # distributed",
"status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('UpdateWorkflowState rpc server",
"import ( UnauthorizedException ) class RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer): def __init__(self, server): self._server",
"try: return self._server.update_workflow_state(request) except UnauthorizedException as e: return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status(",
"from %s: %s', party.domain_name, request) name = request.workflow_name state =",
"fedlearner_webconsole.exceptions import ( UnauthorizedException ) class RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer): def __init__(self, server):",
"return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), transaction_state=workflow.transaction_state.value) def _filter_workflow(self, workflow, modes): #",
"self._lock: self._server = grpc.server( futures.ThreadPoolExecutor(max_workers=10)) service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server( RPCServerServicer(self), self._server) self._server.add_insecure_port('[::]:%d' %",
"transaction_state=workflow.transaction_state.value) def _filter_workflow(self, workflow, modes): # filter peer-readable and peer-writable",
"Exception as e: logging.error('UpdateWorkflowState rpc server error: %s', repr(e)) return",
"msg=repr(e))) except Exception as e: logging.error('CheckConnection rpc server error: %s',",
"domain') source_party = None for party in project_config.participants: if party.domain_name",
"workflow.variables if i.access_mode in modes] workflow.ClearField('variables') for i in var_list:",
"in writing, software # distributed under the License is distributed",
"modes): # filter peer-readable and peer-writable variables if workflow is",
"None: raise UnauthorizedException('Invalid project') project_config = project.get_config() # TODO: fix",
"config=config, jobs=jobs, state=workflow.state.value, target_state=workflow.target_state.value, transaction_state=workflow.transaction_state.value, forkable=workflow.forkable, forked_from=forked_from, reuse_job_names=workflow.get_reuse_job_names(), peer_reuse_job_names=workflow.get_peer_reuse_job_names(), fork_proposal_config=workflow.get_fork_proposal_config()",
"name=request.workflow_name, project_id=project.id).first() if workflow is None: assert state == WorkflowState.NEW",
"= False def check_auth_info(self, auth_info): logging.debug('auth_info: %s', auth_info) project =",
"except UnauthorizedException as e: return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except",
"logging.debug( 'received update_workflow_state from %s: %s', party.domain_name, request) name =",
"from %s', party.domain_name) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS)) def update_workflow_state(self, request):",
"update_workflow_state(self, request): with self._app.app_context(): project, party = self.check_auth_info(request.auth_info) logging.debug( 'received",
"job_def.variables if i.access_mode in modes] job_def.ClearField('variables') for i in var_list:",
"CheckConnection(self, request, context): try: return self._server.check_connection(request) except UnauthorizedException as e:",
"def GetWorkflow(self, request, context): try: return self._server.get_workflow(request) except UnauthorizedException as",
"job details jobs = [service_pb2.JobDetail( name=job.name, state=job.get_state_for_front()) for job in",
"= None def start(self, app): assert not self._started, \"Already started\"",
"== WorkflowState.NEW assert target_state == WorkflowState.READY workflow = Workflow( name=name,",
"workflow is None: return var_list = [ i for i",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"_filter_workflow(self, workflow, modes): # filter peer-readable and peer-writable variables if",
"License, Version 2.0 (the \"License\"); # you may not use",
"common_pb2.Variable.PEER_READABLE, common_pb2.Variable.PEER_WRITABLE ]) # job details jobs = [service_pb2.JobDetail( name=job.name,",
"# You may obtain a copy of the License at",
"name=request.workflow_name, project_id=project.id).first() assert workflow is not None config = workflow.get_config()",
"workflow.job_definitions: var_list = [ i for i in job_def.variables if",
"domain') return project, source_party def check_connection(self, request): with self._app.app_context(): _,",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"if workflow.forked_from: forked_from = Workflow.query.get(workflow.forked_from).name return service_pb2.GetWorkflowResponse( name=request.workflow_name, status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS),",
"Authors. All Rights Reserved. # # Licensed under the Apache",
"project_config.domain_name != auth_info.target_domain: raise UnauthorizedException('Invalid domain') source_party = None for",
"for job in workflow.get_jobs()] # fork info forked_from = ''",
"in workflow.job_definitions: var_list = [ i for i in job_def.variables",
"project_config = project.get_config() # TODO: fix token verification # if",
"self._app = app listen_port = app.config.get('GRPC_LISTEN_PORT', 1999) with self._lock: self._server",
"service_pb2.GetWorkflowResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('GetWorkflow rpc",
"is not None config = workflow.get_config() self._filter_workflow( config, [ common_pb2.Variable.PEER_READABLE,",
"if project is None: raise UnauthorizedException('Invalid project') project_config = project.get_config()",
"None for party in project_config.participants: if party.domain_name == auth_info.source_domain: source_party",
"return self._server.check_connection(request) except UnauthorizedException as e: return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED,",
"request): with self._app.app_context(): project, party = self.check_auth_info(request.auth_info) logging.debug( 'received update_workflow_state",
"the License for the specific language governing permissions and #",
"not self._started, \"Already started\" self._app = app listen_port = app.config.get('GRPC_LISTEN_PORT',",
"not self._started: return with self._lock: self._server.stop(None).wait() del self._server self._started =",
"import logging import threading from concurrent import futures import grpc",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"self._started: return with self._lock: self._server.stop(None).wait() del self._server self._started = False",
"party if source_party is None: raise UnauthorizedException('Invalid domain') return project,",
"either express or implied. # See the License for the",
"workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() if workflow is None: assert",
"target_state == WorkflowState.READY workflow = Workflow( name=name, project_id=project.id, state=state, target_state=target_state,",
"auth_info) project = Project.query.filter_by( name=auth_info.project_name).first() if project is None: raise",
"state = WorkflowState(request.state) target_state = WorkflowState(request.target_state) transaction_state = TransactionState(request.transaction_state) workflow",
"code=common_pb2.STATUS_SUCCESS)) def update_workflow_state(self, request): with self._app.app_context(): project, party = self.check_auth_info(request.auth_info)",
") class RPCServerServicer(service_pb2_grpc.WebConsoleV2ServiceServicer): def __init__(self, server): self._server = server def",
"FedLearner Authors. All Rights Reserved. # # Licensed under the",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"transaction_state=workflow.transaction_state.value, forkable=workflow.forkable, forked_from=forked_from, reuse_job_names=workflow.get_reuse_job_names(), peer_reuse_job_names=workflow.get_peer_reuse_job_names(), fork_proposal_config=workflow.get_fork_proposal_config() ) rpc_server = RpcServer()",
"service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def GetWorkflow(self, request, context): try: return",
"state=job.get_state_for_front()) for job in workflow.get_jobs()] # fork info forked_from =",
"token verification # if project_config.token != auth_info.auth_token: # raise UnauthorizedException('Invalid",
"in workflow.get_jobs()] # fork info forked_from = '' if workflow.forked_from:",
"'' if workflow.forked_from: forked_from = Workflow.query.get(workflow.forked_from).name return service_pb2.GetWorkflowResponse( name=request.workflow_name, status=common_pb2.Status(",
"the License. # coding: utf-8 # pylint: disable=broad-except, cyclic-import import",
"workflow.update_state( state, target_state, transaction_state) db.session.commit() return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS), transaction_state=workflow.transaction_state.value)",
"var_list = [ i for i in job_def.variables if i.access_mode",
"UnauthorizedException('Invalid domain') source_party = None for party in project_config.participants: if",
"% listen_port) self._server.start() self._started = True def stop(self): if not",
"import ( Workflow, WorkflowState, TransactionState ) from fedlearner_webconsole.exceptions import (",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"get_workflow(self, request): with self._app.app_context(): project, party = self.check_auth_info(request.auth_info) workflow =",
"def _filter_workflow(self, workflow, modes): # filter peer-readable and peer-writable variables",
"# Copyright 2020 The FedLearner Authors. All Rights Reserved. #",
"i in var_list: job_def.variables.append(i) def get_workflow(self, request): with self._app.app_context(): project,",
"self._server.stop(None).wait() del self._server self._started = False def check_auth_info(self, auth_info): logging.debug('auth_info:",
"server): self._server = server def CheckConnection(self, request, context): try: return",
"\"License\"); # you may not use this file except in",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"party = self.check_auth_info(request.auth_info) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() assert workflow",
"auth_info): logging.debug('auth_info: %s', auth_info) project = Project.query.filter_by( name=auth_info.project_name).first() if project",
"in job_def.variables if i.access_mode in modes] job_def.ClearField('variables') for i in",
"raise UnauthorizedException('Invalid token') if project_config.domain_name != auth_info.target_domain: raise UnauthorizedException('Invalid domain')",
"WorkflowState.NEW assert target_state == WorkflowState.READY workflow = Workflow( name=name, project_id=project.id,",
"# distributed under the License is distributed on an \"AS",
"for i in var_list: workflow.variables.append(i) for job_def in workflow.job_definitions: var_list",
"# Unless required by applicable law or agreed to in",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"= app.config.get('GRPC_LISTEN_PORT', 1999) with self._lock: self._server = grpc.server( futures.ThreadPoolExecutor(max_workers=10)) service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server(",
"common_pb2 ) from fedlearner_webconsole.db import db from fedlearner_webconsole.project.models import Project",
"self.check_auth_info(request.auth_info) workflow = Workflow.query.filter_by( name=request.workflow_name, project_id=project.id).first() assert workflow is not",
"e: logging.error('CheckConnection rpc server error: %s', repr(e)) return service_pb2.CheckConnectionResponse( status=common_pb2.Status(",
"status=common_pb2.Status( code=common_pb2.STATUS_UNKNOWN_ERROR, msg=repr(e))) def UpdateWorkflowState(self, request, context): try: return self._server.update_workflow_state(request)",
"if source_party is None: raise UnauthorizedException('Invalid domain') return project, source_party",
"%s', party.domain_name) return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_SUCCESS)) def update_workflow_state(self, request): with",
"You may obtain a copy of the License at #",
"__init__(self): self._lock = threading.Lock() self._started = False self._server = None",
"Copyright 2020 The FedLearner Authors. All Rights Reserved. # #",
"# limitations under the License. # coding: utf-8 # pylint:",
"auth_info.auth_token: # raise UnauthorizedException('Invalid token') if project_config.domain_name != auth_info.target_domain: raise",
"code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('UpdateWorkflowState rpc server error:",
"import grpc from fedlearner_webconsole.proto import ( service_pb2, service_pb2_grpc, common_pb2 )",
"if project_config.token != auth_info.auth_token: # raise UnauthorizedException('Invalid token') if project_config.domain_name",
"return service_pb2.CheckConnectionResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED, msg=repr(e))) except Exception as e: logging.error('CheckConnection",
"return self._server.update_workflow_state(request) except UnauthorizedException as e: return service_pb2.UpdateWorkflowStateResponse( status=common_pb2.Status( code=common_pb2.STATUS_UNAUTHORIZED,",
"self._app.app_context(): _, party = self.check_auth_info(request.auth_info) logging.debug( 'received check_connection from %s',",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"self._server = grpc.server( futures.ThreadPoolExecutor(max_workers=10)) service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server( RPCServerServicer(self), self._server) self._server.add_insecure_port('[::]:%d' % listen_port)",
"is None: assert state == WorkflowState.NEW assert target_state == WorkflowState.READY",
"fork info forked_from = '' if workflow.forked_from: forked_from = Workflow.query.get(workflow.forked_from).name",
"= grpc.server( futures.ThreadPoolExecutor(max_workers=10)) service_pb2_grpc.add_WebConsoleV2ServiceServicer_to_server( RPCServerServicer(self), self._server) self._server.add_insecure_port('[::]:%d' % listen_port) self._server.start()",
"context): try: return self._server.check_connection(request) except UnauthorizedException as e: return service_pb2.CheckConnectionResponse(",
"token') if project_config.domain_name != auth_info.target_domain: raise UnauthorizedException('Invalid domain') source_party ="
] |
[
"base))) for base in BASES ]) if __name__ == \"__main__\":",
"def present_result(result): base, rates = (await result) rates_line = \",",
"BASES = ('USD', 'EUR', 'PLN', 'NOK', 'CZK') async def fetch_rates(session,",
"result) rates_line = \", \".join( [f\"{rates[symbol]:7.03} {symbol}\" for symbol in",
"for symbol in SYMBOLS] ) print(f\"1 {base} = {rates_line}\") async",
"asyncio import time import aiohttp from asyncrates import get_rates SYMBOLS",
"]) if __name__ == \"__main__\": started = time.time() loop =",
"time import aiohttp from asyncrates import get_rates SYMBOLS = ('USD',",
"'NOK', 'CZK') async def fetch_rates(session, place): return await get_rates(session, place)",
"\".join( [f\"{rates[symbol]:7.03} {symbol}\" for symbol in SYMBOLS] ) print(f\"1 {base}",
"'NOK', 'CZK') BASES = ('USD', 'EUR', 'PLN', 'NOK', 'CZK') async",
") print(f\"1 {base} = {rates_line}\") async def main(): async with",
"('USD', 'EUR', 'PLN', 'NOK', 'CZK') BASES = ('USD', 'EUR', 'PLN',",
"as session: await asyncio.wait([ asyncio.create_task(present_result(fetch_rates(session, base))) for base in BASES",
"{symbol}\" for symbol in SYMBOLS] ) print(f\"1 {base} = {rates_line}\")",
"started = time.time() loop = asyncio.get_event_loop() loop.run_until_complete(main()) elapsed = time.time()",
"present_result(result): base, rates = (await result) rates_line = \", \".join(",
"= \", \".join( [f\"{rates[symbol]:7.03} {symbol}\" for symbol in SYMBOLS] )",
"aiohttpを使って非同期にHTTPのリクエストを送信する方法 \"\"\" import asyncio import time import aiohttp from asyncrates",
"= asyncio.get_event_loop() loop.run_until_complete(main()) elapsed = time.time() - started print() print(f\"経過時間:",
"place): return await get_rates(session, place) async def present_result(result): base, rates",
"with aiohttp.ClientSession() as session: await asyncio.wait([ asyncio.create_task(present_result(fetch_rates(session, base))) for base",
"\"__main__\": started = time.time() loop = asyncio.get_event_loop() loop.run_until_complete(main()) elapsed =",
"get_rates(session, place) async def present_result(result): base, rates = (await result)",
"session: await asyncio.wait([ asyncio.create_task(present_result(fetch_rates(session, base))) for base in BASES ])",
"loop = asyncio.get_event_loop() loop.run_until_complete(main()) elapsed = time.time() - started print()",
"if __name__ == \"__main__\": started = time.time() loop = asyncio.get_event_loop()",
"asyncio.create_task(present_result(fetch_rates(session, base))) for base in BASES ]) if __name__ ==",
"asyncrates import get_rates SYMBOLS = ('USD', 'EUR', 'PLN', 'NOK', 'CZK')",
"{base} = {rates_line}\") async def main(): async with aiohttp.ClientSession() as",
"'CZK') async def fetch_rates(session, place): return await get_rates(session, place) async",
"def fetch_rates(session, place): return await get_rates(session, place) async def present_result(result):",
"__name__ == \"__main__\": started = time.time() loop = asyncio.get_event_loop() loop.run_until_complete(main())",
"== \"__main__\": started = time.time() loop = asyncio.get_event_loop() loop.run_until_complete(main()) elapsed",
"\"\"\" 「非同期プログラミング」の節で登場するサンプルコード aiohttpを使って非同期にHTTPのリクエストを送信する方法 \"\"\" import asyncio import time import aiohttp",
"import get_rates SYMBOLS = ('USD', 'EUR', 'PLN', 'NOK', 'CZK') BASES",
"{rates_line}\") async def main(): async with aiohttp.ClientSession() as session: await",
"get_rates SYMBOLS = ('USD', 'EUR', 'PLN', 'NOK', 'CZK') BASES =",
"('USD', 'EUR', 'PLN', 'NOK', 'CZK') async def fetch_rates(session, place): return",
"base in BASES ]) if __name__ == \"__main__\": started =",
"in BASES ]) if __name__ == \"__main__\": started = time.time()",
"aiohttp from asyncrates import get_rates SYMBOLS = ('USD', 'EUR', 'PLN',",
"<reponame>haru-256/ExpertPython3_Source<filename>chapter15/async_aiohttp.py<gh_stars>1-10 \"\"\" 「非同期プログラミング」の節で登場するサンプルコード aiohttpを使って非同期にHTTPのリクエストを送信する方法 \"\"\" import asyncio import time import",
"aiohttp.ClientSession() as session: await asyncio.wait([ asyncio.create_task(present_result(fetch_rates(session, base))) for base in",
"rates_line = \", \".join( [f\"{rates[symbol]:7.03} {symbol}\" for symbol in SYMBOLS]",
"\", \".join( [f\"{rates[symbol]:7.03} {symbol}\" for symbol in SYMBOLS] ) print(f\"1",
"await get_rates(session, place) async def present_result(result): base, rates = (await",
"async with aiohttp.ClientSession() as session: await asyncio.wait([ asyncio.create_task(present_result(fetch_rates(session, base))) for",
"for base in BASES ]) if __name__ == \"__main__\": started",
"await asyncio.wait([ asyncio.create_task(present_result(fetch_rates(session, base))) for base in BASES ]) if",
"import asyncio import time import aiohttp from asyncrates import get_rates",
"'EUR', 'PLN', 'NOK', 'CZK') BASES = ('USD', 'EUR', 'PLN', 'NOK',",
"import aiohttp from asyncrates import get_rates SYMBOLS = ('USD', 'EUR',",
"place) async def present_result(result): base, rates = (await result) rates_line",
"(await result) rates_line = \", \".join( [f\"{rates[symbol]:7.03} {symbol}\" for symbol",
"asyncio.wait([ asyncio.create_task(present_result(fetch_rates(session, base))) for base in BASES ]) if __name__",
"fetch_rates(session, place): return await get_rates(session, place) async def present_result(result): base,",
"async def present_result(result): base, rates = (await result) rates_line =",
"[f\"{rates[symbol]:7.03} {symbol}\" for symbol in SYMBOLS] ) print(f\"1 {base} =",
"main(): async with aiohttp.ClientSession() as session: await asyncio.wait([ asyncio.create_task(present_result(fetch_rates(session, base)))",
"'EUR', 'PLN', 'NOK', 'CZK') async def fetch_rates(session, place): return await",
"async def main(): async with aiohttp.ClientSession() as session: await asyncio.wait([",
"「非同期プログラミング」の節で登場するサンプルコード aiohttpを使って非同期にHTTPのリクエストを送信する方法 \"\"\" import asyncio import time import aiohttp from",
"'CZK') BASES = ('USD', 'EUR', 'PLN', 'NOK', 'CZK') async def",
"'PLN', 'NOK', 'CZK') async def fetch_rates(session, place): return await get_rates(session,",
"SYMBOLS = ('USD', 'EUR', 'PLN', 'NOK', 'CZK') BASES = ('USD',",
"import time import aiohttp from asyncrates import get_rates SYMBOLS =",
"in SYMBOLS] ) print(f\"1 {base} = {rates_line}\") async def main():",
"= ('USD', 'EUR', 'PLN', 'NOK', 'CZK') BASES = ('USD', 'EUR',",
"from asyncrates import get_rates SYMBOLS = ('USD', 'EUR', 'PLN', 'NOK',",
"base, rates = (await result) rates_line = \", \".join( [f\"{rates[symbol]:7.03}",
"time.time() loop = asyncio.get_event_loop() loop.run_until_complete(main()) elapsed = time.time() - started",
"= (await result) rates_line = \", \".join( [f\"{rates[symbol]:7.03} {symbol}\" for",
"async def fetch_rates(session, place): return await get_rates(session, place) async def",
"= {rates_line}\") async def main(): async with aiohttp.ClientSession() as session:",
"symbol in SYMBOLS] ) print(f\"1 {base} = {rates_line}\") async def",
"def main(): async with aiohttp.ClientSession() as session: await asyncio.wait([ asyncio.create_task(present_result(fetch_rates(session,",
"asyncio.get_event_loop() loop.run_until_complete(main()) elapsed = time.time() - started print() print(f\"経過時間: {elapsed:.2f}s\")",
"rates = (await result) rates_line = \", \".join( [f\"{rates[symbol]:7.03} {symbol}\"",
"BASES ]) if __name__ == \"__main__\": started = time.time() loop",
"SYMBOLS] ) print(f\"1 {base} = {rates_line}\") async def main(): async",
"return await get_rates(session, place) async def present_result(result): base, rates =",
"print(f\"1 {base} = {rates_line}\") async def main(): async with aiohttp.ClientSession()",
"= time.time() loop = asyncio.get_event_loop() loop.run_until_complete(main()) elapsed = time.time() -",
"\"\"\" import asyncio import time import aiohttp from asyncrates import",
"'PLN', 'NOK', 'CZK') BASES = ('USD', 'EUR', 'PLN', 'NOK', 'CZK')",
"= ('USD', 'EUR', 'PLN', 'NOK', 'CZK') async def fetch_rates(session, place):"
] |
[
"replace_in_file(build_path + \"/conf/nginx.conf\", \"listen 80;\", \"listen 8080;\", ignoreifcontains=True) replace_in_file(build_path +",
"machine) msg = self.run_message.format(input=client_number, **locals()) self.log_run(msg) f.write(\"[run] \" + msg",
"env[\"CLIENT_MACHINE\"] logging.debug(\"Using remote client: %s\" % env[\"CLIENT_MACHINE\"]) else: ssh =",
"if self.config.input_type == \"test\": self.client_numbers = (1,) def per_benchmark_action(self, type_,",
"* from core.run import Runner class NginxPerf(Runner): \"\"\" Runs Nginx",
"client on local machine if env.get(\"CLIENT_MACHINE\"): ssh = \"ssh %s\"",
"pass f.write(\"===== stdout =====\\n\") for line in server.stdout: f.write(line.decode('utf-8')) f.write(\"=====",
"per_thread_action(self, type_, benchmark, args, thread_num): servercmd = \"{action} {exe} -g",
"-t {duration} -n {requests_num} -c {client_number} http://{myip}:8080/\".format( ab=self.ab, duration=self.duration, requests_num=self.requests_num,",
"% servercmd) # by default start client on local machine",
"build_path + '/sbin/' + benchmark build_benchmark( b=benchmark, t=type_, makefile=self.dirs['bench_src'], build_path=build_path",
"#!/usr/bin/env python from __future__ import print_function import logging import os",
"[socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0] with open(self.dirs[\"log_file\"], \"a\") as f: for",
"* self.num_runs * len(self.client_numbers) logging.info(\"Total runs: %d\" % self.num_benchmarks) def",
"per_benchmark_action(self, type_, benchmark, args): self.log_build(type_, benchmark) build_path = \"/\".join([self.dirs[\"build\"], type_])",
"benchmark, args, thread_num): servercmd = \"{action} {exe} -g \\\"daemon off;\\\"\".format(",
"9, 13, 17, 21, 25, 29] ab = \"ab\" duration",
"29] ab = \"ab\" duration = 20 # in seconds",
"ssh = \"ssh %s\" % env[\"CLIENT_MACHINE\"] logging.debug(\"Using remote client: %s\"",
"client_number in self.client_numbers: # start server my_check_output(\"pkill -9 nginx >",
"duration = 20 # in seconds requests_num = 1000000 #",
"server.stdout: f.write(line.decode('utf-8')) f.write(\"===== stderr =====\\n\") for line in server.stderr: f.write(line.decode('utf-8'))",
"* len(self.types) * self.num_runs * len(self.client_numbers) logging.info(\"Total runs: %d\" %",
") logging.debug(\"Server command: %s\" % servercmd) # by default start",
"=====\\n\" % str(server.poll())) try: os.killpg(server.pid, signal.SIGINT) except: pass f.write(\"===== stdout",
"Nginx \"\"\" name = \"nginx\" exp_name = \"nginx\" bench_suite =",
"+ benchmark build_benchmark( b=benchmark, t=type_, makefile=self.dirs['bench_src'], build_path=build_path ) # generate",
"client (use CLIENT_MACHINE env var to specify remote client)\") myip",
"5, 9, 13, 17, 21, 25, 29] ab = \"ab\"",
"\"/conf/nginx.conf\", \"worker_processes 1;\", \"worker_processes auto;\", ignoreifcontains=True) def per_thread_action(self, type_, benchmark,",
"1;\", \"worker_processes auto;\", ignoreifcontains=True) def per_thread_action(self, type_, benchmark, args, thread_num):",
"if env.get(\"CLIENT_MACHINE\"): ssh = \"ssh %s\" % env[\"CLIENT_MACHINE\"] logging.debug(\"Using remote",
"/dev/null || true\") # for sanity sleep(1) server = Popen(servercmd,",
"=====\\n\") f.write(out) # log and stop server f.write(\"===== return code",
"my_check_output(\"{ssh} {ab} -k -t {duration} -n {requests_num} -c {client_number} http://{myip}:8080/\".format(",
"start client on local machine if env.get(\"CLIENT_MACHINE\"): ssh = \"ssh",
"%s =====\\n\" % str(server.poll())) try: os.killpg(server.pid, signal.SIGINT) except: pass f.write(\"=====",
"(1,) def per_benchmark_action(self, type_, benchmark, args): self.log_build(type_, benchmark) build_path =",
"f.write(\"===== return code is %s =====\\n\" % str(server.poll())) try: os.killpg(server.pid,",
"f.write(\"===== stderr =====\\n\") for line in server.stderr: f.write(line.decode('utf-8')) sleep(1) def",
"\" + msg + \"\\n\") out = my_check_output(\"{ssh} {ab} -k",
"-g \\\"daemon off;\\\"\".format( action=self.action, exe=self.current_exe, ) logging.debug(\"Server command: %s\" %",
"[1, 5, 9, 13, 17, 21, 25, 29] ab =",
"80;\", \"listen 8080;\", ignoreifcontains=True) replace_in_file(build_path + \"/conf/nginx.conf\", \"worker_processes 1;\", \"worker_processes",
"% str(server.poll())) try: os.killpg(server.pid, signal.SIGINT) except: pass f.write(\"===== stdout =====\\n\")",
"start server my_check_output(\"pkill -9 nginx > /dev/null || true\") #",
"time import sleep from subprocess import Popen, PIPE import socket",
"server my_check_output(\"pkill -9 nginx > /dev/null || true\") # for",
"f.write(line.decode('utf-8')) sleep(1) def set_logging(self): self.num_benchmarks = len(self.benchmarks) * len(self.types) *",
"= \"{action} {exe} -g \\\"daemon off;\\\"\".format( action=self.action, exe=self.current_exe, ) logging.debug(\"Server",
"self.num_runs * len(self.client_numbers) logging.info(\"Total runs: %d\" % self.num_benchmarks) def main(benchmark_name=None):",
"f.write(out) # log and stop server f.write(\"===== return code is",
"str(server.poll())) try: os.killpg(server.pid, signal.SIGINT) except: pass f.write(\"===== stdout =====\\n\") for",
"client_numbers = [1, 5, 9, 13, 17, 21, 25, 29]",
"preexec_fn=os.setsid) sleep(1) # start client (possibly on another machine) msg",
"# some huge number so we always take 20 seconds",
"= False benchmarks = {\"nginx\": \"\"} test_benchmarks = {\"nginx\": \"\"}",
"class NginxPerf(Runner): \"\"\" Runs Nginx \"\"\" name = \"nginx\" exp_name",
"from __future__ import print_function import logging import os import signal",
"self.log_build(type_, benchmark) build_path = \"/\".join([self.dirs[\"build\"], type_]) self.current_exe = build_path +",
"f.write(\"</body></html>\") # config Nginx replace_in_file(build_path + \"/conf/nginx.conf\", \"listen 80;\", \"listen",
"args): self.log_build(type_, benchmark) build_path = \"/\".join([self.dirs[\"build\"], type_]) self.current_exe = build_path",
"\"\"} test_benchmarks = {\"nginx\": \"\"} client_numbers = [1, 5, 9,",
"l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1],",
"10\") f.write(random_text) f.write(\"</body></html>\") # config Nginx replace_in_file(build_path + \"/conf/nginx.conf\", \"listen",
"Runner class NginxPerf(Runner): \"\"\" Runs Nginx \"\"\" name = \"nginx\"",
"f.write(\"===== client =====\\n\") f.write(out) # log and stop server f.write(\"=====",
"{client_number} http://{myip}:8080/\".format( ab=self.ab, duration=self.duration, requests_num=self.requests_num, **locals() )) f.write(\"===== client =====\\n\")",
"logging.debug(\"Using remote client: %s\" % env[\"CLIENT_MACHINE\"]) else: ssh = \"\"",
"print_function import logging import os import signal from time import",
"from time import sleep from subprocess import Popen, PIPE import",
"%s\" % env[\"CLIENT_MACHINE\"] logging.debug(\"Using remote client: %s\" % env[\"CLIENT_MACHINE\"]) else:",
"stderr=PIPE, preexec_fn=os.setsid) sleep(1) # start client (possibly on another machine)",
"requests_num = 1000000 # some huge number so we always",
"\"worker_processes auto;\", ignoreifcontains=True) def per_thread_action(self, type_, benchmark, args, thread_num): servercmd",
"in self.client_numbers: # start server my_check_output(\"pkill -9 nginx > /dev/null",
"subprocess import Popen, PIPE import socket from core.common_functions import *",
"from core.run import Runner class NginxPerf(Runner): \"\"\" Runs Nginx \"\"\"",
"= {\"nginx\": \"\"} test_benchmarks = {\"nginx\": \"\"} client_numbers = [1,",
"'/sbin/' + benchmark build_benchmark( b=benchmark, t=type_, makefile=self.dirs['bench_src'], build_path=build_path ) #",
"else: ssh = \"\" logging.debug(\"Using local client (use CLIENT_MACHINE env",
"my_check_output(\"pkill -9 nginx > /dev/null || true\") # for sanity",
"= (1,) def per_benchmark_action(self, type_, benchmark, args): self.log_build(type_, benchmark) build_path",
"def set_logging(self): self.num_benchmarks = len(self.benchmarks) * len(self.types) * self.num_runs *",
"an input file with open(build_path + \"/html/index.html\", \"w\") as f:",
"specify remote client)\") myip = [l for l in ([ip",
"+ \"/conf/nginx.conf\", \"listen 80;\", \"listen 8080;\", ignoreifcontains=True) replace_in_file(build_path + \"/conf/nginx.conf\",",
"msg = self.run_message.format(input=client_number, **locals()) self.log_run(msg) f.write(\"[run] \" + msg +",
"always take 20 seconds def __init__(self, *args, **kwargs): super(NginxPerf, self).__init__(*args,",
"len(self.benchmarks) * len(self.types) * self.num_runs * len(self.client_numbers) logging.info(\"Total runs: %d\"",
"13, 17, 21, 25, 29] ab = \"ab\" duration =",
"remote client)\") myip = [l for l in ([ip for",
"benchmark) build_path = \"/\".join([self.dirs[\"build\"], type_]) self.current_exe = build_path + '/sbin/'",
"take 20 seconds def __init__(self, *args, **kwargs): super(NginxPerf, self).__init__(*args, **kwargs)",
"env[\"CLIENT_MACHINE\"]) else: ssh = \"\" logging.debug(\"Using local client (use CLIENT_MACHINE",
"\"\" logging.debug(\"Using local client (use CLIENT_MACHINE env var to specify",
"# start server my_check_output(\"pkill -9 nginx > /dev/null || true\")",
"= [1, 5, 9, 13, 17, 21, 25, 29] ab",
"= Popen(servercmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) sleep(1) # start client",
"\"/conf/nginx.conf\", \"listen 80;\", \"listen 8080;\", ignoreifcontains=True) replace_in_file(build_path + \"/conf/nginx.conf\", \"worker_processes",
"myip = [l for l in ([ip for ip in",
"ignoreifcontains=True) replace_in_file(build_path + \"/conf/nginx.conf\", \"worker_processes 1;\", \"worker_processes auto;\", ignoreifcontains=True) def",
"seconds requests_num = 1000000 # some huge number so we",
"os import signal from time import sleep from subprocess import",
"command: %s\" % servercmd) # by default start client on",
"ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]])",
"local machine if env.get(\"CLIENT_MACHINE\"): ssh = \"ssh %s\" % env[\"CLIENT_MACHINE\"]",
"stop server f.write(\"===== return code is %s =====\\n\" % str(server.poll()))",
"log and stop server f.write(\"===== return code is %s =====\\n\"",
"name = \"nginx\" exp_name = \"nginx\" bench_suite = False benchmarks",
"with open(build_path + \"/html/index.html\", \"w\") as f: f.write(\"<html><body><h1>It works!</h1>\") random_text",
"code is %s =====\\n\" % str(server.poll())) try: os.killpg(server.pid, signal.SIGINT) except:",
"var to specify remote client)\") myip = [l for l",
"% env[\"CLIENT_MACHINE\"]) else: ssh = \"\" logging.debug(\"Using local client (use",
"some huge number so we always take 20 seconds def",
"f.write(\"<html><body><h1>It works!</h1>\") random_text = my_check_output(\"lorem -p 10\") f.write(random_text) f.write(\"</body></html>\") #",
"on local machine if env.get(\"CLIENT_MACHINE\"): ssh = \"ssh %s\" %",
"|| true\") # for sanity sleep(1) server = Popen(servercmd, shell=True,",
"{ab} -k -t {duration} -n {requests_num} -c {client_number} http://{myip}:8080/\".format( ab=self.ab,",
"exe=self.current_exe, ) logging.debug(\"Server command: %s\" % servercmd) # by default",
"# in seconds requests_num = 1000000 # some huge number",
"{exe} -g \\\"daemon off;\\\"\".format( action=self.action, exe=self.current_exe, ) logging.debug(\"Server command: %s\"",
"-k -t {duration} -n {requests_num} -c {client_number} http://{myip}:8080/\".format( ab=self.ab, duration=self.duration,",
"as f: f.write(\"<html><body><h1>It works!</h1>\") random_text = my_check_output(\"lorem -p 10\") f.write(random_text)",
"replace_in_file(build_path + \"/conf/nginx.conf\", \"worker_processes 1;\", \"worker_processes auto;\", ignoreifcontains=True) def per_thread_action(self,",
"in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for",
"t=type_, makefile=self.dirs['bench_src'], build_path=build_path ) # generate an input file with",
"msg + \"\\n\") out = my_check_output(\"{ssh} {ab} -k -t {duration}",
"type_, benchmark, args): self.log_build(type_, benchmark) build_path = \"/\".join([self.dirs[\"build\"], type_]) self.current_exe",
"benchmark, args): self.log_build(type_, benchmark) build_path = \"/\".join([self.dirs[\"build\"], type_]) self.current_exe =",
"= build_path + '/sbin/' + benchmark build_benchmark( b=benchmark, t=type_, makefile=self.dirs['bench_src'],",
"Runs Nginx \"\"\" name = \"nginx\" exp_name = \"nginx\" bench_suite",
"import sleep from subprocess import Popen, PIPE import socket from",
")) f.write(\"===== client =====\\n\") f.write(out) # log and stop server",
"true\") # for sanity sleep(1) server = Popen(servercmd, shell=True, stdout=PIPE,",
"file with open(build_path + \"/html/index.html\", \"w\") as f: f.write(\"<html><body><h1>It works!</h1>\")",
"socket.SOCK_DGRAM)]][0][1]]) if l][0][0] with open(self.dirs[\"log_file\"], \"a\") as f: for client_number",
"logging.debug(\"Using local client (use CLIENT_MACHINE env var to specify remote",
"%s\" % env[\"CLIENT_MACHINE\"]) else: ssh = \"\" logging.debug(\"Using local client",
"try: os.killpg(server.pid, signal.SIGINT) except: pass f.write(\"===== stdout =====\\n\") for line",
"**kwargs): super(NginxPerf, self).__init__(*args, **kwargs) if self.config.input_type == \"test\": self.client_numbers =",
"> /dev/null || true\") # for sanity sleep(1) server =",
"local client (use CLIENT_MACHINE env var to specify remote client)\")",
"self.log_run(msg) f.write(\"[run] \" + msg + \"\\n\") out = my_check_output(\"{ssh}",
"\"\"} client_numbers = [1, 5, 9, 13, 17, 21, 25,",
"False benchmarks = {\"nginx\": \"\"} test_benchmarks = {\"nginx\": \"\"} client_numbers",
"(use CLIENT_MACHINE env var to specify remote client)\") myip =",
"\"nginx\" exp_name = \"nginx\" bench_suite = False benchmarks = {\"nginx\":",
"is %s =====\\n\" % str(server.poll())) try: os.killpg(server.pid, signal.SIGINT) except: pass",
"core.common_functions import * from core.run import Runner class NginxPerf(Runner): \"\"\"",
"for line in server.stdout: f.write(line.decode('utf-8')) f.write(\"===== stderr =====\\n\") for line",
"by default start client on local machine if env.get(\"CLIENT_MACHINE\"): ssh",
"+ \"\\n\") out = my_check_output(\"{ssh} {ab} -k -t {duration} -n",
"super(NginxPerf, self).__init__(*args, **kwargs) if self.config.input_type == \"test\": self.client_numbers = (1,)",
"import Popen, PIPE import socket from core.common_functions import * from",
"-p 10\") f.write(random_text) f.write(\"</body></html>\") # config Nginx replace_in_file(build_path + \"/conf/nginx.conf\",",
"20 # in seconds requests_num = 1000000 # some huge",
"if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in",
"bench_suite = False benchmarks = {\"nginx\": \"\"} test_benchmarks = {\"nginx\":",
"requests_num=self.requests_num, **locals() )) f.write(\"===== client =====\\n\") f.write(out) # log and",
"self).__init__(*args, **kwargs) if self.config.input_type == \"test\": self.client_numbers = (1,) def",
"nginx > /dev/null || true\") # for sanity sleep(1) server",
"f: f.write(\"<html><body><h1>It works!</h1>\") random_text = my_check_output(\"lorem -p 10\") f.write(random_text) f.write(\"</body></html>\")",
"Nginx replace_in_file(build_path + \"/conf/nginx.conf\", \"listen 80;\", \"listen 8080;\", ignoreifcontains=True) replace_in_file(build_path",
"http://{myip}:8080/\".format( ab=self.ab, duration=self.duration, requests_num=self.requests_num, **locals() )) f.write(\"===== client =====\\n\") f.write(out)",
"\"a\") as f: for client_number in self.client_numbers: # start server",
"25, 29] ab = \"ab\" duration = 20 # in",
"**kwargs) if self.config.input_type == \"test\": self.client_numbers = (1,) def per_benchmark_action(self,",
"with open(self.dirs[\"log_file\"], \"a\") as f: for client_number in self.client_numbers: #",
"huge number so we always take 20 seconds def __init__(self,",
"[[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if",
"% env[\"CLIENT_MACHINE\"] logging.debug(\"Using remote client: %s\" % env[\"CLIENT_MACHINE\"]) else: ssh",
"socket from core.common_functions import * from core.run import Runner class",
"generate an input file with open(build_path + \"/html/index.html\", \"w\") as",
"+ \"/html/index.html\", \"w\") as f: f.write(\"<html><body><h1>It works!</h1>\") random_text = my_check_output(\"lorem",
"config Nginx replace_in_file(build_path + \"/conf/nginx.conf\", \"listen 80;\", \"listen 8080;\", ignoreifcontains=True)",
"= len(self.benchmarks) * len(self.types) * self.num_runs * len(self.client_numbers) logging.info(\"Total runs:",
"remote client: %s\" % env[\"CLIENT_MACHINE\"]) else: ssh = \"\" logging.debug(\"Using",
"socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s",
"ab = \"ab\" duration = 20 # in seconds requests_num",
"machine if env.get(\"CLIENT_MACHINE\"): ssh = \"ssh %s\" % env[\"CLIENT_MACHINE\"] logging.debug(\"Using",
"exp_name = \"nginx\" bench_suite = False benchmarks = {\"nginx\": \"\"}",
"8080;\", ignoreifcontains=True) replace_in_file(build_path + \"/conf/nginx.conf\", \"worker_processes 1;\", \"worker_processes auto;\", ignoreifcontains=True)",
"def per_benchmark_action(self, type_, benchmark, args): self.log_build(type_, benchmark) build_path = \"/\".join([self.dirs[\"build\"],",
"= \"\" logging.debug(\"Using local client (use CLIENT_MACHINE env var to",
"\"/html/index.html\", \"w\") as f: f.write(\"<html><body><h1>It works!</h1>\") random_text = my_check_output(\"lorem -p",
"ab=self.ab, duration=self.duration, requests_num=self.requests_num, **locals() )) f.write(\"===== client =====\\n\") f.write(out) #",
"in server.stderr: f.write(line.decode('utf-8')) sleep(1) def set_logging(self): self.num_benchmarks = len(self.benchmarks) *",
"{\"nginx\": \"\"} client_numbers = [1, 5, 9, 13, 17, 21,",
"signal.SIGINT) except: pass f.write(\"===== stdout =====\\n\") for line in server.stdout:",
"53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]",
"21, 25, 29] ab = \"ab\" duration = 20 #",
"makefile=self.dirs['bench_src'], build_path=build_path ) # generate an input file with open(build_path",
"build_path = \"/\".join([self.dirs[\"build\"], type_]) self.current_exe = build_path + '/sbin/' +",
"and stop server f.write(\"===== return code is %s =====\\n\" %",
"auto;\", ignoreifcontains=True) def per_thread_action(self, type_, benchmark, args, thread_num): servercmd =",
"=====\\n\") for line in server.stderr: f.write(line.decode('utf-8')) sleep(1) def set_logging(self): self.num_benchmarks",
"= [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]",
"NginxPerf(Runner): \"\"\" Runs Nginx \"\"\" name = \"nginx\" exp_name =",
"import signal from time import sleep from subprocess import Popen,",
"\"\"\" name = \"nginx\" exp_name = \"nginx\" bench_suite = False",
"f: for client_number in self.client_numbers: # start server my_check_output(\"pkill -9",
"# log and stop server f.write(\"===== return code is %s",
"thread_num): servercmd = \"{action} {exe} -g \\\"daemon off;\\\"\".format( action=self.action, exe=self.current_exe,",
"\"{action} {exe} -g \\\"daemon off;\\\"\".format( action=self.action, exe=self.current_exe, ) logging.debug(\"Server command:",
"(possibly on another machine) msg = self.run_message.format(input=client_number, **locals()) self.log_run(msg) f.write(\"[run]",
"len(self.client_numbers) logging.info(\"Total runs: %d\" % self.num_benchmarks) def main(benchmark_name=None): runner =",
"servercmd = \"{action} {exe} -g \\\"daemon off;\\\"\".format( action=self.action, exe=self.current_exe, )",
"stdout =====\\n\") for line in server.stdout: f.write(line.decode('utf-8')) f.write(\"===== stderr =====\\n\")",
"%s\" % servercmd) # by default start client on local",
"build_benchmark( b=benchmark, t=type_, makefile=self.dirs['bench_src'], build_path=build_path ) # generate an input",
"\"worker_processes 1;\", \"worker_processes auto;\", ignoreifcontains=True) def per_thread_action(self, type_, benchmark, args,",
"s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0] with",
"1000000 # some huge number so we always take 20",
"+ msg + \"\\n\") out = my_check_output(\"{ssh} {ab} -k -t",
"{requests_num} -c {client_number} http://{myip}:8080/\".format( ab=self.ab, duration=self.duration, requests_num=self.requests_num, **locals() )) f.write(\"=====",
"# for sanity sleep(1) server = Popen(servercmd, shell=True, stdout=PIPE, stderr=PIPE,",
"== \"test\": self.client_numbers = (1,) def per_benchmark_action(self, type_, benchmark, args):",
"ignoreifcontains=True) def per_thread_action(self, type_, benchmark, args, thread_num): servercmd = \"{action}",
"\"\\n\") out = my_check_output(\"{ssh} {ab} -k -t {duration} -n {requests_num}",
"ssh = \"\" logging.debug(\"Using local client (use CLIENT_MACHINE env var",
"type_, benchmark, args, thread_num): servercmd = \"{action} {exe} -g \\\"daemon",
"import Runner class NginxPerf(Runner): \"\"\" Runs Nginx \"\"\" name =",
"env.get(\"CLIENT_MACHINE\"): ssh = \"ssh %s\" % env[\"CLIENT_MACHINE\"] logging.debug(\"Using remote client:",
"sleep from subprocess import Popen, PIPE import socket from core.common_functions",
"random_text = my_check_output(\"lorem -p 10\") f.write(random_text) f.write(\"</body></html>\") # config Nginx",
"not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET,",
"= \"nginx\" bench_suite = False benchmarks = {\"nginx\": \"\"} test_benchmarks",
"f.write(\"===== stdout =====\\n\") for line in server.stdout: f.write(line.decode('utf-8')) f.write(\"===== stderr",
"runs: %d\" % self.num_benchmarks) def main(benchmark_name=None): runner = NginxPerf() runner.main()",
"= 1000000 # some huge number so we always take",
"for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0] with open(self.dirs[\"log_file\"], \"a\")",
"b=benchmark, t=type_, makefile=self.dirs['bench_src'], build_path=build_path ) # generate an input file",
"logging.info(\"Total runs: %d\" % self.num_benchmarks) def main(benchmark_name=None): runner = NginxPerf()",
"my_check_output(\"lorem -p 10\") f.write(random_text) f.write(\"</body></html>\") # config Nginx replace_in_file(build_path +",
"\\\"daemon off;\\\"\".format( action=self.action, exe=self.current_exe, ) logging.debug(\"Server command: %s\" % servercmd)",
"\"nginx\" bench_suite = False benchmarks = {\"nginx\": \"\"} test_benchmarks =",
"benchmark build_benchmark( b=benchmark, t=type_, makefile=self.dirs['bench_src'], build_path=build_path ) # generate an",
"import print_function import logging import os import signal from time",
"\"/\".join([self.dirs[\"build\"], type_]) self.current_exe = build_path + '/sbin/' + benchmark build_benchmark(",
"__init__(self, *args, **kwargs): super(NginxPerf, self).__init__(*args, **kwargs) if self.config.input_type == \"test\":",
"action=self.action, exe=self.current_exe, ) logging.debug(\"Server command: %s\" % servercmd) # by",
"__future__ import print_function import logging import os import signal from",
"# by default start client on local machine if env.get(\"CLIENT_MACHINE\"):",
"signal from time import sleep from subprocess import Popen, PIPE",
"we always take 20 seconds def __init__(self, *args, **kwargs): super(NginxPerf,",
"if l][0][0] with open(self.dirs[\"log_file\"], \"a\") as f: for client_number in",
"server.stderr: f.write(line.decode('utf-8')) sleep(1) def set_logging(self): self.num_benchmarks = len(self.benchmarks) * len(self.types)",
"in server.stdout: f.write(line.decode('utf-8')) f.write(\"===== stderr =====\\n\") for line in server.stderr:",
"python from __future__ import print_function import logging import os import",
"open(build_path + \"/html/index.html\", \"w\") as f: f.write(\"<html><body><h1>It works!</h1>\") random_text =",
"line in server.stderr: f.write(line.decode('utf-8')) sleep(1) def set_logging(self): self.num_benchmarks = len(self.benchmarks)",
"Popen(servercmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) sleep(1) # start client (possibly",
"* len(self.client_numbers) logging.info(\"Total runs: %d\" % self.num_benchmarks) def main(benchmark_name=None): runner",
"server = Popen(servercmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) sleep(1) # start",
"from subprocess import Popen, PIPE import socket from core.common_functions import",
"\"test\": self.client_numbers = (1,) def per_benchmark_action(self, type_, benchmark, args): self.log_build(type_,",
"env var to specify remote client)\") myip = [l for",
"import os import signal from time import sleep from subprocess",
"s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0] with open(self.dirs[\"log_file\"], \"a\") as",
"seconds def __init__(self, *args, **kwargs): super(NginxPerf, self).__init__(*args, **kwargs) if self.config.input_type",
"start client (possibly on another machine) msg = self.run_message.format(input=client_number, **locals())",
"another machine) msg = self.run_message.format(input=client_number, **locals()) self.log_run(msg) f.write(\"[run] \" +",
"for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0],",
"= my_check_output(\"lorem -p 10\") f.write(random_text) f.write(\"</body></html>\") # config Nginx replace_in_file(build_path",
"ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close())",
"in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8',",
"= \"ab\" duration = 20 # in seconds requests_num =",
"+ \"/conf/nginx.conf\", \"worker_processes 1;\", \"worker_processes auto;\", ignoreifcontains=True) def per_thread_action(self, type_,",
"as f: for client_number in self.client_numbers: # start server my_check_output(\"pkill",
"server f.write(\"===== return code is %s =====\\n\" % str(server.poll())) try:",
"in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0] with open(self.dirs[\"log_file\"], \"a\") as f:",
"sleep(1) server = Popen(servercmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) sleep(1) #",
"-n {requests_num} -c {client_number} http://{myip}:8080/\".format( ab=self.ab, duration=self.duration, requests_num=self.requests_num, **locals() ))",
"in seconds requests_num = 1000000 # some huge number so",
"= 20 # in seconds requests_num = 1000000 # some",
"default start client on local machine if env.get(\"CLIENT_MACHINE\"): ssh =",
"on another machine) msg = self.run_message.format(input=client_number, **locals()) self.log_run(msg) f.write(\"[run] \"",
"f.write(\"[run] \" + msg + \"\\n\") out = my_check_output(\"{ssh} {ab}",
"open(self.dirs[\"log_file\"], \"a\") as f: for client_number in self.client_numbers: # start",
"= {\"nginx\": \"\"} client_numbers = [1, 5, 9, 13, 17,",
"set_logging(self): self.num_benchmarks = len(self.benchmarks) * len(self.types) * self.num_runs * len(self.client_numbers)",
"l][0][0] with open(self.dirs[\"log_file\"], \"a\") as f: for client_number in self.client_numbers:",
"for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not",
"\"listen 8080;\", ignoreifcontains=True) replace_in_file(build_path + \"/conf/nginx.conf\", \"worker_processes 1;\", \"worker_processes auto;\",",
"self.num_benchmarks = len(self.benchmarks) * len(self.types) * self.num_runs * len(self.client_numbers) logging.info(\"Total",
"f.write(random_text) f.write(\"</body></html>\") # config Nginx replace_in_file(build_path + \"/conf/nginx.conf\", \"listen 80;\",",
"works!</h1>\") random_text = my_check_output(\"lorem -p 10\") f.write(random_text) f.write(\"</body></html>\") # config",
"so we always take 20 seconds def __init__(self, *args, **kwargs):",
"type_]) self.current_exe = build_path + '/sbin/' + benchmark build_benchmark( b=benchmark,",
"s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0] with open(self.dirs[\"log_file\"],",
"stderr =====\\n\") for line in server.stderr: f.write(line.decode('utf-8')) sleep(1) def set_logging(self):",
"benchmarks = {\"nginx\": \"\"} test_benchmarks = {\"nginx\": \"\"} client_numbers =",
"**locals()) self.log_run(msg) f.write(\"[run] \" + msg + \"\\n\") out =",
"def per_thread_action(self, type_, benchmark, args, thread_num): servercmd = \"{action} {exe}",
"CLIENT_MACHINE env var to specify remote client)\") myip = [l",
"logging import os import signal from time import sleep from",
"return code is %s =====\\n\" % str(server.poll())) try: os.killpg(server.pid, signal.SIGINT)",
"self.config.input_type == \"test\": self.client_numbers = (1,) def per_benchmark_action(self, type_, benchmark,",
"-9 nginx > /dev/null || true\") # for sanity sleep(1)",
"self.client_numbers = (1,) def per_benchmark_action(self, type_, benchmark, args): self.log_build(type_, benchmark)",
"duration=self.duration, requests_num=self.requests_num, **locals() )) f.write(\"===== client =====\\n\") f.write(out) # log",
"*args, **kwargs): super(NginxPerf, self).__init__(*args, **kwargs) if self.config.input_type == \"test\": self.client_numbers",
"# generate an input file with open(build_path + \"/html/index.html\", \"w\")",
"number so we always take 20 seconds def __init__(self, *args,",
"\"w\") as f: f.write(\"<html><body><h1>It works!</h1>\") random_text = my_check_output(\"lorem -p 10\")",
"self.run_message.format(input=client_number, **locals()) self.log_run(msg) f.write(\"[run] \" + msg + \"\\n\") out",
"# start client (possibly on another machine) msg = self.run_message.format(input=client_number,",
"test_benchmarks = {\"nginx\": \"\"} client_numbers = [1, 5, 9, 13,",
"# config Nginx replace_in_file(build_path + \"/conf/nginx.conf\", \"listen 80;\", \"listen 8080;\",",
"client)\") myip = [l for l in ([ip for ip",
"off;\\\"\".format( action=self.action, exe=self.current_exe, ) logging.debug(\"Server command: %s\" % servercmd) #",
"core.run import Runner class NginxPerf(Runner): \"\"\" Runs Nginx \"\"\" name",
"= \"ssh %s\" % env[\"CLIENT_MACHINE\"] logging.debug(\"Using remote client: %s\" %",
"out = my_check_output(\"{ssh} {ab} -k -t {duration} -n {requests_num} -c",
"**locals() )) f.write(\"===== client =====\\n\") f.write(out) # log and stop",
"import logging import os import signal from time import sleep",
"input file with open(build_path + \"/html/index.html\", \"w\") as f: f.write(\"<html><body><h1>It",
"f.write(line.decode('utf-8')) f.write(\"===== stderr =====\\n\") for line in server.stderr: f.write(line.decode('utf-8')) sleep(1)",
"\"ssh %s\" % env[\"CLIENT_MACHINE\"] logging.debug(\"Using remote client: %s\" % env[\"CLIENT_MACHINE\"])",
"= \"/\".join([self.dirs[\"build\"], type_]) self.current_exe = build_path + '/sbin/' + benchmark",
"\"listen 80;\", \"listen 8080;\", ignoreifcontains=True) replace_in_file(build_path + \"/conf/nginx.conf\", \"worker_processes 1;\",",
"{duration} -n {requests_num} -c {client_number} http://{myip}:8080/\".format( ab=self.ab, duration=self.duration, requests_num=self.requests_num, **locals()",
"from core.common_functions import * from core.run import Runner class NginxPerf(Runner):",
"for line in server.stderr: f.write(line.decode('utf-8')) sleep(1) def set_logging(self): self.num_benchmarks =",
"client (possibly on another machine) msg = self.run_message.format(input=client_number, **locals()) self.log_run(msg)",
"line in server.stdout: f.write(line.decode('utf-8')) f.write(\"===== stderr =====\\n\") for line in",
"len(self.types) * self.num_runs * len(self.client_numbers) logging.info(\"Total runs: %d\" % self.num_benchmarks)",
"import * from core.run import Runner class NginxPerf(Runner): \"\"\" Runs",
"shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) sleep(1) # start client (possibly on",
") # generate an input file with open(build_path + \"/html/index.html\",",
"sleep(1) def set_logging(self): self.num_benchmarks = len(self.benchmarks) * len(self.types) * self.num_runs",
"stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) sleep(1) # start client (possibly on another",
"for sanity sleep(1) server = Popen(servercmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid)",
"\"\"\" Runs Nginx \"\"\" name = \"nginx\" exp_name = \"nginx\"",
"[l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if",
"client =====\\n\") f.write(out) # log and stop server f.write(\"===== return",
"=====\\n\") for line in server.stdout: f.write(line.decode('utf-8')) f.write(\"===== stderr =====\\n\") for",
"def __init__(self, *args, **kwargs): super(NginxPerf, self).__init__(*args, **kwargs) if self.config.input_type ==",
"import socket from core.common_functions import * from core.run import Runner",
"Popen, PIPE import socket from core.common_functions import * from core.run",
"([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)),",
"for client_number in self.client_numbers: # start server my_check_output(\"pkill -9 nginx",
"-c {client_number} http://{myip}:8080/\".format( ab=self.ab, duration=self.duration, requests_num=self.requests_num, **locals() )) f.write(\"===== client",
"self.current_exe = build_path + '/sbin/' + benchmark build_benchmark( b=benchmark, t=type_,",
"client: %s\" % env[\"CLIENT_MACHINE\"]) else: ssh = \"\" logging.debug(\"Using local",
"\"ab\" duration = 20 # in seconds requests_num = 1000000",
"sanity sleep(1) server = Popen(servercmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) sleep(1)",
"args, thread_num): servercmd = \"{action} {exe} -g \\\"daemon off;\\\"\".format( action=self.action,",
"PIPE import socket from core.common_functions import * from core.run import",
"to specify remote client)\") myip = [l for l in",
"= my_check_output(\"{ssh} {ab} -k -t {duration} -n {requests_num} -c {client_number}",
"= \"nginx\" exp_name = \"nginx\" bench_suite = False benchmarks =",
"17, 21, 25, 29] ab = \"ab\" duration = 20",
"= self.run_message.format(input=client_number, **locals()) self.log_run(msg) f.write(\"[run] \" + msg + \"\\n\")",
"{\"nginx\": \"\"} test_benchmarks = {\"nginx\": \"\"} client_numbers = [1, 5,",
"+ '/sbin/' + benchmark build_benchmark( b=benchmark, t=type_, makefile=self.dirs['bench_src'], build_path=build_path )",
"logging.debug(\"Server command: %s\" % servercmd) # by default start client",
"servercmd) # by default start client on local machine if",
"self.client_numbers: # start server my_check_output(\"pkill -9 nginx > /dev/null ||",
"build_path=build_path ) # generate an input file with open(build_path +",
"sleep(1) # start client (possibly on another machine) msg =",
"except: pass f.write(\"===== stdout =====\\n\") for line in server.stdout: f.write(line.decode('utf-8'))",
"os.killpg(server.pid, signal.SIGINT) except: pass f.write(\"===== stdout =====\\n\") for line in",
"20 seconds def __init__(self, *args, **kwargs): super(NginxPerf, self).__init__(*args, **kwargs) if"
] |
[
"NoFieldsSample(BaseDocument): pass def setUp(self): super(BaseDocumentNoFieldsTest, self).setUp() self.no_fields_sample = self.NoFieldsSample() def",
"super(BaseDocumentNoFieldsTest, self).setUp() self.no_fields_sample = self.NoFieldsSample() def test_get_fields(self): self.assertEqual([], self.no_fields_sample.fields) def",
"def test_get_errors(self): self.assertEqual(0, self.no_fields_sample.errors.count) def test_valid(self): self.assertEqual(True, self.no_fields_sample.valid) def test_get_field_values(self):",
"= self.NoFieldsSample() def test_get_fields(self): self.assertEqual([], self.no_fields_sample.fields) def test_get_errors(self): self.assertEqual(0, self.no_fields_sample.errors.count)",
"self.assertEqual([], self.no_fields_sample.fields) def test_get_errors(self): self.assertEqual(0, self.no_fields_sample.errors.count) def test_valid(self): self.assertEqual(True, self.no_fields_sample.valid)",
"test_get_errors(self): self.assertEqual(0, self.no_fields_sample.errors.count) def test_valid(self): self.assertEqual(True, self.no_fields_sample.valid) def test_get_field_values(self): self.assertEqual({},",
"self.NoFieldsSample() def test_get_fields(self): self.assertEqual([], self.no_fields_sample.fields) def test_get_errors(self): self.assertEqual(0, self.no_fields_sample.errors.count) def",
"def setUp(self): super(BaseDocumentNoFieldsTest, self).setUp() self.no_fields_sample = self.NoFieldsSample() def test_get_fields(self): self.assertEqual([],",
"-*- import unittest from tavi.base.documents import BaseDocument class BaseDocumentNoFieldsTest(unittest.TestCase): class",
"class BaseDocumentNoFieldsTest(unittest.TestCase): class NoFieldsSample(BaseDocument): pass def setUp(self): super(BaseDocumentNoFieldsTest, self).setUp() self.no_fields_sample",
"class NoFieldsSample(BaseDocument): pass def setUp(self): super(BaseDocumentNoFieldsTest, self).setUp() self.no_fields_sample = self.NoFieldsSample()",
"<gh_stars>0 # -*- coding: utf-8 -*- import unittest from tavi.base.documents",
"self.assertEqual(0, self.no_fields_sample.errors.count) def test_valid(self): self.assertEqual(True, self.no_fields_sample.valid) def test_get_field_values(self): self.assertEqual({}, self.no_fields_sample.field_values)",
"-*- coding: utf-8 -*- import unittest from tavi.base.documents import BaseDocument",
"BaseDocument class BaseDocumentNoFieldsTest(unittest.TestCase): class NoFieldsSample(BaseDocument): pass def setUp(self): super(BaseDocumentNoFieldsTest, self).setUp()",
"import unittest from tavi.base.documents import BaseDocument class BaseDocumentNoFieldsTest(unittest.TestCase): class NoFieldsSample(BaseDocument):",
"utf-8 -*- import unittest from tavi.base.documents import BaseDocument class BaseDocumentNoFieldsTest(unittest.TestCase):",
"BaseDocumentNoFieldsTest(unittest.TestCase): class NoFieldsSample(BaseDocument): pass def setUp(self): super(BaseDocumentNoFieldsTest, self).setUp() self.no_fields_sample =",
"unittest from tavi.base.documents import BaseDocument class BaseDocumentNoFieldsTest(unittest.TestCase): class NoFieldsSample(BaseDocument): pass",
"def test_get_fields(self): self.assertEqual([], self.no_fields_sample.fields) def test_get_errors(self): self.assertEqual(0, self.no_fields_sample.errors.count) def test_valid(self):",
"import BaseDocument class BaseDocumentNoFieldsTest(unittest.TestCase): class NoFieldsSample(BaseDocument): pass def setUp(self): super(BaseDocumentNoFieldsTest,",
"test_get_fields(self): self.assertEqual([], self.no_fields_sample.fields) def test_get_errors(self): self.assertEqual(0, self.no_fields_sample.errors.count) def test_valid(self): self.assertEqual(True,",
"self.no_fields_sample.fields) def test_get_errors(self): self.assertEqual(0, self.no_fields_sample.errors.count) def test_valid(self): self.assertEqual(True, self.no_fields_sample.valid) def",
"coding: utf-8 -*- import unittest from tavi.base.documents import BaseDocument class",
"tavi.base.documents import BaseDocument class BaseDocumentNoFieldsTest(unittest.TestCase): class NoFieldsSample(BaseDocument): pass def setUp(self):",
"setUp(self): super(BaseDocumentNoFieldsTest, self).setUp() self.no_fields_sample = self.NoFieldsSample() def test_get_fields(self): self.assertEqual([], self.no_fields_sample.fields)",
"self).setUp() self.no_fields_sample = self.NoFieldsSample() def test_get_fields(self): self.assertEqual([], self.no_fields_sample.fields) def test_get_errors(self):",
"pass def setUp(self): super(BaseDocumentNoFieldsTest, self).setUp() self.no_fields_sample = self.NoFieldsSample() def test_get_fields(self):",
"# -*- coding: utf-8 -*- import unittest from tavi.base.documents import",
"from tavi.base.documents import BaseDocument class BaseDocumentNoFieldsTest(unittest.TestCase): class NoFieldsSample(BaseDocument): pass def",
"self.no_fields_sample = self.NoFieldsSample() def test_get_fields(self): self.assertEqual([], self.no_fields_sample.fields) def test_get_errors(self): self.assertEqual(0,"
] |
[
"3\" group and 2000 moves to the \"pad 4\" group!",
"the seqparse module.\"\"\" _test_ext = \"exr\" _test_file_name = \"TEST_DIR\" _test_root",
"is os.sep): # test_dir/TEST_DIR.5-8.exr # test_dir/TEST_DIR.008-010,012,114,199.exr # test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr mock_api_call.return_value =",
"parser = get_parser() parser.scan_path(self._test_root) file_names = parser.singletons self.assertIn(self._test_root, file_names) self.assertEqual(self._test_root,",
"... frame_seq_output = \"0000-0004\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output, self._test_ext))",
"101] } input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) #",
"root=self._test_root) # Expected output frame sequences. Note how frames 114,",
"test_nested_sequences(self, mock_api_call): \"\"\"Seqparse: Test file sequence discovery in nested directories.\"\"\"",
"\".test.0001-0004,0006.py\"), os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 3) self.assertEqual(list(map(str, output)),",
"TestSeqparseModule class TestSeqparseModule(unittest.TestCase): \"\"\"Test file discovery on the seqparse module.\"\"\"",
"= os.path.join(self._test_root, input_file_seq) output_file_seq = \".\".join( (self._test_file_name, output_frame_seq, self._test_ext)) output_file_seq",
"def test_scan_options(self, mock_api_call): \"\"\"Seqparse: Make sure scan_options works as expected.\"\"\"",
"print(\" \", seq) print(\"\\n MAX LEVELS\\n ----------\") for max_levels in",
"\"TEST_DIR\" _test_root = \"test_dir\" _singletons = [\"singleton0.jpg\", \"singleton1.jpg\"] def setUp(self):",
"input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) mock_api_call.return_value = iter(input_entries)",
"Seqparse.output.\"\"\" file_path = os.path.join(self._test_root, self._test_file_name) chunk_in = FrameChunk(first=1, last=11, step=2,",
"test_dir/TEST_DIR.5-8.exr # test_dir/TEST_DIR.008-010,012,114,199.exr # test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr mock_api_call.return_value = iter(input_entries) parser =",
"str(expected)) fseq = FileSequence( name=file_path, ext=self._test_ext, frames=[1, 2, 3, 4,",
"# Expected outputs ... output = [os.path.join(self._test_root, x) for x",
"range from future.utils import lrange from . import (DirEntry, generate_entries,",
"mock_api_call.return_value = input_entries chunk_out = FrameChunk(first=2, last=10, step=2, pad=4) expected",
"= generate_entries( name=\"test\", ext=\"py\", frames=frames, root=self._test_root) input_entries.extend( generate_entries( name=\".test\", ext=\"py\",",
"} # Expected final output (where \"/\" is os.sep): #",
"input_file = os.path.join(self._test_root, input_file) # Expected outputs ... input_frame_seq =",
"print(\" input files: \", fseq) print(\" expected files:\", expected) print(\"",
"file_seq_output) input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) mock_api_call.return_value =",
"step=2, pad=4) fseq = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_in) input_entries =",
"[DirEntry(x) for x in fseq] mock_api_call.return_value = input_entries chunk_out =",
"of the sequences property. self.assertIn(self._test_root, data) self.assertEqual(len(data), 1) self.assertIn(self._test_file_name, data[self._test_root])",
"OUTPUT FILES\\n ------------\") for line in output: print(\" o\", line)",
"get_parser() parser.scan_options[\"all\"] = True parser.scan_path(self._test_root) output = list(parser.output()) expected =",
"print(\"\\n BAD SEQUENCES\\n -------------\") for frame_seq in bad_frame_seqs: print(' o",
"5 seqs = list(parser.output()) blurb = \" o min_levels ==",
"range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, max_levels=max_levels) expected_seqs =",
"x in fseq] mock_api_call.return_value = input_entries expected = FileSequence( name=file_path,",
"----------\") for max_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser()",
"name=file_path, ext=self._test_ext, frames=[5], pad=4) parser = get_parser() parser.scan_path(self._test_root) inverted =",
"parser.add_file(input_file_seq) parser.add_file(input_file) output = list(parser.output()) print(\"\\n OUTPUT FILES\\n ------------\") for",
"self._test_ext)) final_output = os.path.join(self._test_root, file_seq_output) input_entries = generate_entries( ext=self._test_ext, frames=frames,",
"= \"0000-0004\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output, self._test_ext)) final_output =",
"input_frame_seq = \"0000-0002,,0003-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq",
"mock_scandir_deep) from .. import (__version__, get_parser, get_sequence, get_version, invert, validate_frame_sequence)",
"Test simple file sequence discovery.\"\"\" frames = {4: [0, 1,",
"self.assertEqual(str(seq), \"0001-0007x2\") expected = FrameChunk(first=2, last=6, step=2, pad=4) inverted =",
"EXPECTED OUTPUT\\n ---------------\") print(\" o\", output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]),",
"(1, 2, 3, 4, 6)} input_entries = generate_entries( name=\"test\", ext=\"py\",",
"output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) input_frame_seq = \"0000-0002,,0003-0005\" input_file_seq",
"6)} input_entries = generate_entries( name=\"test\", ext=\"py\", frames=frames, root=self._test_root) input_entries.extend( generate_entries(",
"\"0001-0001x0\", \"0001-0003x3\", \"0001,0003\", \"0001,,0003\", \"0001-0010\", \"0001-0010x0\", \"0001-0011x2\", \"0001-0012x2\", \"0001-0005,0007-0010\", \"0001-0005x2,0007-0010\",",
"output = list(parser.output()) print(\"\\n OUTPUT FILES\\n ------------\") for line in",
"= list() for file_name in output: entries.append(DirEntry(file_name)) mock_api_call.return_value = iter(entries)",
"self.assertEqual(len(data[self._test_root]), 1) # Now check the file sequence itself. file_seq",
"of simple frame ranges.\"\"\" good_frame_seqs = [ \"0001\", \",0001\", \"0001,\",",
"pad=4) self.assertTrue(isinstance(seq, FrameSequence)) self.assertEqual(str(seq), \"0001-0007x2\") expected = FrameChunk(first=2, last=6, step=2,",
"self.assertEqual(len(file_names), 1) self.assertEqual( len(file_names[self._test_root]), len(self._singletons)) self.assertEqual( sorted(self._singletons), sorted(file_names[self._test_root])) # Check",
"file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_simple_sequence(self, mock_api_call): \"\"\"Seqparse:",
"sequence discovery on disk.\"\"\" # \"Future\" Libraries from __future__ import",
"3, 4]} # Expected outputs ... frame_seq_output = \"0000-0004\" file_seq_output",
"self._singletons] entries = list() for file_name in output: entries.append(DirEntry(file_name)) mock_api_call.return_value",
"SEQUENCES\\n -------------\") for frame_seq in bad_frame_seqs: print(' o {!r}'.format(frame_seq)) self.assertFalse(validate_frame_sequence(frame_seq))",
"8, 10, 12, 101] } input_entries = generate_entries( ext=self._test_ext, frames=frames,",
"file singleton discovery from disk location.\"\"\" # Expected outputs ...",
"if max_levels == -1: expected_seqs = 5 seqs = list(parser.output())",
"frames=frames, root=self._test_root)) input_entries.append( DirEntry(os.path.join(self._test_root, \"pony.py\"))) mock_api_call.return_value = input_entries parser =",
"parser output ... self.assertEqual(sorted(map(str, parser.output())), output) # Test seqs_only option",
"generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) # Expected output frame sequences.",
"\"0001-0001\", \"0001-0001x0\", \"0001-0003x3\", \"0001,0003\", \"0001,,0003\", \"0001-0010\", \"0001-0010x0\", \"0001-0011x2\", \"0001-0012x2\", \"0001-0005,0007-0010\",",
"for seq in seqs: print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\\n",
"o {!r} --> {!r}'.format(frame_seq, output)) self.assertTrue(output) print(\"\\n BAD SEQUENCES\\n -------------\")",
"# Expected outputs ... input_frame_seq = \"0000-0004\" output_frame_seq = \"0000-0005\"",
"\"pad 4\" group! output_seqs = { 1: \"5-8\", 3: \"008-010,012,114,199\",",
"list(parser.output(missing=True)) self.assertEqual(len(inverted), 1) print(\"\\n\\n SEQUENCE\\n --------\") print(\" input files: \",",
"SEQUENCE\\n --------\") print(\" input files: \", fseq) print(\" expected files:\",",
"min_levels if min_levels == -1: expected_seqs = 5 seqs =",
"Make sure scan_options works as expected.\"\"\" frames = {4: (1,",
"input_entries parser = get_parser() parser.scan_options[\"stat\"] = True parser.scan_path(self._test_root) output =",
"get_parser() parser.scan_path(self._test_root) for seq in parser.output(): print(\" \", seq) print(\"\\n",
"self.assertIn(self._test_root, file_names) self.assertEqual(self._test_root, file_names[self._test_root].path) self.assertEqual(len(file_names), 1) self.assertEqual( len(file_names[self._test_root]), len(self._singletons)) self.assertEqual(",
"in sorted(output_seqs): self.assertEqual(output_seqs[pad], str(file_seq[self._test_ext][pad])) @mock.patch(\"seqparse.seqparse.scandir\") def test_nested_sequences(self, mock_api_call): \"\"\"Seqparse: Test",
"last=11, step=2, pad=4) fseq = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_in) input_entries",
"expected_seqs = max_levels + 2 if max_levels == -1: expected_seqs",
"Expected outputs ... frame_seq_output = \"0001\" file_seq_output = \".\".join( (self._test_file_name,",
"\"0001-0012x2\", \"0001-0005,0007-0010\", \"0001-0005x2,0007-0010\", \"0001-0005,0007-0011x2\", \"0001-0005,0006,0008-0012x2\", \"0001,0003-0007,0009-0015x2\", \"3,1,5,7\", \"01-05,03-07\" ] bad_frame_seqs",
"__future__ import print_function # Standard Libraries import os import unittest",
"in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, min_levels=min_levels) expected_seqs",
"file_seq) self.assertEqual(len(file_seq), 1) self.assertTrue(4 in file_seq[self._test_ext]) self.assertEqual(len(file_seq[self._test_ext]), 1) # And",
"\"0001-0010x0\", \"0001-0011x2\", \"0001-0012x2\", \"0001-0005,0007-0010\", \"0001-0005x2,0007-0010\", \"0001-0005,0007-0011x2\", \"0001-0005,0006,0008-0012x2\", \"0001,0003-0007,0009-0015x2\", \"3,1,5,7\", \"01-05,03-07\"",
"= list(parser.output()) blurb = \" o max_levels == {:d}: {:d}",
"{:d} ({:d} expected) entries\" print(blurb.format(min_levels, len(seqs), expected_seqs)) for seq in",
"\"\"\"Seqparse: Make sure scan_options works as expected.\"\"\" frames = {4:",
"self.assertEqual(len(data), 1) self.assertIn(self._test_file_name, data[self._test_root]) self.assertEqual(len(data[self._test_root]), 1) # Now check the",
"frame_seq_output = \"0001\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output, self._test_ext)) final_output",
"discovery on disk.\"\"\" # \"Future\" Libraries from __future__ import print_function",
"print(\"\\n\\n SEQUENCES\\n ---------\") initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root) for seq",
"inverted = invert(seq) self.assertEqual(str(inverted), str(expected)) with self.assertRaises(TypeError): invert(get_parser()) self.assertEqual(get_version(), __version__)",
"# Check the structure of the sequences property. self.assertIn(self._test_root, data)",
"final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_complex_sequence(self, mock_api_call): \"\"\"Seqparse: Test complex file sequence",
"\"0000-0006,0008-0012x2,0101,2000\" } # Expected final output (where \"/\" is os.sep):",
"\"0001-0003x3\", \"0001,0003\", \"0001,,0003\", \"0001-0010\", \"0001-0010x0\", \"0001-0011x2\", \"0001-0012x2\", \"0001-0005,0007-0010\", \"0001-0005x2,0007-0010\", \"0001-0005,0007-0011x2\",",
"3, 4, 6], pad=4) input_entries = [DirEntry(x) for x in",
"ext=self._test_ext, frames=[1, 2, 3, 4, 6], pad=4) input_entries = [DirEntry(x)",
"file sequence discovery.\"\"\" frames = { 1: [5, 6, 7,",
"test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr mock_api_call.return_value = iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) final_output =",
"FrameChunk, FrameSequence ############################################################################### # class: TestSeqparseModule class TestSeqparseModule(unittest.TestCase): \"\"\"Test file",
"= FrameChunk(first=2, last=10, step=2, pad=4) expected = FileSequence( name=file_path, ext=self._test_ext,",
"parser.scan_path(self._test_root) output = list(parser.output()) expected = [ os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root,",
"_singletons = [\"singleton0.jpg\", \"singleton1.jpg\"] def setUp(self): \"\"\"Set up the test",
"\"pony.py\") ] self.assertEqual(len(output), 3) self.assertEqual(list(map(str, output)), expected) def test_api_calls(self): \"\"\"Seqparse:",
"seqparse module.\"\"\" _test_ext = \"exr\" _test_file_name = \"TEST_DIR\" _test_root =",
"file_seq = file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_complex_sequence(self,",
"FrameChunk(first=2, last=10, step=2, pad=4) expected = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_out)",
"list(parser.output()) expected = [ os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output),",
"last=6, step=2, pad=4) inverted = invert(chunk) self.assertEqual(str(inverted), str(expected)) inverted =",
"\"0001-\", \"0001x2\", \"x2\", \"0001,0003x2\", \"0001-0005x\", \"0010-0001\", \"x\", \",\", \",,\", \"\"",
"self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertTrue(4 in",
"self.assertEqual(output[0].size, 36520) parser = get_parser() parser.scan_options[\"all\"] = True parser.scan_path(self._test_root) output",
"get_version, invert, validate_frame_sequence) from ..sequences import FileSequence, FrameChunk, FrameSequence ###############################################################################",
"= \".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) print(\"\\n",
"Now check the file sequence itself. file_seq = data[self._test_root][self._test_file_name] test_output",
"fseq = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_in) input_entries = [DirEntry(x) for",
"sequences property. self.assertIn(self._test_root, data) self.assertEqual(len(data), 1) self.assertIn(self._test_file_name, data[self._test_root]) self.assertEqual(len(data[self._test_root]), 1)",
"# And finally, the file sequence. file_seq = file_seq[self._test_ext][4] self.assertEqual(len(file_seq),",
"5 seqs = list(parser.output()) blurb = \" o max_levels ==",
"= 3 - min_levels if min_levels == -1: expected_seqs =",
"for line in output: print(\" o\", line) print(\"\\n EXPECTED OUTPUT\\n",
"last=7, step=2, pad=4) seq = get_sequence(lrange(1, 8, 2), pad=4) self.assertTrue(isinstance(seq,",
"mock_api_call): \"\"\"Seqparse: Test complex file sequence discovery.\"\"\" frames = {",
"calls at root of module.\"\"\" chunk = FrameChunk(first=1, last=7, step=2,",
"self.assertEqual(output_seqs[pad], str(file_seq[self._test_ext][pad])) @mock.patch(\"seqparse.seqparse.scandir\") def test_nested_sequences(self, mock_api_call): \"\"\"Seqparse: Test file sequence",
"input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) print(\"\\n INPUT FILES\\n -----------\")",
"= list(parser.output(missing=True)) self.assertEqual(len(inverted), 1) print(\"\\n\\n SEQUENCE\\n --------\") print(\" input files:",
"test_simple_sequence(self, mock_api_call): \"\"\"Seqparse: Test simple file sequence discovery.\"\"\" frames =",
"for x in fseq] mock_api_call.return_value = input_entries expected = FileSequence(",
"... input_frame_seq = \"0000-0004\" output_frame_seq = \"0000-0005\" input_file_seq = \".\".join(",
"import lrange from . import (DirEntry, generate_entries, initialise_mock_scandir_data, mock_scandir_deep) from",
"1490908305) self.assertEqual(output[0].size, 36520) parser = get_parser() parser.scan_options[\"all\"] = True parser.scan_path(self._test_root)",
"= get_sequence(lrange(1, 8, 2), pad=4) self.assertTrue(isinstance(seq, FrameSequence)) self.assertEqual(str(seq), \"0001-0007x2\") expected",
"input_entries = generate_entries( name=\"test\", ext=\"py\", frames=frames, root=self._test_root) input_entries.extend( generate_entries( name=\".test\",",
"the test case.\"\"\" pass @mock.patch(\"seqparse.seqparse.scandir\") def test_singletons(self, mock_api_call): \"\"\"Seqparse: Test",
"list() for file_name in output: entries.append(DirEntry(file_name)) mock_api_call.return_value = iter(entries) parser",
"-------------\") for frame_seq in bad_frame_seqs: print(' o {!r}'.format(frame_seq)) self.assertFalse(validate_frame_sequence(frame_seq)) print(\"\")",
"\".\".join( (self._test_file_name, output_frame_seq, self._test_ext)) output_file_seq = os.path.join(self._test_root, output_file_seq) print(\"\\n\\n INPUT",
"the file sequence itself. file_seq = data[self._test_root][self._test_file_name] test_output = list(file_seq.output())",
"option in Seqparse.output.\"\"\" file_path = os.path.join(self._test_root, self._test_file_name) chunk_in = FrameChunk(first=1,",
"from future.utils import lrange from . import (DirEntry, generate_entries, initialise_mock_scandir_data,",
"test_inversion(self, mock_api_call): \"\"\"Seqparse: Test usage of the \"missing\" option in",
"os.path.join(self._test_root, file_seq_output) input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) mock_api_call.return_value",
"name=\".test\", ext=\"py\", frames=frames, root=self._test_root)) input_entries.append( DirEntry(os.path.join(self._test_root, \"pony.py\"))) mock_api_call.return_value = input_entries",
"... frame_seq_output = \"0001\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output, self._test_ext))",
"= get_parser() parser.add_file(input_file_seq) parser.add_file(input_file) output = list(parser.output()) print(\"\\n OUTPUT FILES\\n",
"\",0001\", \"0001,\", \"0001-0001\", \"0001-0001x0\", \"0001-0003x3\", \"0001,0003\", \"0001,,0003\", \"0001-0010\", \"0001-0010x0\", \"0001-0011x2\",",
"print_function # Standard Libraries import os import unittest # Third",
"2, 3, 4, 5, 6, 8, 10, 12, 101] }",
"seq = get_sequence(lrange(1, 8, 2), pad=4) self.assertTrue(isinstance(seq, FrameSequence)) self.assertEqual(str(seq), \"0001-0007x2\")",
"# Test seqs_only option ... self.assertEqual(sorted(parser.output(seqs_only=True)), []) @mock.patch(\"seqparse.seqparse.scandir\") def test_single_padded_file(self,",
"file sequence. file_seq = file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\")",
"= os.path.join(self._test_root, self._test_file_name) chunk_in = FrameChunk(first=1, last=11, step=2, pad=4) fseq",
"\"\"\"Set up the test case.\"\"\" pass @mock.patch(\"seqparse.seqparse.scandir\") def test_singletons(self, mock_api_call):",
"3, 4, 5, 6, 8, 10, 12, 101] } input_entries",
"== {:d}: {:d} ({:d} expected) entries\" print(blurb.format(max_levels, len(seqs), expected_seqs)) for",
"setUp(self): \"\"\"Set up the test case.\"\"\" pass @mock.patch(\"seqparse.seqparse.scandir\") def test_singletons(self,",
"len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_complex_sequence(self, mock_api_call): \"\"\"Seqparse: Test complex",
"max_levels=max_levels) expected_seqs = max_levels + 2 if max_levels == -1:",
"len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_simple_sequence(self, mock_api_call): \"\"\"Seqparse: Test simple",
"in parser.output(): print(\" \", seq) print(\"\\n MAX LEVELS\\n ----------\") for",
"x in self._singletons] entries = list() for file_name in output:",
"unittest # Third Party Libraries import mock from builtins import",
"list(parser.output()) blurb = \" o min_levels == {:d}: {:d} ({:d}",
"sorted(output_seqs.items()): bits = (self._test_file_name, seq_frames, self._test_ext) output_seqs[pad] = os.path.join(self._test_root, \".\".join(bits))",
"bad_frame_seqs: print(' o {!r}'.format(frame_seq)) self.assertFalse(validate_frame_sequence(frame_seq)) print(\"\") def test_add_file_sequence(self): \"\"\"Seqparse: Test",
"output_file_seq) print(\"\\n\\n INPUT FILES\\n -----------\") print(\" o\", input_file_seq) print(\" o\",",
"os.path.join(self._test_root, \".\".join(bits)) final_output.append(output_seqs[pad]) data = parser.sequences # Check the structure",
"parser.scan_options[\"all\"] = True parser.scan_path(self._test_root) output = list(parser.output()) expected = [",
"FrameChunk(first=2, last=6, step=2, pad=4) inverted = invert(chunk) self.assertEqual(str(inverted), str(expected)) inverted",
"And finally, the file sequences. for pad in sorted(output_seqs): self.assertEqual(output_seqs[pad],",
"\"0001-0011x2\", \"0001-0012x2\", \"0001-0005,0007-0010\", \"0001-0005x2,0007-0010\", \"0001-0005,0007-0011x2\", \"0001-0005,0006,0008-0012x2\", \"0001,0003-0007,0009-0015x2\", \"3,1,5,7\", \"01-05,03-07\" ]",
"= get_parser() parser.scan_path(self._test_root) final_output = list() for pad, seq_frames in",
"sequence. file_seq = file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def",
"pad=4) seq = get_sequence(lrange(1, 8, 2), pad=4) self.assertTrue(isinstance(seq, FrameSequence)) self.assertEqual(str(seq),",
"ext=self._test_ext, frames=[5], pad=4) parser = get_parser() parser.scan_path(self._test_root) inverted = list(parser.output(missing=True))",
"input_entries = [DirEntry(x) for x in fseq] mock_api_call.return_value = input_entries",
"= os.path.join(self._test_root, output_file_seq) print(\"\\n\\n INPUT FILES\\n -----------\") print(\" o\", input_file_seq)",
"for seq in seqs: print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\")",
"os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 2) self.assertEqual(list(map(str, output)), expected)",
"at root of module.\"\"\" chunk = FrameChunk(first=1, last=7, step=2, pad=4)",
"file_seq = data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 3) self.assertEqual(list(map(str, test_output)),",
"3 - min_levels if min_levels == -1: expected_seqs = 5",
"os.path.join(self._test_root, input_file) # Expected outputs ... input_frame_seq = \"0000-0004\" output_frame_seq",
"list(file_seq.output()) self.assertEqual(len(test_output), 3) self.assertEqual(list(map(str, test_output)), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1)",
"frames 114, 199 move to the # \"pad 3\" group",
"output)) self.assertTrue(output) print(\"\\n BAD SEQUENCES\\n -------------\") for frame_seq in bad_frame_seqs:",
"1: \"5-8\", 3: \"008-010,012,114,199\", 4: \"0000-0006,0008-0012x2,0101,2000\" } # Expected final",
"output: entries.append(DirEntry(file_name)) mock_api_call.return_value = iter(entries) parser = get_parser() parser.scan_path(self._test_root) file_names",
"self.assertEqual(output[0].mtime, 1490908305) self.assertEqual(output[0].size, 36520) parser = get_parser() parser.scan_options[\"all\"] = True",
"sequence discovery.\"\"\" frames = { 1: [5, 6, 7, 8,",
"print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) @mock.patch(\"seqparse.seqparse.scandir\") def test_scan_options(self, mock_api_call):",
"list(parser.output()) print(\"\\n OUTPUT FILES\\n ------------\") for line in output: print(\"",
"input files: \", fseq) print(\" expected files:\", expected) print(\" inverted",
"output_file_seq = \".\".join( (self._test_file_name, output_frame_seq, self._test_ext)) output_file_seq = os.path.join(self._test_root, output_file_seq)",
"self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) @mock.patch(\"seqparse.seqparse.scandir\") def test_inversion(self, mock_api_call): \"\"\"Seqparse: Test",
"step=2, pad=4) inverted = invert(chunk) self.assertEqual(str(inverted), str(expected)) inverted = invert(seq)",
"... output = [os.path.join(self._test_root, x) for x in self._singletons] entries",
"def test_inversion(self, mock_api_call): \"\"\"Seqparse: Test usage of the \"missing\" option",
"of module.\"\"\" chunk = FrameChunk(first=1, last=7, step=2, pad=4) seq =",
"simple file sequence discovery.\"\"\" frames = {4: [0, 1, 2,",
"on the seqparse module.\"\"\" _test_ext = \"exr\" _test_file_name = \"TEST_DIR\"",
"frame sequences. Note how frames 114, 199 move to the",
"= invert(chunk) self.assertEqual(str(inverted), str(expected)) inverted = invert(seq) self.assertEqual(str(inverted), str(expected)) with",
"print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\\n MIN LEVELS\\n ----------\") for",
"frames=chunk_in) input_entries = [DirEntry(x) for x in fseq] mock_api_call.return_value =",
"finally, the file sequence. file_seq = file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq),",
"file sequence discovery.\"\"\" frames = {4: [0, 1, 2, 3,",
"self.assertEqual(sorted(map(str, parser.output())), output) # Test seqs_only option ... self.assertEqual(sorted(parser.output(seqs_only=True)), [])",
"print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\") def test_valid_frame_sequences(self): \"\"\"Seqparse: Test",
"blurb = \" o max_levels == {:d}: {:d} ({:d} expected)",
"builtins import range from future.utils import lrange from . import",
"frame_seq_output, self._test_ext)) final_output = os.path.join(self._test_root, file_seq_output) input_entries = generate_entries( ext=self._test_ext,",
"print(\"\") def test_valid_frame_sequences(self): \"\"\"Seqparse: Test validity of simple frame ranges.\"\"\"",
"parser = get_parser() parser.scan_path(self._test_root) for seq in parser.output(): print(\" \",",
"FileSequence( name=file_path, ext=self._test_ext, frames=[1, 2, 3, 4, 6], pad=4) input_entries",
"file_seq = data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output)",
"mock_api_call.return_value = iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) final_output = list()",
"parser.scan_path(self._test_root) final_output = list() for pad, seq_frames in sorted(output_seqs.items()): bits",
"self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_complex_sequence(self, mock_api_call): \"\"\"Seqparse: Test complex file",
"os.sep): # test_dir/TEST_DIR.5-8.exr # test_dir/TEST_DIR.008-010,012,114,199.exr # test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr mock_api_call.return_value = iter(input_entries)",
"file discovery on the seqparse module.\"\"\" _test_ext = \"exr\" _test_file_name",
"\"008-010,012,114,199\", 4: \"0000-0006,0008-0012x2,0101,2000\" } # Expected final output (where \"/\"",
"list() for pad, seq_frames in sorted(output_seqs.items()): bits = (self._test_file_name, seq_frames,",
"\"-0001\", \"0001-\", \"0001x2\", \"x2\", \"0001,0003x2\", \"0001-0005x\", \"0010-0001\", \"x\", \",\", \",,\",",
"range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, min_levels=min_levels) expected_seqs =",
"-\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\") def test_valid_frame_sequences(self): \"\"\"Seqparse: Test validity",
"= file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_simple_sequence(self, mock_api_call):",
".. import (__version__, get_parser, get_sequence, get_version, invert, validate_frame_sequence) from ..sequences",
"list(parser.output()) blurb = \" o max_levels == {:d}: {:d} ({:d}",
"Expected output frame sequences. Note how frames 114, 199 move",
"entries.append(DirEntry(file_name)) mock_api_call.return_value = iter(entries) parser = get_parser() parser.scan_path(self._test_root) file_names =",
"from ..sequences import FileSequence, FrameChunk, FrameSequence ############################################################################### # class: TestSeqparseModule",
"@mock.patch(\"seqparse.seqparse.scandir\") def test_inversion(self, mock_api_call): \"\"\"Seqparse: Test usage of the \"missing\"",
"file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_complex_sequence(self, mock_api_call): \"\"\"Seqparse:",
"file_seq) self.assertEqual(len(file_seq), 1) self.assertEqual(set(file_seq[self._test_ext]), set(output_seqs)) # And finally, the file",
"ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) mock_api_call.return_value = iter(input_entries) parser = get_parser()",
"= input_entries parser = get_parser() parser.scan_options[\"stat\"] = True parser.scan_path(self._test_root) output",
"= \" o max_levels == {:d}: {:d} ({:d} expected) entries\"",
"fseq) print(\" expected files:\", expected) print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]),",
"x in fseq] mock_api_call.return_value = input_entries chunk_out = FrameChunk(first=2, last=10,",
"file sequence discovery on disk.\"\"\" # \"Future\" Libraries from __future__",
"print(' o {!r}'.format(frame_seq)) self.assertFalse(validate_frame_sequence(frame_seq)) print(\"\") def test_add_file_sequence(self): \"\"\"Seqparse: Test file",
"seqs_only option ... self.assertEqual(sorted(parser.output(seqs_only=True)), []) @mock.patch(\"seqparse.seqparse.scandir\") def test_single_padded_file(self, mock_api_call): \"\"\"Seqparse:",
"len(seqs), expected_seqs)) for seq in seqs: print(\" -\", seq) self.assertEqual(len(seqs),",
"generate_entries, initialise_mock_scandir_data, mock_scandir_deep) from .. import (__version__, get_parser, get_sequence, get_version,",
"simple frame ranges.\"\"\" good_frame_seqs = [ \"0001\", \",0001\", \"0001,\", \"0001-0001\",",
"[0, 1, 2, 3, 4]} # Expected outputs ... frame_seq_output",
"test_complex_sequence(self, mock_api_call): \"\"\"Seqparse: Test complex file sequence discovery.\"\"\" frames =",
"pad=4) inverted = invert(chunk) self.assertEqual(str(inverted), str(expected)) inverted = invert(seq) self.assertEqual(str(inverted),",
"sorted(self._singletons), sorted(file_names[self._test_root])) # Check parser output ... self.assertEqual(sorted(map(str, parser.output())), output)",
"inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) fseq = FileSequence( name=file_path, ext=self._test_ext, frames=[1, 2,",
"\"x2\", \"0001,0003x2\", \"0001-0005x\", \"0010-0001\", \"x\", \",\", \",,\", \"\" ] print(\"\\n\\n",
"option ... self.assertEqual(sorted(parser.output(seqs_only=True)), []) @mock.patch(\"seqparse.seqparse.scandir\") def test_single_padded_file(self, mock_api_call): \"\"\"Seqparse: Test",
"os import unittest # Third Party Libraries import mock from",
"seq in parser.output(): print(\" \", seq) print(\"\\n MAX LEVELS\\n ----------\")",
"name=\"test\", ext=\"py\", frames=frames, root=self._test_root) input_entries.extend( generate_entries( name=\".test\", ext=\"py\", frames=frames, root=self._test_root))",
"== {:d}: {:d} ({:d} expected) entries\" print(blurb.format(min_levels, len(seqs), expected_seqs)) for",
"discovery.\"\"\" frames = { 1: [5, 6, 7, 8, 114,",
"ext=self._test_ext, frames=chunk_out) parser = get_parser() parser.scan_path(self._test_root) inverted = list(parser.output(missing=True)) self.assertEqual(len(inverted),",
"[8, 9, 10, 12], 4: [0, 1, 2, 3, 4,",
"3) self.assertEqual(list(map(str, test_output)), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertEqual(set(file_seq[self._test_ext]), set(output_seqs))",
"\",,\", \"\" ] print(\"\\n\\n GOOD SEQUENCES\\n --------------\") for frame_seq in",
"= list(parser.output()) expected = [ os.path.join(self._test_root, \".test.0001-0004,0006.py\"), os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root,",
"name=self._test_file_name, root=self._test_root) mock_api_call.return_value = iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) data",
"\"\"\"Test file sequence discovery on disk.\"\"\" # \"Future\" Libraries from",
"chunk = FrameChunk(first=1, last=7, step=2, pad=4) seq = get_sequence(lrange(1, 8,",
"expected_seqs) print(\"\\n MIN LEVELS\\n ----------\") for min_levels in range(-1, 4):",
"= list() for pad, seq_frames in sorted(output_seqs.items()): bits = (self._test_file_name,",
"mock_api_call): \"\"\"Seqparse: Test usage of the \"missing\" option in Seqparse.output.\"\"\"",
"get_parser() parser.scan_path(self._test_root, min_levels=min_levels) expected_seqs = 3 - min_levels if min_levels",
"for frame_seq in bad_frame_seqs: print(' o {!r}'.format(frame_seq)) self.assertFalse(validate_frame_sequence(frame_seq)) print(\"\") def",
"= generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) mock_api_call.return_value = iter(input_entries) parser",
"= get_parser() parser.scan_options[\"stat\"] = True parser.scan_path(self._test_root) output = list(parser.output()) expected",
"[\"singleton0.jpg\", \"singleton1.jpg\"] def setUp(self): \"\"\"Set up the test case.\"\"\" pass",
"entries\" print(blurb.format(max_levels, len(seqs), expected_seqs)) for seq in seqs: print(\" -\",",
"input_file = \".\".join((self._test_file_name, \"0005\", self._test_ext)) input_file = os.path.join(self._test_root, input_file) #",
"print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) fseq = FileSequence( name=file_path,",
"os.path.join(self._test_root, \".test.0001-0004,0006.py\"), os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 3) self.assertEqual(list(map(str,",
"sequence discovery in nested directories.\"\"\" mock_api_call.side_effect = mock_scandir_deep print(\"\\n\\n SEQUENCES\\n",
"= [ \"0001\", \",0001\", \"0001,\", \"0001-0001\", \"0001-0001x0\", \"0001-0003x3\", \"0001,0003\", \"0001,,0003\",",
"self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) output_file_seq = \".\".join( (self._test_file_name, output_frame_seq,",
"class: TestSeqparseModule class TestSeqparseModule(unittest.TestCase): \"\"\"Test file discovery on the seqparse",
"location.\"\"\" # Expected outputs ... output = [os.path.join(self._test_root, x) for",
"self.assertTrue(isinstance(seq, FrameSequence)) self.assertEqual(str(seq), \"0001-0007x2\") expected = FrameChunk(first=2, last=6, step=2, pad=4)",
"input_file_seq = os.path.join(self._test_root, input_file_seq) output_file_seq = \".\".join( (self._test_file_name, output_frame_seq, self._test_ext))",
"= FrameChunk(first=2, last=6, step=2, pad=4) inverted = invert(chunk) self.assertEqual(str(inverted), str(expected))",
"file_names) self.assertEqual(self._test_root, file_names[self._test_root].path) self.assertEqual(len(file_names), 1) self.assertEqual( len(file_names[self._test_root]), len(self._singletons)) self.assertEqual( sorted(self._singletons),",
"Note how frames 114, 199 move to the # \"pad",
"Expected outputs ... frame_seq_output = \"0000-0004\" file_seq_output = \".\".join( (self._test_file_name,",
"frames=[1, 2, 3, 4, 6], pad=4) input_entries = [DirEntry(x) for",
"self._test_ext)) input_file = os.path.join(self._test_root, input_file) # Expected outputs ... input_frame_seq",
"4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, min_levels=min_levels) expected_seqs = 3",
"- min_levels if min_levels == -1: expected_seqs = 5 seqs",
"o min_levels == {:d}: {:d} ({:d} expected) entries\" print(blurb.format(min_levels, len(seqs),",
"itself. file_seq = data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]),",
"final_output.append(output_seqs[pad]) data = parser.sequences # Check the structure of the",
"fseq] mock_api_call.return_value = input_entries chunk_out = FrameChunk(first=2, last=10, step=2, pad=4)",
"get_parser, get_sequence, get_version, invert, validate_frame_sequence) from ..sequences import FileSequence, FrameChunk,",
"8, 114, 199, 2000], 3: [8, 9, 10, 12], 4:",
"the sequences property. self.assertIn(self._test_root, data) self.assertEqual(len(data), 1) self.assertIn(self._test_file_name, data[self._test_root]) self.assertEqual(len(data[self._test_root]),",
"output) # Test seqs_only option ... self.assertEqual(sorted(parser.output(seqs_only=True)), []) @mock.patch(\"seqparse.seqparse.scandir\") def",
"1) self.assertIn(self._test_file_name, data[self._test_root]) self.assertEqual(len(data[self._test_root]), 1) # Now check the file",
"1: [5, 6, 7, 8, 114, 199, 2000], 3: [8,",
"the file sequences. for pad in sorted(output_seqs): self.assertEqual(output_seqs[pad], str(file_seq[self._test_ext][pad])) @mock.patch(\"seqparse.seqparse.scandir\")",
"fseq] mock_api_call.return_value = input_entries expected = FileSequence( name=file_path, ext=self._test_ext, frames=[5],",
"12], 4: [0, 1, 2, 3, 4, 5, 6, 8,",
"expected_seqs = 5 seqs = list(parser.output()) blurb = \" o",
"self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) # Check the structure of the",
"LEVELS\\n ----------\") for max_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser =",
"self.assertEqual( len(file_names[self._test_root]), len(self._singletons)) self.assertEqual( sorted(self._singletons), sorted(file_names[self._test_root])) # Check parser output",
"up the test case.\"\"\" pass @mock.patch(\"seqparse.seqparse.scandir\") def test_singletons(self, mock_api_call): \"\"\"Seqparse:",
"\"0000-0004\" output_frame_seq = \"0000-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq, self._test_ext))",
"FrameChunk(first=1, last=11, step=2, pad=4) fseq = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_in)",
"input_entries expected = FileSequence( name=file_path, ext=self._test_ext, frames=[5], pad=4) parser =",
"root=self._test_root) input_entries.extend( generate_entries( name=\".test\", ext=\"py\", frames=frames, root=self._test_root)) input_entries.append( DirEntry(os.path.join(self._test_root, \"pony.py\")))",
"good_frame_seqs: output = validate_frame_sequence(frame_seq) print(' o {!r} --> {!r}'.format(frame_seq, output))",
"{ 1: [5, 6, 7, 8, 114, 199, 2000], 3:",
"file sequence discovery in nested directories.\"\"\" mock_api_call.side_effect = mock_scandir_deep print(\"\\n\\n",
"({:d} expected) entries\" print(blurb.format(max_levels, len(seqs), expected_seqs)) for seq in seqs:",
"parser.output())), output) # Test seqs_only option ... self.assertEqual(sorted(parser.output(seqs_only=True)), []) @mock.patch(\"seqparse.seqparse.scandir\")",
"self.assertEqual(len(output), 2) self.assertEqual(list(map(str, output)), expected) self.assertEqual(output[0].ctime, 1490908340) self.assertEqual(output[0].mtime, 1490908305) self.assertEqual(output[0].size,",
"\"0010-0001\", \"x\", \",\", \",,\", \"\" ] print(\"\\n\\n GOOD SEQUENCES\\n --------------\")",
"print(\"\\n OUTPUT FILES\\n ------------\") for line in output: print(\" o\",",
"= iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) data = parser.sequences test_output",
"1) # And finally, the file sequence. file_seq = file_seq[self._test_ext][4]",
"seq in seqs: print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\\n MIN",
"print(' o {!r} --> {!r}'.format(frame_seq, output)) self.assertTrue(output) print(\"\\n BAD SEQUENCES\\n",
"@mock.patch(\"seqparse.seqparse.scandir\") def test_single_padded_file(self, mock_api_call): \"\"\"Seqparse: Test single padded file sequence",
"\"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 3) self.assertEqual(list(map(str, output)), expected) def",
"@mock.patch(\"seqparse.seqparse.scandir\") def test_scan_options(self, mock_api_call): \"\"\"Seqparse: Make sure scan_options works as",
"on disk.\"\"\" # \"Future\" Libraries from __future__ import print_function #",
"= list(parser.output()) expected = [ os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ]",
"\"/\" is os.sep): # test_dir/TEST_DIR.5-8.exr # test_dir/TEST_DIR.008-010,012,114,199.exr # test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr mock_api_call.return_value",
"expected files:\", expected) print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) fseq",
"SEQUENCES\\n --------------\") for frame_seq in good_frame_seqs: output = validate_frame_sequence(frame_seq) print('",
"[ \"-0001\", \"0001-\", \"0001x2\", \"x2\", \"0001,0003x2\", \"0001-0005x\", \"0010-0001\", \"x\", \",\",",
"in Seqparse.output.\"\"\" file_path = os.path.join(self._test_root, self._test_file_name) chunk_in = FrameChunk(first=1, last=11,",
"files:\", expected) print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) @mock.patch(\"seqparse.seqparse.scandir\") def",
"get_parser() parser.add_file(input_file_seq) parser.add_file(input_file) output = list(parser.output()) print(\"\\n OUTPUT FILES\\n ------------\")",
"file_seq[self._test_ext]) self.assertEqual(len(file_seq[self._test_ext]), 1) # And finally, the file sequence. file_seq",
"\"3,1,5,7\", \"01-05,03-07\" ] bad_frame_seqs = [ \"-0001\", \"0001-\", \"0001x2\", \"x2\",",
"2) self.assertEqual(list(map(str, output)), expected) self.assertEqual(output[0].ctime, 1490908340) self.assertEqual(output[0].mtime, 1490908305) self.assertEqual(output[0].size, 36520)",
"nested directories.\"\"\" mock_api_call.side_effect = mock_scandir_deep print(\"\\n\\n SEQUENCES\\n ---------\") initialise_mock_scandir_data(self._test_root) parser",
"self.assertEqual(str(inverted), str(expected)) inverted = invert(seq) self.assertEqual(str(inverted), str(expected)) with self.assertRaises(TypeError): invert(get_parser())",
"print(\"\\n\\n INPUT FILES\\n -----------\") print(\" o\", input_file_seq) print(\" o\", input_file)",
"from .. import (__version__, get_parser, get_sequence, get_version, invert, validate_frame_sequence) from",
"move to the # \"pad 3\" group and 2000 moves",
"from disk location.\"\"\" # Expected outputs ... output = [os.path.join(self._test_root,",
"test case.\"\"\" pass @mock.patch(\"seqparse.seqparse.scandir\") def test_singletons(self, mock_api_call): \"\"\"Seqparse: Test file",
"in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, max_levels=max_levels) expected_seqs",
"10, 12, 101] } input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name,",
"4, 5, 6, 8, 10, 12, 101] } input_entries =",
"self.assertEqual(str(inverted[0]), str(expected)) @mock.patch(\"seqparse.seqparse.scandir\") def test_scan_options(self, mock_api_call): \"\"\"Seqparse: Make sure scan_options",
"output_frame_seq = \"0000-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq",
"pad in sorted(output_seqs): self.assertEqual(output_seqs[pad], str(file_seq[self._test_ext][pad])) @mock.patch(\"seqparse.seqparse.scandir\") def test_nested_sequences(self, mock_api_call): \"\"\"Seqparse:",
"pad=4) fseq = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_in) input_entries = [DirEntry(x)",
"output = list(parser.output()) expected = [ os.path.join(self._test_root, \".test.0001-0004,0006.py\"), os.path.join(self._test_root, \"test.0001-0004,0006.py\"),",
"from . import (DirEntry, generate_entries, initialise_mock_scandir_data, mock_scandir_deep) from .. import",
"output = validate_frame_sequence(frame_seq) print(' o {!r} --> {!r}'.format(frame_seq, output)) self.assertTrue(output)",
"= input_entries expected = FileSequence( name=file_path, ext=self._test_ext, frames=[5], pad=4) parser",
"DirEntry(os.path.join(self._test_root, \"pony.py\"))) mock_api_call.return_value = input_entries parser = get_parser() parser.scan_options[\"stat\"] =",
"1) self.assertEqual(str(test_output[0]), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertTrue(4 in file_seq[self._test_ext])",
"output: print(\" o\", line) print(\"\\n EXPECTED OUTPUT\\n ---------------\") print(\" o\",",
"structure of the sequences property. self.assertIn(self._test_root, data) self.assertEqual(len(data), 1) self.assertIn(self._test_file_name,",
"# Expected outputs ... frame_seq_output = \"0001\" file_seq_output = \".\".join(",
"ranges.\"\"\" good_frame_seqs = [ \"0001\", \",0001\", \"0001,\", \"0001-0001\", \"0001-0001x0\", \"0001-0003x3\",",
"addition via seqparse.add_file.\"\"\" input_file = \".\".join((self._test_file_name, \"0005\", self._test_ext)) input_file =",
"= FileSequence( name=file_path, ext=self._test_ext, frames=[5], pad=4) parser = get_parser() parser.scan_path(self._test_root)",
"= [ os.path.join(self._test_root, \".test.0001-0004,0006.py\"), os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output),",
"= get_parser() parser.scan_path(self._test_root) for seq in parser.output(): print(\" \", seq)",
"Libraries from __future__ import print_function # Standard Libraries import os",
"2), pad=4) self.assertTrue(isinstance(seq, FrameSequence)) self.assertEqual(str(seq), \"0001-0007x2\") expected = FrameChunk(first=2, last=6,",
"module.\"\"\" chunk = FrameChunk(first=1, last=7, step=2, pad=4) seq = get_sequence(lrange(1,",
"ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) # Expected output frame sequences. Note",
"expected) def test_api_calls(self): \"\"\"Seqparse: Test API calls at root of",
"for pad in sorted(output_seqs): self.assertEqual(output_seqs[pad], str(file_seq[self._test_ext][pad])) @mock.patch(\"seqparse.seqparse.scandir\") def test_nested_sequences(self, mock_api_call):",
"output frame sequences. Note how frames 114, 199 move to",
"max_levels + 2 if max_levels == -1: expected_seqs = 5",
"sequence itself. file_seq = data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 3)",
"output = list(parser.output()) expected = [ os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\")",
"_test_ext = \"exr\" _test_file_name = \"TEST_DIR\" _test_root = \"test_dir\" _singletons",
"\".\".join((self._test_file_name, \"0005\", self._test_ext)) input_file = os.path.join(self._test_root, input_file) # Expected outputs",
"} input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) # Expected",
"o max_levels == {:d}: {:d} ({:d} expected) entries\" print(blurb.format(max_levels, len(seqs),",
"\", fseq) print(\" expected files:\", expected) print(\" inverted files:\", inverted[0])",
"initialise_mock_scandir_data, mock_scandir_deep) from .. import (__version__, get_parser, get_sequence, get_version, invert,",
"self.assertEqual(set(file_seq[self._test_ext]), set(output_seqs)) # And finally, the file sequences. for pad",
"2000], 3: [8, 9, 10, 12], 4: [0, 1, 2,",
"Libraries import mock from builtins import range from future.utils import",
"\"\"\"Test file discovery on the seqparse module.\"\"\" _test_ext = \"exr\"",
"self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_complex_sequence(self, mock_api_call): \"\"\"Seqparse: Test",
"generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) mock_api_call.return_value = iter(input_entries) parser =",
"\"\"\"Seqparse: Test file sequence discovery in nested directories.\"\"\" mock_api_call.side_effect =",
"itself. file_seq = data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 3) self.assertEqual(list(map(str,",
"in good_frame_seqs: output = validate_frame_sequence(frame_seq) print(' o {!r} --> {!r}'.format(frame_seq,",
"import (DirEntry, generate_entries, initialise_mock_scandir_data, mock_scandir_deep) from .. import (__version__, get_parser,",
"files: \", fseq) print(\" expected files:\", expected) print(\" inverted files:\",",
"[DirEntry(x) for x in fseq] mock_api_call.return_value = input_entries expected =",
"future.utils import lrange from . import (DirEntry, generate_entries, initialise_mock_scandir_data, mock_scandir_deep)",
"6, 7, 8, 114, 199, 2000], 3: [8, 9, 10,",
"############################################################################### # class: TestSeqparseModule class TestSeqparseModule(unittest.TestCase): \"\"\"Test file discovery on",
"----------\") for min_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser()",
"min_levels == {:d}: {:d} ({:d} expected) entries\" print(blurb.format(min_levels, len(seqs), expected_seqs))",
"files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) fseq = FileSequence( name=file_path, ext=self._test_ext, frames=[1,",
"= data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) self.assertIn(self._test_ext,",
"to the \"pad 4\" group! output_seqs = { 1: \"5-8\",",
"= [ \"-0001\", \"0001-\", \"0001x2\", \"x2\", \"0001,0003x2\", \"0001-0005x\", \"0010-0001\", \"x\",",
"outputs ... input_frame_seq = \"0000-0004\" output_frame_seq = \"0000-0005\" input_file_seq =",
"[1]} # Expected outputs ... frame_seq_output = \"0001\" file_seq_output =",
"last=10, step=2, pad=4) expected = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_out) parser",
"] self.assertEqual(len(output), 2) self.assertEqual(list(map(str, output)), expected) self.assertEqual(output[0].ctime, 1490908340) self.assertEqual(output[0].mtime, 1490908305)",
"# Expected final output (where \"/\" is os.sep): # test_dir/TEST_DIR.5-8.exr",
"= FrameChunk(first=1, last=7, step=2, pad=4) seq = get_sequence(lrange(1, 8, 2),",
"= get_parser() parser.scan_path(self._test_root, min_levels=min_levels) expected_seqs = 3 - min_levels if",
"list(parser.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) # Check the structure of",
"os.path.join(self._test_root, input_file_seq) print(\"\\n INPUT FILES\\n -----------\") print(\" o\", input_file_seq) print(\"",
"= (self._test_file_name, seq_frames, self._test_ext) output_seqs[pad] = os.path.join(self._test_root, \".\".join(bits)) final_output.append(output_seqs[pad]) data",
"seq_frames, self._test_ext) output_seqs[pad] = os.path.join(self._test_root, \".\".join(bits)) final_output.append(output_seqs[pad]) data = parser.sequences",
"file sequence addition via seqparse.add_file.\"\"\" input_file = \".\".join((self._test_file_name, \"0005\", self._test_ext))",
"via seqparse.add_file.\"\"\" input_file = \".\".join((self._test_file_name, \"0005\", self._test_ext)) input_file = os.path.join(self._test_root,",
"4, 6)} input_entries = generate_entries( name=\"test\", ext=\"py\", frames=frames, root=self._test_root) input_entries.extend(",
"FILES\\n ------------\") for line in output: print(\" o\", line) print(\"\\n",
"1) print(\"\\n\\n SEQUENCE\\n --------\") print(\" input files: \", fseq) print(\"",
"{:d}: {:d} ({:d} expected) entries\" print(blurb.format(min_levels, len(seqs), expected_seqs)) for seq",
"test_valid_frame_sequences(self): \"\"\"Seqparse: Test validity of simple frame ranges.\"\"\" good_frame_seqs =",
"self.assertTrue(output) print(\"\\n BAD SEQUENCES\\n -------------\") for frame_seq in bad_frame_seqs: print('",
"---------------\") print(\" o\", output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) @mock.patch(\"seqparse.seqparse.scandir\")",
"data[self._test_root]) self.assertEqual(len(data[self._test_root]), 1) # Now check the file sequence itself.",
"bad_frame_seqs = [ \"-0001\", \"0001-\", \"0001x2\", \"x2\", \"0001,0003x2\", \"0001-0005x\", \"0010-0001\",",
"min_levels == -1: expected_seqs = 5 seqs = list(parser.output()) blurb",
"outputs ... frame_seq_output = \"0000-0004\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output,",
"frame_seq in good_frame_seqs: output = validate_frame_sequence(frame_seq) print(' o {!r} -->",
"import print_function # Standard Libraries import os import unittest #",
"ext=\"py\", frames=frames, root=self._test_root) input_entries.extend( generate_entries( name=\".test\", ext=\"py\", frames=frames, root=self._test_root)) input_entries.append(",
"self.assertEqual(list(map(str, test_output)), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertEqual(set(file_seq[self._test_ext]), set(output_seqs)) #",
"def test_add_file_sequence(self): \"\"\"Seqparse: Test file sequence addition via seqparse.add_file.\"\"\" input_file",
"12, 101] } input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root)",
"pad=4) parser = get_parser() parser.scan_path(self._test_root) inverted = list(parser.output(missing=True)) self.assertEqual(len(inverted), 1)",
"MIN LEVELS\\n ----------\") for min_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser",
"files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) @mock.patch(\"seqparse.seqparse.scandir\") def test_scan_options(self, mock_api_call): \"\"\"Seqparse: Make",
"and 2000 moves to the \"pad 4\" group! output_seqs =",
"= validate_frame_sequence(frame_seq) print(' o {!r} --> {!r}'.format(frame_seq, output)) self.assertTrue(output) print(\"\\n",
"in output: print(\" o\", line) print(\"\\n EXPECTED OUTPUT\\n ---------------\") print(\"",
"for max_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root,",
"output_frame_seq, self._test_ext)) output_file_seq = os.path.join(self._test_root, output_file_seq) print(\"\\n\\n INPUT FILES\\n -----------\")",
"(self._test_file_name, output_frame_seq, self._test_ext)) output_file_seq = os.path.join(self._test_root, output_file_seq) print(\"\\n\\n INPUT FILES\\n",
"= FileSequence( name=file_path, ext=self._test_ext, frames=chunk_out) parser = get_parser() parser.scan_path(self._test_root) inverted",
"= os.path.join(self._test_root, file_seq_output) input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root)",
"= parser.singletons self.assertIn(self._test_root, file_names) self.assertEqual(self._test_root, file_names[self._test_root].path) self.assertEqual(len(file_names), 1) self.assertEqual( len(file_names[self._test_root]),",
"get_parser() parser.scan_path(self._test_root) file_names = parser.singletons self.assertIn(self._test_root, file_names) self.assertEqual(self._test_root, file_names[self._test_root].path) self.assertEqual(len(file_names),",
"\"\"\"Seqparse: Test API calls at root of module.\"\"\" chunk =",
"self.assertEqual(len(file_seq), 1) self.assertTrue(4 in file_seq[self._test_ext]) self.assertEqual(len(file_seq[self._test_ext]), 1) # And finally,",
"frames = {4: (1, 2, 3, 4, 6)} input_entries =",
"for seq in parser.output(): print(\" \", seq) print(\"\\n MAX LEVELS\\n",
"in bad_frame_seqs: print(' o {!r}'.format(frame_seq)) self.assertFalse(validate_frame_sequence(frame_seq)) print(\"\") def test_add_file_sequence(self): \"\"\"Seqparse:",
"finally, the file sequences. for pad in sorted(output_seqs): self.assertEqual(output_seqs[pad], str(file_seq[self._test_ext][pad]))",
"# Now check the file sequence itself. file_seq = data[self._test_root][self._test_file_name]",
"in nested directories.\"\"\" mock_api_call.side_effect = mock_scandir_deep print(\"\\n\\n SEQUENCES\\n ---------\") initialise_mock_scandir_data(self._test_root)",
"parser.scan_path(self._test_root) inverted = list(parser.output(missing=True)) self.assertEqual(len(inverted), 1) print(\"\\n\\n SEQUENCE\\n --------\") print(\"",
"\"0001-0007x2\") expected = FrameChunk(first=2, last=6, step=2, pad=4) inverted = invert(chunk)",
"---------\") initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root) for seq in parser.output():",
"the \"missing\" option in Seqparse.output.\"\"\" file_path = os.path.join(self._test_root, self._test_file_name) chunk_in",
"1, 2, 3, 4]} # Expected outputs ... frame_seq_output =",
"# test_dir/TEST_DIR.008-010,012,114,199.exr # test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr mock_api_call.return_value = iter(input_entries) parser = get_parser()",
"directories.\"\"\" mock_api_call.side_effect = mock_scandir_deep print(\"\\n\\n SEQUENCES\\n ---------\") initialise_mock_scandir_data(self._test_root) parser =",
"print(\"\") def test_add_file_sequence(self): \"\"\"Seqparse: Test file sequence addition via seqparse.add_file.\"\"\"",
"= list(parser.output()) blurb = \" o min_levels == {:d}: {:d}",
"o\", line) print(\"\\n EXPECTED OUTPUT\\n ---------------\") print(\" o\", output_file_seq) print(\"\")",
"2 if max_levels == -1: expected_seqs = 5 seqs =",
"= FileSequence( name=file_path, ext=self._test_ext, frames=chunk_in) input_entries = [DirEntry(x) for x",
"inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) @mock.patch(\"seqparse.seqparse.scandir\") def test_scan_options(self, mock_api_call): \"\"\"Seqparse:",
"OUTPUT\\n ---------------\") print(\" o\", output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq)",
"# test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr mock_api_call.return_value = iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) final_output",
"self._test_ext)) output_file_seq = os.path.join(self._test_root, output_file_seq) print(\"\\n\\n INPUT FILES\\n -----------\") print(\"",
"file sequence itself. file_seq = data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output),",
"print(\"\\n MIN LEVELS\\n ----------\") for min_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root)",
"inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) fseq = FileSequence( name=file_path, ext=self._test_ext,",
"case.\"\"\" pass @mock.patch(\"seqparse.seqparse.scandir\") def test_singletons(self, mock_api_call): \"\"\"Seqparse: Test file singleton",
"expected) self.assertEqual(output[0].ctime, 1490908340) self.assertEqual(output[0].mtime, 1490908305) self.assertEqual(output[0].size, 36520) parser = get_parser()",
"seqparse.add_file.\"\"\" input_file = \".\".join((self._test_file_name, \"0005\", self._test_ext)) input_file = os.path.join(self._test_root, input_file)",
"blurb = \" o min_levels == {:d}: {:d} ({:d} expected)",
"\".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) print(\"\\n INPUT",
"(self._test_file_name, frame_seq_output, self._test_ext)) final_output = os.path.join(self._test_root, file_seq_output) input_entries = generate_entries(",
"entries = list() for file_name in output: entries.append(DirEntry(file_name)) mock_api_call.return_value =",
"discovery on the seqparse module.\"\"\" _test_ext = \"exr\" _test_file_name =",
"\"0001,0003x2\", \"0001-0005x\", \"0010-0001\", \"x\", \",\", \",,\", \"\" ] print(\"\\n\\n GOOD",
"for frame_seq in good_frame_seqs: output = validate_frame_sequence(frame_seq) print(' o {!r}",
"name=file_path, ext=self._test_ext, frames=chunk_in) input_entries = [DirEntry(x) for x in fseq]",
"print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) @mock.patch(\"seqparse.seqparse.scandir\") def test_inversion(self, mock_api_call): \"\"\"Seqparse:",
"= \"test_dir\" _singletons = [\"singleton0.jpg\", \"singleton1.jpg\"] def setUp(self): \"\"\"Set up",
"[os.path.join(self._test_root, x) for x in self._singletons] entries = list() for",
"= \".\".join( (self._test_file_name, frame_seq_output, self._test_ext)) final_output = os.path.join(self._test_root, file_seq_output) input_entries",
"\".\".join( (self._test_file_name, frame_seq_output, self._test_ext)) final_output = os.path.join(self._test_root, file_seq_output) input_entries =",
"len(self._singletons)) self.assertEqual( sorted(self._singletons), sorted(file_names[self._test_root])) # Check parser output ... self.assertEqual(sorted(map(str,",
"\"\"\"Seqparse: Test file sequence addition via seqparse.add_file.\"\"\" input_file = \".\".join((self._test_file_name,",
"parser.scan_path(self._test_root) for seq in parser.output(): print(\" \", seq) print(\"\\n MAX",
"= get_parser() parser.scan_path(self._test_root, max_levels=max_levels) expected_seqs = max_levels + 2 if",
"--------\") print(\" input files: \", fseq) print(\" expected files:\", expected)",
"parser.scan_options[\"stat\"] = True parser.scan_path(self._test_root) output = list(parser.output()) expected = [",
"group! output_seqs = { 1: \"5-8\", 3: \"008-010,012,114,199\", 4: \"0000-0006,0008-0012x2,0101,2000\"",
"test_output)), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertEqual(set(file_seq[self._test_ext]), set(output_seqs)) # And",
"os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 2) self.assertEqual(list(map(str, output)), expected) self.assertEqual(output[0].ctime, 1490908340)",
"validate_frame_sequence) from ..sequences import FileSequence, FrameChunk, FrameSequence ############################################################################### # class:",
"\"singleton1.jpg\"] def setUp(self): \"\"\"Set up the test case.\"\"\" pass @mock.patch(\"seqparse.seqparse.scandir\")",
"= data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 3) self.assertEqual(list(map(str, test_output)), final_output)",
"frame ranges.\"\"\" good_frame_seqs = [ \"0001\", \",0001\", \"0001,\", \"0001-0001\", \"0001-0001x0\",",
"{4: [1]} # Expected outputs ... frame_seq_output = \"0001\" file_seq_output",
"expected = [ os.path.join(self._test_root, \".test.0001-0004,0006.py\"), os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ]",
"iter(entries) parser = get_parser() parser.scan_path(self._test_root) file_names = parser.singletons self.assertIn(self._test_root, file_names)",
"mock_api_call): \"\"\"Seqparse: Test simple file sequence discovery.\"\"\" frames = {4:",
"FileSequence( name=file_path, ext=self._test_ext, frames=chunk_in) input_entries = [DirEntry(x) for x in",
"= file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_complex_sequence(self, mock_api_call):",
"self.assertEqual( sorted(self._singletons), sorted(file_names[self._test_root])) # Check parser output ... self.assertEqual(sorted(map(str, parser.output())),",
"\"\"\"Seqparse: Test single padded file sequence discovery.\"\"\" frames = {4:",
"data) self.assertEqual(len(data), 1) self.assertIn(self._test_file_name, data[self._test_root]) self.assertEqual(len(data[self._test_root]), 1) # Now check",
"\"\"\"Seqparse: Test simple file sequence discovery.\"\"\" frames = {4: [0,",
"= generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) # Expected output frame",
"= [\"singleton0.jpg\", \"singleton1.jpg\"] def setUp(self): \"\"\"Set up the test case.\"\"\"",
"2, 3, 4, 6)} input_entries = generate_entries( name=\"test\", ext=\"py\", frames=frames,",
"invert, validate_frame_sequence) from ..sequences import FileSequence, FrameChunk, FrameSequence ############################################################################### #",
"output_file_seq) @mock.patch(\"seqparse.seqparse.scandir\") def test_inversion(self, mock_api_call): \"\"\"Seqparse: Test usage of the",
"sequence itself. file_seq = data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 1)",
"\"0001-0005,0006,0008-0012x2\", \"0001,0003-0007,0009-0015x2\", \"3,1,5,7\", \"01-05,03-07\" ] bad_frame_seqs = [ \"-0001\", \"0001-\",",
"Expected outputs ... output = [os.path.join(self._test_root, x) for x in",
"str(expected)) @mock.patch(\"seqparse.seqparse.scandir\") def test_scan_options(self, mock_api_call): \"\"\"Seqparse: Make sure scan_options works",
"test_dir/TEST_DIR.008-010,012,114,199.exr # test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr mock_api_call.return_value = iter(input_entries) parser = get_parser() parser.scan_path(self._test_root)",
"output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) @mock.patch(\"seqparse.seqparse.scandir\") def test_inversion(self, mock_api_call):",
"\"\"\"Seqparse: Test file singleton discovery from disk location.\"\"\" # Expected",
"Libraries import os import unittest # Third Party Libraries import",
"Third Party Libraries import mock from builtins import range from",
"initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, min_levels=min_levels) expected_seqs = 3 -",
"@mock.patch(\"seqparse.seqparse.scandir\") def test_complex_sequence(self, mock_api_call): \"\"\"Seqparse: Test complex file sequence discovery.\"\"\"",
"(self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) output_file_seq = \".\".join(",
"print(\"\\n INPUT FILES\\n -----------\") print(\" o\", input_file_seq) print(\" o\", input_file)",
"for file_name in output: entries.append(DirEntry(file_name)) mock_api_call.return_value = iter(entries) parser =",
"[ os.path.join(self._test_root, \".test.0001-0004,0006.py\"), os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 3)",
"check the file sequence itself. file_seq = data[self._test_root][self._test_file_name] test_output =",
"input_file_seq) print(\" o\", input_file) parser = get_parser() parser.add_file(input_file_seq) parser.add_file(input_file) output",
"o {!r}'.format(frame_seq)) self.assertFalse(validate_frame_sequence(frame_seq)) print(\"\") def test_add_file_sequence(self): \"\"\"Seqparse: Test file sequence",
"final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_simple_sequence(self, mock_api_call): \"\"\"Seqparse: Test simple file sequence",
"expected_seqs)) for seq in seqs: print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs)",
"..sequences import FileSequence, FrameChunk, FrameSequence ############################################################################### # class: TestSeqparseModule class",
"import (__version__, get_parser, get_sequence, get_version, invert, validate_frame_sequence) from ..sequences import",
"2, 3, 4]} # Expected outputs ... frame_seq_output = \"0000-0004\"",
"] self.assertEqual(len(output), 3) self.assertEqual(list(map(str, output)), expected) def test_api_calls(self): \"\"\"Seqparse: Test",
"inverted = invert(chunk) self.assertEqual(str(inverted), str(expected)) inverted = invert(seq) self.assertEqual(str(inverted), str(expected))",
"frames=[5], pad=4) parser = get_parser() parser.scan_path(self._test_root) inverted = list(parser.output(missing=True)) self.assertEqual(len(inverted),",
"seqs = list(parser.output()) blurb = \" o max_levels == {:d}:",
"ext=\"py\", frames=frames, root=self._test_root)) input_entries.append( DirEntry(os.path.join(self._test_root, \"pony.py\"))) mock_api_call.return_value = input_entries parser",
"parser.singletons self.assertIn(self._test_root, file_names) self.assertEqual(self._test_root, file_names[self._test_root].path) self.assertEqual(len(file_names), 1) self.assertEqual( len(file_names[self._test_root]), len(self._singletons))",
"import mock from builtins import range from future.utils import lrange",
"= list(parser.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) # Check the structure",
"get_sequence(lrange(1, 8, 2), pad=4) self.assertTrue(isinstance(seq, FrameSequence)) self.assertEqual(str(seq), \"0001-0007x2\") expected =",
"[5, 6, 7, 8, 114, 199, 2000], 3: [8, 9,",
"199 move to the # \"pad 3\" group and 2000",
"str(expected)) inverted = invert(seq) self.assertEqual(str(inverted), str(expected)) with self.assertRaises(TypeError): invert(get_parser()) self.assertEqual(get_version(),",
"\"pony.py\"))) mock_api_call.return_value = input_entries parser = get_parser() parser.scan_options[\"stat\"] = True",
"output (where \"/\" is os.sep): # test_dir/TEST_DIR.5-8.exr # test_dir/TEST_DIR.008-010,012,114,199.exr #",
"expected files:\", expected) print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) @mock.patch(\"seqparse.seqparse.scandir\")",
"mock_api_call): \"\"\"Seqparse: Test single padded file sequence discovery.\"\"\" frames =",
"seq in seqs: print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\") def",
"the \"pad 4\" group! output_seqs = { 1: \"5-8\", 3:",
"frames = { 1: [5, 6, 7, 8, 114, 199,",
"= parser.sequences # Check the structure of the sequences property.",
"in self._singletons] entries = list() for file_name in output: entries.append(DirEntry(file_name))",
"validity of simple frame ranges.\"\"\" good_frame_seqs = [ \"0001\", \",0001\",",
"(__version__, get_parser, get_sequence, get_version, invert, validate_frame_sequence) from ..sequences import FileSequence,",
"def test_single_padded_file(self, mock_api_call): \"\"\"Seqparse: Test single padded file sequence discovery.\"\"\"",
"3, 4, 6)} input_entries = generate_entries( name=\"test\", ext=\"py\", frames=frames, root=self._test_root)",
"self._test_ext) output_seqs[pad] = os.path.join(self._test_root, \".\".join(bits)) final_output.append(output_seqs[pad]) data = parser.sequences #",
"parser = get_parser() parser.scan_path(self._test_root) data = parser.sequences test_output = list(parser.output())",
"pad, seq_frames in sorted(output_seqs.items()): bits = (self._test_file_name, seq_frames, self._test_ext) output_seqs[pad]",
"FrameSequence)) self.assertEqual(str(seq), \"0001-0007x2\") expected = FrameChunk(first=2, last=6, step=2, pad=4) inverted",
"print(\" o\", input_file) parser = get_parser() parser.add_file(input_file_seq) parser.add_file(input_file) output =",
"def setUp(self): \"\"\"Set up the test case.\"\"\" pass @mock.patch(\"seqparse.seqparse.scandir\") def",
"print(blurb.format(max_levels, len(seqs), expected_seqs)) for seq in seqs: print(\" -\", seq)",
"# Standard Libraries import os import unittest # Third Party",
"initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root) for seq in parser.output(): print(\"",
"file_names = parser.singletons self.assertIn(self._test_root, file_names) self.assertEqual(self._test_root, file_names[self._test_root].path) self.assertEqual(len(file_names), 1) self.assertEqual(",
"7, 8, 114, 199, 2000], 3: [8, 9, 10, 12],",
"seq) self.assertEqual(len(seqs), expected_seqs) print(\"\\n MIN LEVELS\\n ----------\") for min_levels in",
"\"0001-0005,0007-0011x2\", \"0001-0005,0006,0008-0012x2\", \"0001,0003-0007,0009-0015x2\", \"3,1,5,7\", \"01-05,03-07\" ] bad_frame_seqs = [ \"-0001\",",
"final_output = os.path.join(self._test_root, file_seq_output) input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name,",
"10, 12], 4: [0, 1, 2, 3, 4, 5, 6,",
"@mock.patch(\"seqparse.seqparse.scandir\") def test_singletons(self, mock_api_call): \"\"\"Seqparse: Test file singleton discovery from",
"parser = get_parser() parser.scan_path(self._test_root) final_output = list() for pad, seq_frames",
"sorted(output_seqs): self.assertEqual(output_seqs[pad], str(file_seq[self._test_ext][pad])) @mock.patch(\"seqparse.seqparse.scandir\") def test_nested_sequences(self, mock_api_call): \"\"\"Seqparse: Test file",
"+ 2 if max_levels == -1: expected_seqs = 5 seqs",
"\"0001\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output, self._test_ext)) final_output = os.path.join(self._test_root,",
"\",\", \",,\", \"\" ] print(\"\\n\\n GOOD SEQUENCES\\n --------------\") for frame_seq",
"root=self._test_root) mock_api_call.return_value = iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) data =",
"# And finally, the file sequences. for pad in sorted(output_seqs):",
"self.assertEqual(str(test_output[0]), final_output) # Check the structure of the sequences property.",
"parser = get_parser() parser.add_file(input_file_seq) parser.add_file(input_file) output = list(parser.output()) print(\"\\n OUTPUT",
"Standard Libraries import os import unittest # Third Party Libraries",
"---------------\") print(\" o\", output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) input_frame_seq",
"output_file_seq) input_frame_seq = \"0000-0002,,0003-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq, self._test_ext))",
"of the \"missing\" option in Seqparse.output.\"\"\" file_path = os.path.join(self._test_root, self._test_file_name)",
"expected = FrameChunk(first=2, last=6, step=2, pad=4) inverted = invert(chunk) self.assertEqual(str(inverted),",
"True parser.scan_path(self._test_root) output = list(parser.output()) expected = [ os.path.join(self._test_root, \".test.0001-0004,0006.py\"),",
"final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertTrue(4 in file_seq[self._test_ext]) self.assertEqual(len(file_seq[self._test_ext]), 1)",
"in sorted(output_seqs.items()): bits = (self._test_file_name, seq_frames, self._test_ext) output_seqs[pad] = os.path.join(self._test_root,",
"expected) entries\" print(blurb.format(max_levels, len(seqs), expected_seqs)) for seq in seqs: print(\"",
"usage of the \"missing\" option in Seqparse.output.\"\"\" file_path = os.path.join(self._test_root,",
"os.path.join(self._test_root, self._test_file_name) chunk_in = FrameChunk(first=1, last=11, step=2, pad=4) fseq =",
"frames=chunk_out) parser = get_parser() parser.scan_path(self._test_root) inverted = list(parser.output(missing=True)) self.assertEqual(len(inverted), 1)",
"pad=4) input_entries = [DirEntry(x) for x in fseq] mock_api_call.return_value =",
"== -1: expected_seqs = 5 seqs = list(parser.output()) blurb =",
"get_parser() parser.scan_options[\"stat\"] = True parser.scan_path(self._test_root) output = list(parser.output()) expected =",
"1) self.assertEqual(str(test_output[0]), final_output) # Check the structure of the sequences",
"in seqs: print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\\n MIN LEVELS\\n",
"input_file_seq) output_file_seq = \".\".join( (self._test_file_name, output_frame_seq, self._test_ext)) output_file_seq = os.path.join(self._test_root,",
"output_file_seq = os.path.join(self._test_root, output_file_seq) print(\"\\n\\n INPUT FILES\\n -----------\") print(\" o\",",
"module.\"\"\" _test_ext = \"exr\" _test_file_name = \"TEST_DIR\" _test_root = \"test_dir\"",
"max_levels == -1: expected_seqs = 5 seqs = list(parser.output()) blurb",
"\"\"\"Seqparse: Test usage of the \"missing\" option in Seqparse.output.\"\"\" file_path",
"parser = get_parser() parser.scan_path(self._test_root, min_levels=min_levels) expected_seqs = 3 - min_levels",
"list(file_seq.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertTrue(4",
"= 5 seqs = list(parser.output()) blurb = \" o max_levels",
"GOOD SEQUENCES\\n --------------\") for frame_seq in good_frame_seqs: output = validate_frame_sequence(frame_seq)",
"\"\"\"Seqparse: Test complex file sequence discovery.\"\"\" frames = { 1:",
"the file sequence. file_seq = file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output)",
"test_output = list(file_seq.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq),",
"self.assertEqual(len(inverted), 1) print(\"\\n\\n SEQUENCE\\n --------\") print(\" input files: \", fseq)",
"= True parser.scan_path(self._test_root) output = list(parser.output()) expected = [ os.path.join(self._test_root,",
"self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) input_frame_seq = \"0000-0002,,0003-0005\" input_file_seq = \".\".join(",
"[0, 1, 2, 3, 4, 5, 6, 8, 10, 12,",
"= input_entries chunk_out = FrameChunk(first=2, last=10, step=2, pad=4) expected =",
"\"pad 3\" group and 2000 moves to the \"pad 4\"",
"114, 199, 2000], 3: [8, 9, 10, 12], 4: [0,",
"self.assertEqual(sorted(parser.output(seqs_only=True)), []) @mock.patch(\"seqparse.seqparse.scandir\") def test_single_padded_file(self, mock_api_call): \"\"\"Seqparse: Test single padded",
"\"missing\" option in Seqparse.output.\"\"\" file_path = os.path.join(self._test_root, self._test_file_name) chunk_in =",
"seq) print(\"\\n MAX LEVELS\\n ----------\") for max_levels in range(-1, 4):",
"[ \"0001\", \",0001\", \"0001,\", \"0001-0001\", \"0001-0001x0\", \"0001-0003x3\", \"0001,0003\", \"0001,,0003\", \"0001-0010\",",
"1) self.assertTrue(4 in file_seq[self._test_ext]) self.assertEqual(len(file_seq[self._test_ext]), 1) # And finally, the",
"mock_api_call): \"\"\"Seqparse: Make sure scan_options works as expected.\"\"\" frames =",
"= list(file_seq.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1)",
"input_entries.extend( generate_entries( name=\".test\", ext=\"py\", frames=frames, root=self._test_root)) input_entries.append( DirEntry(os.path.join(self._test_root, \"pony.py\"))) mock_api_call.return_value",
"Check parser output ... self.assertEqual(sorted(map(str, parser.output())), output) # Test seqs_only",
"list(parser.output()) expected = [ os.path.join(self._test_root, \".test.0001-0004,0006.py\"), os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\")",
"print(blurb.format(min_levels, len(seqs), expected_seqs)) for seq in seqs: print(\" -\", seq)",
"def test_complex_sequence(self, mock_api_call): \"\"\"Seqparse: Test complex file sequence discovery.\"\"\" frames",
"sequence addition via seqparse.add_file.\"\"\" input_file = \".\".join((self._test_file_name, \"0005\", self._test_ext)) input_file",
"= \"0001\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output, self._test_ext)) final_output =",
"discovery.\"\"\" frames = {4: [1]} # Expected outputs ... frame_seq_output",
"\"0001-0005x\", \"0010-0001\", \"x\", \",\", \",,\", \"\" ] print(\"\\n\\n GOOD SEQUENCES\\n",
"expected = FileSequence( name=file_path, ext=self._test_ext, frames=[5], pad=4) parser = get_parser()",
"8, 2), pad=4) self.assertTrue(isinstance(seq, FrameSequence)) self.assertEqual(str(seq), \"0001-0007x2\") expected = FrameChunk(first=2,",
"{:d} ({:d} expected) entries\" print(blurb.format(max_levels, len(seqs), expected_seqs)) for seq in",
"... self.assertEqual(sorted(map(str, parser.output())), output) # Test seqs_only option ... self.assertEqual(sorted(parser.output(seqs_only=True)),",
"iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) final_output = list() for pad,",
"seqs: print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\") def test_valid_frame_sequences(self): \"\"\"Seqparse:",
"data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 3) self.assertEqual(list(map(str, test_output)), final_output) self.assertIn(self._test_ext,",
"= get_parser() parser.scan_options[\"all\"] = True parser.scan_path(self._test_root) output = list(parser.output()) expected",
"parser.add_file(input_file) output = list(parser.output()) print(\"\\n OUTPUT FILES\\n ------------\") for line",
"= \"0000-0002,,0003-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq =",
"= iter(entries) parser = get_parser() parser.scan_path(self._test_root) file_names = parser.singletons self.assertIn(self._test_root,",
"expected_seqs = 3 - min_levels if min_levels == -1: expected_seqs",
"for pad, seq_frames in sorted(output_seqs.items()): bits = (self._test_file_name, seq_frames, self._test_ext)",
"import unittest # Third Party Libraries import mock from builtins",
"= \"0000-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq =",
"if min_levels == -1: expected_seqs = 5 seqs = list(parser.output())",
"test_add_file_sequence(self): \"\"\"Seqparse: Test file sequence addition via seqparse.add_file.\"\"\" input_file =",
"= \".\".join( (self._test_file_name, output_frame_seq, self._test_ext)) output_file_seq = os.path.join(self._test_root, output_file_seq) print(\"\\n\\n",
"from builtins import range from future.utils import lrange from .",
"sorted(file_names[self._test_root])) # Check parser output ... self.assertEqual(sorted(map(str, parser.output())), output) #",
"max_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, max_levels=max_levels)",
"\"test_dir\" _singletons = [\"singleton0.jpg\", \"singleton1.jpg\"] def setUp(self): \"\"\"Set up the",
"frames=frames, name=self._test_file_name, root=self._test_root) # Expected output frame sequences. Note how",
"validate_frame_sequence(frame_seq) print(' o {!r} --> {!r}'.format(frame_seq, output)) self.assertTrue(output) print(\"\\n BAD",
"Test file sequence addition via seqparse.add_file.\"\"\" input_file = \".\".join((self._test_file_name, \"0005\",",
"property. self.assertIn(self._test_root, data) self.assertEqual(len(data), 1) self.assertIn(self._test_file_name, data[self._test_root]) self.assertEqual(len(data[self._test_root]), 1) #",
"\"0001,,0003\", \"0001-0010\", \"0001-0010x0\", \"0001-0011x2\", \"0001-0012x2\", \"0001-0005,0007-0010\", \"0001-0005x2,0007-0010\", \"0001-0005,0007-0011x2\", \"0001-0005,0006,0008-0012x2\", \"0001,0003-0007,0009-0015x2\",",
"moves to the \"pad 4\" group! output_seqs = { 1:",
"import os import unittest # Third Party Libraries import mock",
"FileSequence, FrameChunk, FrameSequence ############################################################################### # class: TestSeqparseModule class TestSeqparseModule(unittest.TestCase): \"\"\"Test",
"[]) @mock.patch(\"seqparse.seqparse.scandir\") def test_single_padded_file(self, mock_api_call): \"\"\"Seqparse: Test single padded file",
"def test_singletons(self, mock_api_call): \"\"\"Seqparse: Test file singleton discovery from disk",
"= \".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) output_file_seq",
"1) self.assertEqual(set(file_seq[self._test_ext]), set(output_seqs)) # And finally, the file sequences. for",
"= 5 seqs = list(parser.output()) blurb = \" o min_levels",
"frame_seq in bad_frame_seqs: print(' o {!r}'.format(frame_seq)) self.assertFalse(validate_frame_sequence(frame_seq)) print(\"\") def test_add_file_sequence(self):",
"input_file) parser = get_parser() parser.add_file(input_file_seq) parser.add_file(input_file) output = list(parser.output()) print(\"\\n",
"1) self.assertEqual(str(output[0]), output_file_seq) input_frame_seq = \"0000-0002,,0003-0005\" input_file_seq = \".\".join( (self._test_file_name,",
"6], pad=4) input_entries = [DirEntry(x) for x in fseq] mock_api_call.return_value",
"= \"0000-0004\" output_frame_seq = \"0000-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq,",
"(where \"/\" is os.sep): # test_dir/TEST_DIR.5-8.exr # test_dir/TEST_DIR.008-010,012,114,199.exr # test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr",
"self.assertEqual(output[0].ctime, 1490908340) self.assertEqual(output[0].mtime, 1490908305) self.assertEqual(output[0].size, 36520) parser = get_parser() parser.scan_options[\"all\"]",
"final_output) # Check the structure of the sequences property. self.assertIn(self._test_root,",
"= max_levels + 2 if max_levels == -1: expected_seqs =",
"group and 2000 moves to the \"pad 4\" group! output_seqs",
"self.assertTrue(4 in file_seq[self._test_ext]) self.assertEqual(len(file_seq[self._test_ext]), 1) # And finally, the file",
"sequence discovery.\"\"\" frames = {4: [1]} # Expected outputs ...",
"get_parser() parser.scan_path(self._test_root) data = parser.sequences test_output = list(parser.output()) self.assertEqual(len(test_output), 1)",
"initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, max_levels=max_levels) expected_seqs = max_levels +",
"name=file_path, ext=self._test_ext, frames=[1, 2, 3, 4, 6], pad=4) input_entries =",
"parser = get_parser() parser.scan_path(self._test_root, max_levels=max_levels) expected_seqs = max_levels + 2",
"Test file singleton discovery from disk location.\"\"\" # Expected outputs",
"bits = (self._test_file_name, seq_frames, self._test_ext) output_seqs[pad] = os.path.join(self._test_root, \".\".join(bits)) final_output.append(output_seqs[pad])",
"self.assertIn(self._test_root, data) self.assertEqual(len(data), 1) self.assertIn(self._test_file_name, data[self._test_root]) self.assertEqual(len(data[self._test_root]), 1) # Now",
"--> {!r}'.format(frame_seq, output)) self.assertTrue(output) print(\"\\n BAD SEQUENCES\\n -------------\") for frame_seq",
"3) self.assertEqual(list(map(str, output)), expected) def test_api_calls(self): \"\"\"Seqparse: Test API calls",
"def test_valid_frame_sequences(self): \"\"\"Seqparse: Test validity of simple frame ranges.\"\"\" good_frame_seqs",
"test_output = list(parser.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) # Check the",
"Check the structure of the sequences property. self.assertIn(self._test_root, data) self.assertEqual(len(data),",
"= list(file_seq.output()) self.assertEqual(len(test_output), 3) self.assertEqual(list(map(str, test_output)), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq),",
"{!r}'.format(frame_seq)) self.assertFalse(validate_frame_sequence(frame_seq)) print(\"\") def test_add_file_sequence(self): \"\"\"Seqparse: Test file sequence addition",
"MAX LEVELS\\n ----------\") for max_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser",
"print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) input_frame_seq = \"0000-0002,,0003-0005\" input_file_seq =",
"in output: entries.append(DirEntry(file_name)) mock_api_call.return_value = iter(entries) parser = get_parser() parser.scan_path(self._test_root)",
"\"0001\", \",0001\", \"0001,\", \"0001-0001\", \"0001-0001x0\", \"0001-0003x3\", \"0001,0003\", \"0001,,0003\", \"0001-0010\", \"0001-0010x0\",",
"\"0000-0004\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output, self._test_ext)) final_output = os.path.join(self._test_root,",
"chunk_out = FrameChunk(first=2, last=10, step=2, pad=4) expected = FileSequence( name=file_path,",
"self.assertFalse(validate_frame_sequence(frame_seq)) print(\"\") def test_add_file_sequence(self): \"\"\"Seqparse: Test file sequence addition via",
"1490908340) self.assertEqual(output[0].mtime, 1490908305) self.assertEqual(output[0].size, 36520) parser = get_parser() parser.scan_options[\"all\"] =",
"set(output_seqs)) # And finally, the file sequences. for pad in",
"test_api_calls(self): \"\"\"Seqparse: Test API calls at root of module.\"\"\" chunk",
"from __future__ import print_function # Standard Libraries import os import",
"= {4: [1]} # Expected outputs ... frame_seq_output = \"0001\"",
"(DirEntry, generate_entries, initialise_mock_scandir_data, mock_scandir_deep) from .. import (__version__, get_parser, get_sequence,",
"self.assertEqual(str(inverted[0]), str(expected)) fseq = FileSequence( name=file_path, ext=self._test_ext, frames=[1, 2, 3,",
"self.assertEqual(len(seqs), expected_seqs) print(\"\\n MIN LEVELS\\n ----------\") for min_levels in range(-1,",
"output)), expected) self.assertEqual(output[0].ctime, 1490908340) self.assertEqual(output[0].mtime, 1490908305) self.assertEqual(output[0].size, 36520) parser =",
"frame_seq_output = \"0000-0004\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output, self._test_ext)) final_output",
"os.path.join(self._test_root, input_file_seq) output_file_seq = \".\".join( (self._test_file_name, output_frame_seq, self._test_ext)) output_file_seq =",
"output_seqs[pad] = os.path.join(self._test_root, \".\".join(bits)) final_output.append(output_seqs[pad]) data = parser.sequences # Check",
"scan_options works as expected.\"\"\" frames = {4: (1, 2, 3,",
"step=2, pad=4) seq = get_sequence(lrange(1, 8, 2), pad=4) self.assertTrue(isinstance(seq, FrameSequence))",
"] print(\"\\n\\n GOOD SEQUENCES\\n --------------\") for frame_seq in good_frame_seqs: output",
"5, 6, 8, 10, 12, 101] } input_entries = generate_entries(",
"FrameSequence ############################################################################### # class: TestSeqparseModule class TestSeqparseModule(unittest.TestCase): \"\"\"Test file discovery",
"sequence discovery.\"\"\" frames = {4: [0, 1, 2, 3, 4]}",
"3: \"008-010,012,114,199\", 4: \"0000-0006,0008-0012x2,0101,2000\" } # Expected final output (where",
"114, 199 move to the # \"pad 3\" group and",
"good_frame_seqs = [ \"0001\", \",0001\", \"0001,\", \"0001-0001\", \"0001-0001x0\", \"0001-0003x3\", \"0001,0003\",",
"{!r}'.format(frame_seq, output)) self.assertTrue(output) print(\"\\n BAD SEQUENCES\\n -------------\") for frame_seq in",
"# test_dir/TEST_DIR.5-8.exr # test_dir/TEST_DIR.008-010,012,114,199.exr # test_dir/TEST_DIR.0000-0006,0008-0012x2,0101,2000.exr mock_api_call.return_value = iter(input_entries) parser",
"{4: [0, 1, 2, 3, 4]} # Expected outputs ...",
"line in output: print(\" o\", line) print(\"\\n EXPECTED OUTPUT\\n ---------------\")",
"mock_api_call): \"\"\"Seqparse: Test file sequence discovery in nested directories.\"\"\" mock_api_call.side_effect",
"how frames 114, 199 move to the # \"pad 3\"",
"2, 3, 4, 6], pad=4) input_entries = [DirEntry(x) for x",
"input_frame_seq = \"0000-0004\" output_frame_seq = \"0000-0005\" input_file_seq = \".\".join( (self._test_file_name,",
"import FileSequence, FrameChunk, FrameSequence ############################################################################### # class: TestSeqparseModule class TestSeqparseModule(unittest.TestCase):",
"outputs ... frame_seq_output = \"0001\" file_seq_output = \".\".join( (self._test_file_name, frame_seq_output,",
"= iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) final_output = list() for",
"self.assertEqual(len(file_seq), 1) self.assertEqual(set(file_seq[self._test_ext]), set(output_seqs)) # And finally, the file sequences.",
"36520) parser = get_parser() parser.scan_options[\"all\"] = True parser.scan_path(self._test_root) output =",
"\"\" ] print(\"\\n\\n GOOD SEQUENCES\\n --------------\") for frame_seq in good_frame_seqs:",
"discovery in nested directories.\"\"\" mock_api_call.side_effect = mock_scandir_deep print(\"\\n\\n SEQUENCES\\n ---------\")",
"SEQUENCES\\n ---------\") initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root) for seq in",
"max_levels == {:d}: {:d} ({:d} expected) entries\" print(blurb.format(max_levels, len(seqs), expected_seqs))",
"files:\", expected) print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) fseq =",
"parser.sequences # Check the structure of the sequences property. self.assertIn(self._test_root,",
"Test validity of simple frame ranges.\"\"\" good_frame_seqs = [ \"0001\",",
"expected.\"\"\" frames = {4: (1, 2, 3, 4, 6)} input_entries",
"sequences. for pad in sorted(output_seqs): self.assertEqual(output_seqs[pad], str(file_seq[self._test_ext][pad])) @mock.patch(\"seqparse.seqparse.scandir\") def test_nested_sequences(self,",
"self._test_file_name) chunk_in = FrameChunk(first=1, last=11, step=2, pad=4) fseq = FileSequence(",
"Test complex file sequence discovery.\"\"\" frames = { 1: [5,",
"API calls at root of module.\"\"\" chunk = FrameChunk(first=1, last=7,",
"= [os.path.join(self._test_root, x) for x in self._singletons] entries = list()",
"And finally, the file sequence. file_seq = file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4]))",
"inverted = list(parser.output(missing=True)) self.assertEqual(len(inverted), 1) print(\"\\n\\n SEQUENCE\\n --------\") print(\" input",
"= [ os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 2) self.assertEqual(list(map(str,",
"input_file_seq = os.path.join(self._test_root, input_file_seq) print(\"\\n INPUT FILES\\n -----------\") print(\" o\",",
"test_scan_options(self, mock_api_call): \"\"\"Seqparse: Make sure scan_options works as expected.\"\"\" frames",
"= \" o min_levels == {:d}: {:d} ({:d} expected) entries\"",
"print(\" o\", output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) @mock.patch(\"seqparse.seqparse.scandir\") def",
"test_singletons(self, mock_api_call): \"\"\"Seqparse: Test file singleton discovery from disk location.\"\"\"",
"\"0001,\", \"0001-0001\", \"0001-0001x0\", \"0001-0003x3\", \"0001,0003\", \"0001,,0003\", \"0001-0010\", \"0001-0010x0\", \"0001-0011x2\", \"0001-0012x2\",",
"\".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) output_file_seq =",
"\"0001-0010\", \"0001-0010x0\", \"0001-0011x2\", \"0001-0012x2\", \"0001-0005,0007-0010\", \"0001-0005x2,0007-0010\", \"0001-0005,0007-0011x2\", \"0001-0005,0006,0008-0012x2\", \"0001,0003-0007,0009-0015x2\", \"3,1,5,7\",",
"(self._test_file_name, seq_frames, self._test_ext) output_seqs[pad] = os.path.join(self._test_root, \".\".join(bits)) final_output.append(output_seqs[pad]) data =",
"Test API calls at root of module.\"\"\" chunk = FrameChunk(first=1,",
"generate_entries( name=\"test\", ext=\"py\", frames=frames, root=self._test_root) input_entries.extend( generate_entries( name=\".test\", ext=\"py\", frames=frames,",
"Party Libraries import mock from builtins import range from future.utils",
"({:d} expected) entries\" print(blurb.format(min_levels, len(seqs), expected_seqs)) for seq in seqs:",
"expected) entries\" print(blurb.format(min_levels, len(seqs), expected_seqs)) for seq in seqs: print(\"",
"os.path.join(self._test_root, output_file_seq) print(\"\\n\\n INPUT FILES\\n -----------\") print(\" o\", input_file_seq) print(\"",
"Expected final output (where \"/\" is os.sep): # test_dir/TEST_DIR.5-8.exr #",
"print(\"\\n MAX LEVELS\\n ----------\") for max_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root)",
"seq_frames in sorted(output_seqs.items()): bits = (self._test_file_name, seq_frames, self._test_ext) output_seqs[pad] =",
"self.assertEqual(str(test_output[0]), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertTrue(4 in file_seq[self._test_ext]) self.assertEqual(len(file_seq[self._test_ext]),",
"199, 2000], 3: [8, 9, 10, 12], 4: [0, 1,",
"self.assertEqual(self._test_root, file_names[self._test_root].path) self.assertEqual(len(file_names), 1) self.assertEqual( len(file_names[self._test_root]), len(self._singletons)) self.assertEqual( sorted(self._singletons), sorted(file_names[self._test_root]))",
"1, 2, 3, 4, 5, 6, 8, 10, 12, 101]",
"self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_simple_sequence(self, mock_api_call): \"\"\"Seqparse: Test",
"parser = get_parser() parser.scan_options[\"stat\"] = True parser.scan_path(self._test_root) output = list(parser.output())",
"iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) data = parser.sequences test_output =",
"\"0001-0005,0007-0010\", \"0001-0005x2,0007-0010\", \"0001-0005,0007-0011x2\", \"0001-0005,0006,0008-0012x2\", \"0001,0003-0007,0009-0015x2\", \"3,1,5,7\", \"01-05,03-07\" ] bad_frame_seqs =",
"parser.scan_path(self._test_root) file_names = parser.singletons self.assertIn(self._test_root, file_names) self.assertEqual(self._test_root, file_names[self._test_root].path) self.assertEqual(len(file_names), 1)",
"9, 10, 12], 4: [0, 1, 2, 3, 4, 5,",
"\"x\", \",\", \",,\", \"\" ] print(\"\\n\\n GOOD SEQUENCES\\n --------------\") for",
"in fseq] mock_api_call.return_value = input_entries expected = FileSequence( name=file_path, ext=self._test_ext,",
"parser.scan_path(self._test_root) output = list(parser.output()) expected = [ os.path.join(self._test_root, \".test.0001-0004,0006.py\"), os.path.join(self._test_root,",
"frames=frames, root=self._test_root) input_entries.extend( generate_entries( name=\".test\", ext=\"py\", frames=frames, root=self._test_root)) input_entries.append( DirEntry(os.path.join(self._test_root,",
"mock_api_call.side_effect = mock_scandir_deep print(\"\\n\\n SEQUENCES\\n ---------\") initialise_mock_scandir_data(self._test_root) parser = get_parser()",
"self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_simple_sequence(self, mock_api_call): \"\"\"Seqparse: Test simple file",
"works as expected.\"\"\" frames = {4: (1, 2, 3, 4,",
"4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, max_levels=max_levels) expected_seqs = max_levels",
"[ os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 2) self.assertEqual(list(map(str, output)),",
"mock_scandir_deep print(\"\\n\\n SEQUENCES\\n ---------\") initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root) for",
"seqs = list(parser.output()) blurb = \" o min_levels == {:d}:",
"single padded file sequence discovery.\"\"\" frames = {4: [1]} #",
"entries\" print(blurb.format(min_levels, len(seqs), expected_seqs)) for seq in seqs: print(\" -\",",
"as expected.\"\"\" frames = {4: (1, 2, 3, 4, 6)}",
"import range from future.utils import lrange from . import (DirEntry,",
"o\", output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) input_frame_seq = \"0000-0002,,0003-0005\"",
"input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) output_file_seq = \".\".join( (self._test_file_name,",
"singleton discovery from disk location.\"\"\" # Expected outputs ... output",
"Test seqs_only option ... self.assertEqual(sorted(parser.output(seqs_only=True)), []) @mock.patch(\"seqparse.seqparse.scandir\") def test_single_padded_file(self, mock_api_call):",
"for x in fseq] mock_api_call.return_value = input_entries chunk_out = FrameChunk(first=2,",
"output)), expected) def test_api_calls(self): \"\"\"Seqparse: Test API calls at root",
"-----------\") print(\" o\", input_file_seq) print(\" o\", input_file) parser = get_parser()",
"parser.output(): print(\" \", seq) print(\"\\n MAX LEVELS\\n ----------\") for max_levels",
"step=2, pad=4) expected = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_out) parser =",
"= mock_scandir_deep print(\"\\n\\n SEQUENCES\\n ---------\") initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root)",
"file sequences. for pad in sorted(output_seqs): self.assertEqual(output_seqs[pad], str(file_seq[self._test_ext][pad])) @mock.patch(\"seqparse.seqparse.scandir\") def",
"get_sequence, get_version, invert, validate_frame_sequence) from ..sequences import FileSequence, FrameChunk, FrameSequence",
"final_output = list() for pad, seq_frames in sorted(output_seqs.items()): bits =",
"get_parser() parser.scan_path(self._test_root, max_levels=max_levels) expected_seqs = max_levels + 2 if max_levels",
"min_levels=min_levels) expected_seqs = 3 - min_levels if min_levels == -1:",
"mock_api_call.return_value = iter(input_entries) parser = get_parser() parser.scan_path(self._test_root) data = parser.sequences",
"self.assertIn(self._test_file_name, data[self._test_root]) self.assertEqual(len(data[self._test_root]), 1) # Now check the file sequence",
"class TestSeqparseModule(unittest.TestCase): \"\"\"Test file discovery on the seqparse module.\"\"\" _test_ext",
"4\" group! output_seqs = { 1: \"5-8\", 3: \"008-010,012,114,199\", 4:",
"\"0005\", self._test_ext)) input_file = os.path.join(self._test_root, input_file) # Expected outputs ...",
"output_seqs = { 1: \"5-8\", 3: \"008-010,012,114,199\", 4: \"0000-0006,0008-0012x2,0101,2000\" }",
"\"0001-0005x2,0007-0010\", \"0001-0005,0007-0011x2\", \"0001-0005,0006,0008-0012x2\", \"0001,0003-0007,0009-0015x2\", \"3,1,5,7\", \"01-05,03-07\" ] bad_frame_seqs = [",
"parser.sequences test_output = list(parser.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) # Check",
"2000 moves to the \"pad 4\" group! output_seqs = {",
"\"pony.py\") ] self.assertEqual(len(output), 2) self.assertEqual(list(map(str, output)), expected) self.assertEqual(output[0].ctime, 1490908340) self.assertEqual(output[0].mtime,",
"Test single padded file sequence discovery.\"\"\" frames = {4: [1]}",
"self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertEqual(set(file_seq[self._test_ext]), set(output_seqs)) # And finally, the",
"= os.path.join(self._test_root, input_file) # Expected outputs ... input_frame_seq = \"0000-0004\"",
"{4: (1, 2, 3, 4, 6)} input_entries = generate_entries( name=\"test\",",
"input_entries = generate_entries( ext=self._test_ext, frames=frames, name=self._test_file_name, root=self._test_root) # Expected output",
"the structure of the sequences property. self.assertIn(self._test_root, data) self.assertEqual(len(data), 1)",
"(self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) print(\"\\n INPUT FILES\\n",
"expected) print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) fseq = FileSequence(",
"frames = {4: [1]} # Expected outputs ... frame_seq_output =",
"frames=frames, name=self._test_file_name, root=self._test_root) mock_api_call.return_value = iter(input_entries) parser = get_parser() parser.scan_path(self._test_root)",
"# Expected output frame sequences. Note how frames 114, 199",
"input_file) # Expected outputs ... input_frame_seq = \"0000-0004\" output_frame_seq =",
"\".\".join(bits)) final_output.append(output_seqs[pad]) data = parser.sequences # Check the structure of",
"= [DirEntry(x) for x in fseq] mock_api_call.return_value = input_entries expected",
"print(\" expected files:\", expected) print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected))",
"for min_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root,",
"data[self._test_root][self._test_file_name] test_output = list(file_seq.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) self.assertIn(self._test_ext, file_seq)",
"Expected outputs ... input_frame_seq = \"0000-0004\" output_frame_seq = \"0000-0005\" input_file_seq",
"line) print(\"\\n EXPECTED OUTPUT\\n ---------------\") print(\" o\", output_file_seq) print(\"\") self.assertEqual(len(output),",
"def test_api_calls(self): \"\"\"Seqparse: Test API calls at root of module.\"\"\"",
"discovery from disk location.\"\"\" # Expected outputs ... output =",
"\" o max_levels == {:d}: {:d} ({:d} expected) entries\" print(blurb.format(max_levels,",
"self.assertEqual(str(output[0]), output_file_seq) input_frame_seq = \"0000-0002,,0003-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq,",
"self.assertEqual(str(output[0]), output_file_seq) @mock.patch(\"seqparse.seqparse.scandir\") def test_inversion(self, mock_api_call): \"\"\"Seqparse: Test usage of",
"_test_root = \"test_dir\" _singletons = [\"singleton0.jpg\", \"singleton1.jpg\"] def setUp(self): \"\"\"Set",
"# Check parser output ... self.assertEqual(sorted(map(str, parser.output())), output) # Test",
"FileSequence( name=file_path, ext=self._test_ext, frames=chunk_out) parser = get_parser() parser.scan_path(self._test_root) inverted =",
"4, 6], pad=4) input_entries = [DirEntry(x) for x in fseq]",
"\"exr\" _test_file_name = \"TEST_DIR\" _test_root = \"test_dir\" _singletons = [\"singleton0.jpg\",",
"input_file_seq) print(\"\\n INPUT FILES\\n -----------\") print(\" o\", input_file_seq) print(\" o\",",
"input_entries.append( DirEntry(os.path.join(self._test_root, \"pony.py\"))) mock_api_call.return_value = input_entries parser = get_parser() parser.scan_options[\"stat\"]",
"expected = [ os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 2)",
"\"5-8\", 3: \"008-010,012,114,199\", 4: \"0000-0006,0008-0012x2,0101,2000\" } # Expected final output",
"file_seq_output = \".\".join( (self._test_file_name, frame_seq_output, self._test_ext)) final_output = os.path.join(self._test_root, file_seq_output)",
"--------------\") for frame_seq in good_frame_seqs: output = validate_frame_sequence(frame_seq) print(' o",
"name=file_path, ext=self._test_ext, frames=chunk_out) parser = get_parser() parser.scan_path(self._test_root) inverted = list(parser.output(missing=True))",
"expected = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_out) parser = get_parser() parser.scan_path(self._test_root)",
"invert(chunk) self.assertEqual(str(inverted), str(expected)) inverted = invert(seq) self.assertEqual(str(inverted), str(expected)) with self.assertRaises(TypeError):",
"output = [os.path.join(self._test_root, x) for x in self._singletons] entries =",
"self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertTrue(4 in file_seq[self._test_ext]) self.assertEqual(len(file_seq[self._test_ext]), 1) #",
"lrange from . import (DirEntry, generate_entries, initialise_mock_scandir_data, mock_scandir_deep) from ..",
"name=self._test_file_name, root=self._test_root) # Expected output frame sequences. Note how frames",
"\"0001x2\", \"x2\", \"0001,0003x2\", \"0001-0005x\", \"0010-0001\", \"x\", \",\", \",,\", \"\" ]",
". import (DirEntry, generate_entries, initialise_mock_scandir_data, mock_scandir_deep) from .. import (__version__,",
"= os.path.join(self._test_root, \".\".join(bits)) final_output.append(output_seqs[pad]) data = parser.sequences # Check the",
"] bad_frame_seqs = [ \"-0001\", \"0001-\", \"0001x2\", \"x2\", \"0001,0003x2\", \"0001-0005x\",",
"-\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\\n MIN LEVELS\\n ----------\") for min_levels",
"self.assertEqual(list(map(str, output)), expected) def test_api_calls(self): \"\"\"Seqparse: Test API calls at",
"root of module.\"\"\" chunk = FrameChunk(first=1, last=7, step=2, pad=4) seq",
"x) for x in self._singletons] entries = list() for file_name",
"file sequence discovery.\"\"\" frames = {4: [1]} # Expected outputs",
"4: [0, 1, 2, 3, 4, 5, 6, 8, 10,",
"def test_nested_sequences(self, mock_api_call): \"\"\"Seqparse: Test file sequence discovery in nested",
"print(\"\\n\\n SEQUENCE\\n --------\") print(\" input files: \", fseq) print(\" expected",
"frames = {4: [0, 1, 2, 3, 4]} # Expected",
"mock from builtins import range from future.utils import lrange from",
"{:d}: {:d} ({:d} expected) entries\" print(blurb.format(max_levels, len(seqs), expected_seqs)) for seq",
"{ 1: \"5-8\", 3: \"008-010,012,114,199\", 4: \"0000-0006,0008-0012x2,0101,2000\" } # Expected",
"4]} # Expected outputs ... frame_seq_output = \"0000-0004\" file_seq_output =",
"def test_simple_sequence(self, mock_api_call): \"\"\"Seqparse: Test simple file sequence discovery.\"\"\" frames",
"------------\") for line in output: print(\" o\", line) print(\"\\n EXPECTED",
"= [DirEntry(x) for x in fseq] mock_api_call.return_value = input_entries chunk_out",
"LEVELS\\n ----------\") for min_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser =",
"complex file sequence discovery.\"\"\" frames = { 1: [5, 6,",
"= \".\".join((self._test_file_name, \"0005\", self._test_ext)) input_file = os.path.join(self._test_root, input_file) # Expected",
"\"0001,0003-0007,0009-0015x2\", \"3,1,5,7\", \"01-05,03-07\" ] bad_frame_seqs = [ \"-0001\", \"0001-\", \"0001x2\",",
"padded file sequence discovery.\"\"\" frames = {4: [1]} # Expected",
"Test file sequence discovery in nested directories.\"\"\" mock_api_call.side_effect = mock_scandir_deep",
"self.assertEqual(len(output), 3) self.assertEqual(list(map(str, output)), expected) def test_api_calls(self): \"\"\"Seqparse: Test API",
"file_seq = file_seq[self._test_ext][4] self.assertEqual(len(file_seq), len(frames[4])) self.assertEqual(str(file_seq), final_output) @mock.patch(\"seqparse.seqparse.scandir\") def test_simple_sequence(self,",
"sure scan_options works as expected.\"\"\" frames = {4: (1, 2,",
"_test_file_name = \"TEST_DIR\" _test_root = \"test_dir\" _singletons = [\"singleton0.jpg\", \"singleton1.jpg\"]",
"\", seq) print(\"\\n MAX LEVELS\\n ----------\") for max_levels in range(-1,",
"seq) self.assertEqual(len(seqs), expected_seqs) print(\"\") def test_valid_frame_sequences(self): \"\"\"Seqparse: Test validity of",
"FILES\\n -----------\") print(\" o\", input_file_seq) print(\" o\", input_file) parser =",
"\"Future\" Libraries from __future__ import print_function # Standard Libraries import",
"Test usage of the \"missing\" option in Seqparse.output.\"\"\" file_path =",
"# Third Party Libraries import mock from builtins import range",
"o\", output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) @mock.patch(\"seqparse.seqparse.scandir\") def test_inversion(self,",
"self.assertEqual(list(map(str, output)), expected) self.assertEqual(output[0].ctime, 1490908340) self.assertEqual(output[0].mtime, 1490908305) self.assertEqual(output[0].size, 36520) parser",
"# class: TestSeqparseModule class TestSeqparseModule(unittest.TestCase): \"\"\"Test file discovery on the",
"\"01-05,03-07\" ] bad_frame_seqs = [ \"-0001\", \"0001-\", \"0001x2\", \"x2\", \"0001,0003x2\",",
"print(\" o\", input_file_seq) print(\" o\", input_file) parser = get_parser() parser.add_file(input_file_seq)",
"3: [8, 9, 10, 12], 4: [0, 1, 2, 3,",
"= os.path.join(self._test_root, input_file_seq) print(\"\\n INPUT FILES\\n -----------\") print(\" o\", input_file_seq)",
"os.path.join(self._test_root, \"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 3) self.assertEqual(list(map(str, output)), expected)",
"final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertEqual(set(file_seq[self._test_ext]), set(output_seqs)) # And finally,",
"# \"Future\" Libraries from __future__ import print_function # Standard Libraries",
"INPUT FILES\\n -----------\") print(\" o\", input_file_seq) print(\" o\", input_file) parser",
"= {4: (1, 2, 3, 4, 6)} input_entries = generate_entries(",
"mock_api_call.return_value = input_entries parser = get_parser() parser.scan_options[\"stat\"] = True parser.scan_path(self._test_root)",
"expected_seqs) print(\"\") def test_valid_frame_sequences(self): \"\"\"Seqparse: Test validity of simple frame",
"= FrameChunk(first=1, last=11, step=2, pad=4) fseq = FileSequence( name=file_path, ext=self._test_ext,",
"parser.scan_path(self._test_root) data = parser.sequences test_output = list(parser.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]),",
"= get_parser() parser.scan_path(self._test_root) data = parser.sequences test_output = list(parser.output()) self.assertEqual(len(test_output),",
"1) self.assertEqual( len(file_names[self._test_root]), len(self._singletons)) self.assertEqual( sorted(self._singletons), sorted(file_names[self._test_root])) # Check parser",
"input_file_seq = \".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq)",
"\"0000-0002,,0003-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root,",
"for x in self._singletons] entries = list() for file_name in",
"= \"TEST_DIR\" _test_root = \"test_dir\" _singletons = [\"singleton0.jpg\", \"singleton1.jpg\"] def",
"\"0001,0003\", \"0001,,0003\", \"0001-0010\", \"0001-0010x0\", \"0001-0011x2\", \"0001-0012x2\", \"0001-0005,0007-0010\", \"0001-0005x2,0007-0010\", \"0001-0005,0007-0011x2\", \"0001-0005,0006,0008-0012x2\",",
"self._test_ext)) input_file_seq = os.path.join(self._test_root, input_file_seq) print(\"\\n INPUT FILES\\n -----------\") print(\"",
"disk location.\"\"\" # Expected outputs ... output = [os.path.join(self._test_root, x)",
"@mock.patch(\"seqparse.seqparse.scandir\") def test_simple_sequence(self, mock_api_call): \"\"\"Seqparse: Test simple file sequence discovery.\"\"\"",
"sequences. Note how frames 114, 199 move to the #",
"TestSeqparseModule(unittest.TestCase): \"\"\"Test file discovery on the seqparse module.\"\"\" _test_ext =",
"file_path = os.path.join(self._test_root, self._test_file_name) chunk_in = FrameChunk(first=1, last=11, step=2, pad=4)",
"file_name in output: entries.append(DirEntry(file_name)) mock_api_call.return_value = iter(entries) parser = get_parser()",
"file_names[self._test_root].path) self.assertEqual(len(file_names), 1) self.assertEqual( len(file_names[self._test_root]), len(self._singletons)) self.assertEqual( sorted(self._singletons), sorted(file_names[self._test_root])) #",
"# \"pad 3\" group and 2000 moves to the \"pad",
"min_levels in range(-1, 4): initialise_mock_scandir_data(self._test_root) parser = get_parser() parser.scan_path(self._test_root, min_levels=min_levels)",
"test_single_padded_file(self, mock_api_call): \"\"\"Seqparse: Test single padded file sequence discovery.\"\"\" frames",
"\" o min_levels == {:d}: {:d} ({:d} expected) entries\" print(blurb.format(min_levels,",
"output ... self.assertEqual(sorted(map(str, parser.output())), output) # Test seqs_only option ...",
"self.assertEqual(len(file_seq[self._test_ext]), 1) # And finally, the file sequence. file_seq =",
"1) self.assertEqual(str(output[0]), output_file_seq) @mock.patch(\"seqparse.seqparse.scandir\") def test_inversion(self, mock_api_call): \"\"\"Seqparse: Test usage",
"= get_parser() parser.scan_path(self._test_root) inverted = list(parser.output(missing=True)) self.assertEqual(len(inverted), 1) print(\"\\n\\n SEQUENCE\\n",
"get_parser() parser.scan_path(self._test_root) inverted = list(parser.output(missing=True)) self.assertEqual(len(inverted), 1) print(\"\\n\\n SEQUENCE\\n --------\")",
"6, 8, 10, 12, 101] } input_entries = generate_entries( ext=self._test_ext,",
"chunk_in = FrameChunk(first=1, last=11, step=2, pad=4) fseq = FileSequence( name=file_path,",
"final output (where \"/\" is os.sep): # test_dir/TEST_DIR.5-8.exr # test_dir/TEST_DIR.008-010,012,114,199.exr",
"pass @mock.patch(\"seqparse.seqparse.scandir\") def test_singletons(self, mock_api_call): \"\"\"Seqparse: Test file singleton discovery",
"root=self._test_root)) input_entries.append( DirEntry(os.path.join(self._test_root, \"pony.py\"))) mock_api_call.return_value = input_entries parser = get_parser()",
"print(\" o\", output_file_seq) print(\"\") self.assertEqual(len(output), 1) self.assertEqual(str(output[0]), output_file_seq) input_frame_seq =",
"print(\"\\n EXPECTED OUTPUT\\n ---------------\") print(\" o\", output_file_seq) print(\"\") self.assertEqual(len(output), 1)",
"= \"exr\" _test_file_name = \"TEST_DIR\" _test_root = \"test_dir\" _singletons =",
"test_output = list(file_seq.output()) self.assertEqual(len(test_output), 3) self.assertEqual(list(map(str, test_output)), final_output) self.assertIn(self._test_ext, file_seq)",
"@mock.patch(\"seqparse.seqparse.scandir\") def test_nested_sequences(self, mock_api_call): \"\"\"Seqparse: Test file sequence discovery in",
"print(\" o\", line) print(\"\\n EXPECTED OUTPUT\\n ---------------\") print(\" o\", output_file_seq)",
"= FileSequence( name=file_path, ext=self._test_ext, frames=[1, 2, 3, 4, 6], pad=4)",
"in seqs: print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\") def test_valid_frame_sequences(self):",
"outputs ... output = [os.path.join(self._test_root, x) for x in self._singletons]",
"input_entries chunk_out = FrameChunk(first=2, last=10, step=2, pad=4) expected = FileSequence(",
"= list(parser.output()) print(\"\\n OUTPUT FILES\\n ------------\") for line in output:",
"True parser.scan_path(self._test_root) output = list(parser.output()) expected = [ os.path.join(self._test_root, \"test.0001-0004,0006.py\"),",
"{!r} --> {!r}'.format(frame_seq, output)) self.assertTrue(output) print(\"\\n BAD SEQUENCES\\n -------------\") for",
"get_parser() parser.scan_path(self._test_root) final_output = list() for pad, seq_frames in sorted(output_seqs.items()):",
"os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 3) self.assertEqual(list(map(str, output)), expected) def test_api_calls(self):",
"FrameChunk(first=1, last=7, step=2, pad=4) seq = get_sequence(lrange(1, 8, 2), pad=4)",
"... self.assertEqual(sorted(parser.output(seqs_only=True)), []) @mock.patch(\"seqparse.seqparse.scandir\") def test_single_padded_file(self, mock_api_call): \"\"\"Seqparse: Test single",
"mock_api_call.return_value = input_entries expected = FileSequence( name=file_path, ext=self._test_ext, frames=[5], pad=4)",
"= { 1: \"5-8\", 3: \"008-010,012,114,199\", 4: \"0000-0006,0008-0012x2,0101,2000\" } #",
"self.assertEqual(len(seqs), expected_seqs) print(\"\") def test_valid_frame_sequences(self): \"\"\"Seqparse: Test validity of simple",
"ext=self._test_ext, frames=chunk_in) input_entries = [DirEntry(x) for x in fseq] mock_api_call.return_value",
"o\", input_file) parser = get_parser() parser.add_file(input_file_seq) parser.add_file(input_file) output = list(parser.output())",
"1) # Now check the file sequence itself. file_seq =",
"o\", input_file_seq) print(\" o\", input_file) parser = get_parser() parser.add_file(input_file_seq) parser.add_file(input_file)",
"to the # \"pad 3\" group and 2000 moves to",
"in fseq] mock_api_call.return_value = input_entries chunk_out = FrameChunk(first=2, last=10, step=2,",
"= get_parser() parser.scan_path(self._test_root) file_names = parser.singletons self.assertIn(self._test_root, file_names) self.assertEqual(self._test_root, file_names[self._test_root].path)",
"mock_api_call): \"\"\"Seqparse: Test file singleton discovery from disk location.\"\"\" #",
"seqs: print(\" -\", seq) self.assertEqual(len(seqs), expected_seqs) print(\"\\n MIN LEVELS\\n ----------\")",
"generate_entries( name=\".test\", ext=\"py\", frames=frames, root=self._test_root)) input_entries.append( DirEntry(os.path.join(self._test_root, \"pony.py\"))) mock_api_call.return_value =",
"self.assertEqual(len(test_output), 3) self.assertEqual(list(map(str, test_output)), final_output) self.assertIn(self._test_ext, file_seq) self.assertEqual(len(file_seq), 1) self.assertEqual(set(file_seq[self._test_ext]),",
"mock_api_call.return_value = iter(entries) parser = get_parser() parser.scan_path(self._test_root) file_names = parser.singletons",
"= {4: [0, 1, 2, 3, 4]} # Expected outputs",
"\"test.0001-0004,0006.py\"), os.path.join(self._test_root, \"pony.py\") ] self.assertEqual(len(output), 2) self.assertEqual(list(map(str, output)), expected) self.assertEqual(output[0].ctime,",
"\"\"\"Seqparse: Test validity of simple frame ranges.\"\"\" good_frame_seqs = [",
"data = parser.sequences # Check the structure of the sequences",
"parser = get_parser() parser.scan_options[\"all\"] = True parser.scan_path(self._test_root) output = list(parser.output())",
"discovery.\"\"\" frames = {4: [0, 1, 2, 3, 4]} #",
"# Expected outputs ... frame_seq_output = \"0000-0004\" file_seq_output = \".\".join(",
"\"0000-0005\" input_file_seq = \".\".join( (self._test_file_name, input_frame_seq, self._test_ext)) input_file_seq = os.path.join(self._test_root,",
"BAD SEQUENCES\\n -------------\") for frame_seq in bad_frame_seqs: print(' o {!r}'.format(frame_seq))",
"expected) print(\" inverted files:\", inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) @mock.patch(\"seqparse.seqparse.scandir\") def test_scan_options(self,",
"parser.scan_path(self._test_root, max_levels=max_levels) expected_seqs = max_levels + 2 if max_levels ==",
"parser.scan_path(self._test_root, min_levels=min_levels) expected_seqs = 3 - min_levels if min_levels ==",
"FileSequence( name=file_path, ext=self._test_ext, frames=[5], pad=4) parser = get_parser() parser.scan_path(self._test_root) inverted",
"= { 1: [5, 6, 7, 8, 114, 199, 2000],",
"parser = get_parser() parser.scan_path(self._test_root) inverted = list(parser.output(missing=True)) self.assertEqual(len(inverted), 1) print(\"\\n\\n",
"disk.\"\"\" # \"Future\" Libraries from __future__ import print_function # Standard",
"pad=4) expected = FileSequence( name=file_path, ext=self._test_ext, frames=chunk_out) parser = get_parser()",
"-1: expected_seqs = 5 seqs = list(parser.output()) blurb = \"",
"4: \"0000-0006,0008-0012x2,0101,2000\" } # Expected final output (where \"/\" is",
"inverted[0]) self.assertEqual(str(inverted[0]), str(expected)) @mock.patch(\"seqparse.seqparse.scandir\") def test_scan_options(self, mock_api_call): \"\"\"Seqparse: Make sure",
"data = parser.sequences test_output = list(parser.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output)",
"len(file_names[self._test_root]), len(self._singletons)) self.assertEqual( sorted(self._singletons), sorted(file_names[self._test_root])) # Check parser output ...",
"the # \"pad 3\" group and 2000 moves to the",
"= parser.sequences test_output = list(parser.output()) self.assertEqual(len(test_output), 1) self.assertEqual(str(test_output[0]), final_output) #",
"str(file_seq[self._test_ext][pad])) @mock.patch(\"seqparse.seqparse.scandir\") def test_nested_sequences(self, mock_api_call): \"\"\"Seqparse: Test file sequence discovery",
"in file_seq[self._test_ext]) self.assertEqual(len(file_seq[self._test_ext]), 1) # And finally, the file sequence.",
"print(\"\\n\\n GOOD SEQUENCES\\n --------------\") for frame_seq in good_frame_seqs: output =",
"fseq = FileSequence( name=file_path, ext=self._test_ext, frames=[1, 2, 3, 4, 6],"
] |
[
"finding the index of what as inserted # Again this",
"the CSS class menu-index-page__item_content items_html = category.find_all(\"div\", class_=\"menu-index-page__item-content\") for menu_item",
"seen before if deliveroo_name not in restaurants['deliveroo_name']: # Get the",
"URL - it doesn't matter that it says camden, it",
"<div> tags with the CSS class # menu-index-page__menu-category categories =",
"will update as appropriate. url = \"https://deliveroo.co.uk/restaurants/london/camden\" \\ f\"?postcode={postcode}&sort=time\" #",
"\"loc_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"loc_id\": \"int64\"}) for post_code in postcodes['post_code']:",
"menu_sections, menu_items, restaurants_to_locs, postcodes) # Write to db cnx =",
"if __name__ == \"__main__\": postcodes_df = pd.DataFrame({ 'post_code': postcodes_list })",
"{\"restaurant_id\": restaurant_index, \"loc_id\": postcodes_index}, ignore_index=True) # Return the amended dataframes",
"not in London deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # This",
"efficient, if you were wanting to scrape large numbers #",
"adds this to the restaurants dataframe # This isn't very",
"exists in the tags_df dataframe matches = tags_df[ (tags_df ==",
"is then # converted to a floating-point number (decimal), multiplied",
"dataframe # This isn't very efficient, if you were wanting",
"postcodes): # This functions gets the restaurant and then processes",
"== [name, type_matches.index[0]]).all(axis=1)] # If it doesn't if len(matches) ==",
"very efficient) tag_type = tag_type.append({\"name\": tagtype}, ignore_index=True) # Update the",
"pd.DataFrame({\"name\": []}) restaurants = pd.DataFrame({\"name\": [], \"deliveroo_name\": []})\\ .astype({\"name\": \"str\",",
"in postcodes['post_code']: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) =\\",
"the CSS class tag for tag in doc.find_all(\"small\", class_=\"tag\"): #",
"# For each tag for tag in restaurant_tags: # Add",
"menu_sections, menu_items, restaurants_to_locs) =\\ process_restaurants_for_postcode(post_code, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) # Write to",
"each menu item. Found by looking for <div> inside the",
"Sides, Mains, Desserts, Drinks - # different for every restaurant",
"restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_all_restaurants(postcodes, db_name): # This function",
"postcodes) # Return the amended dataframes return (tags_df, tag_type, restaurants,",
"menu_sections.append( {\"restaurant_id\": restaurant_id, \"name\": category_name}, ignore_index=True) # Get the id",
"Add all the menu items in that category to the",
"number (decimal), multiplied by 100 # so that it is",
"than doing this one at a time menu_items = menu_items.append(category_items,",
"# For each menu item. Found by looking for <div>",
"process_menu(doc, url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items): # This",
"pd.DataFrame({\"name\": [], \"type\": []})\\ .astype({\"name\": \"str\", \"type\": \"int32\"}) tag_type =",
"restaurant_tags = [] # Deal with tags # Start by",
"restaurant_name, \"deliveroo_name\": deliveroo_name}, ignore_index=True) # This gets the restaurant_id by",
"0: # Add it (again not very efficient) tag_type =",
"menu_items, restaurants_to_locs, postcodes): # This functions gets the restaurant and",
"restaurants_to_locs = restaurants_to_locs.append( {\"restaurant_id\": restaurant_index, \"loc_id\": postcodes_index}, ignore_index=True) # Return",
"inside the <small> name = tag.text # See if the",
"tag_type = pd.DataFrame({\"name\": []}) restaurants = pd.DataFrame({\"name\": [], \"deliveroo_name\": []})\\",
"is dropped, it is then # converted to a floating-point",
"the category to the menu_sections data frame. Again this isn't",
"= urllib.request.urlopen(request) soup = BeautifulSoup(page) # Try and process the",
"ignore_index=True) # Update the matches type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)]",
"CSS class # restaurant_name restaurant_name = doc.find(\"h1\", class_=\"restaurant__name\", text=True).text #",
"postcodes): # This function processes the restaurants for the postcodes",
"import sqlite3 import re from bs4 import BeautifulSoup # Parameters",
"- it doesn't matter that it says camden, it #",
"pd import sqlite3 import re from bs4 import BeautifulSoup #",
"restaurants_to_tags, menu_sections, menu_items): # This function processes the menu #",
"# Add it (again not very efficient) tag_type = tag_type.append({\"name\":",
"of the link destination = link.get(\"href\") # If it's to",
"this restaurant is # available at this location restaurants_to_locs =",
"is then converted to an integer. # # https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency price_as_text",
"'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} def process_menu(doc, url, tags_df, tag_type, restaurants,",
"# this is more efficient than doing this one at",
"== 0: # Add it (again not very efficient) tag_type",
"headers=hdr) # Get the page page = urllib.request.urlopen(request) soup =",
"is more efficient than doing this one at a time",
"(in the menu, e.g. Sides, Mains, Desserts, Drinks - #",
"{\"menu_section_id\": \"int64\", \"name\": \"str\", \"price_in_pence\": \"int64\", \"is_popular\": \"bool\"}) restaurants_to_locs =",
"of tags for that restaurant restaurant_tags.append(matches.index[0]) # For each tag",
"isn't very efficient, if you were wanting to scrape large",
"# This is found by looking for <div> tags with",
"CSS class # menu-index-page__menu-category categories = doc.find_all(\"div\", class_=\"menu-index-page__menu-category\") for category",
"index of what as inserted # Again this isn't very",
"# with the CSS class menu-index-page__item_content items_html = category.find_all(\"div\", class_=\"menu-index-page__item-content\")",
"for the postcodes # Add the postcode to the URL",
"be locale or food etc. tagtype = tag['class'][1] # The",
"CSS class # menu-index-page__item-price. The £ symbol is dropped, it",
"\"name\": []})\\ .astype({\"restaurant_id\": \"int64\", \"name\": \"str\"}) menu_items = pd.DataFrame( {\"menu_section_id\":",
"has a <span> with the CSS class # menu-index-page__item-popular #",
"BeautifulSoup # Parameters postcodes_list = [\"W1F7EY\"] db_name = \"scraped.db\" #",
".astype({\"name\": \"str\", \"deliveroo_name\": \"str\"}) restaurants_to_tags = pd.DataFrame({\"restaurant_id\": [], \"tag_id\": []})\\",
"<h6> with the CSS class # menu-index-page__item-title item_name = \\",
"menu_items) def get_restaurant_and_process_menu(url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs,",
"restaurants_to_locs, postcodes) # Return the amended dataframes return (tags_df, tag_type,",
"# menu-index-page__menu-category categories = doc.find_all(\"div\", class_=\"menu-index-page__menu-category\") for category in categories:",
"== 0: # Add it entry = {\"name\": name, \"type\":",
"# restaurant_name restaurant_name = doc.find(\"h1\", class_=\"restaurant__name\", text=True).text # This gets",
"tag already exists in the tags_df dataframe matches = tags_df[",
"already exists in the tags_df dataframe matches = tags_df[ (tags_df",
"menu-index-page__item_content items_html = category.find_all(\"div\", class_=\"menu-index-page__item-content\") for menu_item in items_html: #",
"# The name is the <h6> with the CSS class",
"floating-point number (decimal), multiplied by 100 # so that it",
"process the menu items # This is found by looking",
"item. Found by looking for <div> inside the category #",
"amended dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs)",
"For each tag for tag in restaurant_tags: # Add this",
"<small> name = tag.text # See if the tagtype exists",
"postcodes_list = [\"W1F7EY\"] db_name = \"scraped.db\" # This is so",
"Start by finding all <small> tags with the CSS class",
"name is inside the h3 inside the div category_name =",
"type_matches.index[0]]).all(axis=1)] # If it doesn't if len(matches) == 0: #",
"(restaurants == [restaurant_name, deliveroo_name]).all( axis=1)].index[0] restaurant_tags = [] # Deal",
"\"type\": type_matches.index[0]} tags_df = tags_df.append(entry, ignore_index=True) matches = tags_df[(tags_df ==",
"for every restaurant though!) process the menu items # This",
"category.h3.text # Add the category to the menu_sections data frame.",
"frame. Again this isn't # efficient. menu_sections = menu_sections.append( {\"restaurant_id\":",
"Get the destination of the link destination = link.get(\"href\") #",
"the h3 inside the div category_name = category.h3.text # Add",
"menu_sections.to_sql(\"MENU_SECTIONS\", cnx, index_label=\"id\") tags_df.to_sql(\"CATEGORIES\", cnx, index_label=\"id\") tag_type.to_sql(\"CATEGORY_TYPES\", cnx, index_label=\"id\") restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\",",
"tag in doc.find_all(\"small\", class_=\"tag\"): # The second element of the",
"\\ f\"?postcode={postcode}&sort=time\" # Create the HTTP request request = urllib.request.Request(url,",
"cnx = sqlite3.connect(db_name) postcodes.to_sql(\"POSTCODES\", cnx, index_label=\"id\") restaurants.to_sql(\"RESTAURANTS\", cnx, index_label=\"id\") restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\",",
"{url}\") # Get the postcode from the URL postcode =",
"# Add the tag to a list of tags for",
"from bs4 import BeautifulSoup # Parameters postcodes_list = [\"W1F7EY\"] db_name",
"+ ';q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'}",
"\\ (restaurants['deliveroo_name'] == deliveroo_name).index[0] # Add an entry to restaurants_to_locs",
"Linux x86_64) AppleWebKit/537.11' + '(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept':",
"matches type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] # See if the",
"inside the h3 inside the div category_name = category.h3.text #",
"= tags_df.append(entry, ignore_index=True) matches = tags_df[(tags_df == [name, type_matches.index[0]]).all( axis=1)]",
"# See if the tagtype exists in the tag_type dataframe",
"opposed to a web scraper hdr = {'User-Agent': 'Mozilla/5.0 (X11;",
"selecting the appropriate part from the # URL # This",
"# Add the category to the menu_sections data frame. Again",
"this restaurant hasn't been seen before if deliveroo_name not in",
"the link destination = link.get(\"href\") # If it's to a",
"{\"name\": name, \"type\": type_matches.index[0]} tags_df = tags_df.append(entry, ignore_index=True) matches =",
"# Create the dataframes tags_df = pd.DataFrame({\"name\": [], \"type\": []})\\",
"entry to restaurants_to_locs saying that this restaurant is # available",
"to an integer. # # https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency price_as_text = \\ menu_item.find(\"span\",",
"\"int32\"}) tag_type = pd.DataFrame({\"name\": []}) restaurants = pd.DataFrame({\"name\": [], \"deliveroo_name\":",
"the amended dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items,",
"class is the type of the tag # this could",
"# hasn't been processed before # Get the deliveroo name",
"the deliveroo_name by selecting the appropriate part from the #",
"# If an item is popular it has a <span>",
"dataframe matches = tags_df[ (tags_df == [name, type_matches.index[0]]).all(axis=1)] # If",
"menu_sections[ (menu_sections == [restaurant_id, category_name]).all( axis=1)].index[0] # Get each of",
"the CSS class # menu-index-page__item-popular # So this tries to",
"the menu, e.g. Sides, Mains, Desserts, Drinks - # different",
"find it, if it exists is_item_popular = True, # False",
"url)[0] # If this restaurant hasn't been seen before if",
"the restaurants dataframe using the deliveroo # name restaurant_index =",
"postcodes # Add the postcode to the URL - it",
"restaurants = restaurants.append( {\"name\": restaurant_name, \"deliveroo_name\": deliveroo_name}, ignore_index=True) # This",
"though!) process the menu items # This is found by",
"price_as_text = \\ menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\ .text[1:] price_as_float = float(price_as_text) item_price",
"menu_sections = pd.DataFrame({\"restaurant_id\": [], \"name\": []})\\ .astype({\"restaurant_id\": \"int64\", \"name\": \"str\"})",
"type_matches.index[0]]).all( axis=1)] # Add the tag to a list of",
"restaurant_index = \\ (restaurants['deliveroo_name'] == deliveroo_name).index[0] # Add an entry",
"the restaurant_name by finding the <h1> tag with the CSS",
"dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) def get_restaurant_and_process_menu(url,",
"an entry to restaurants_to_locs saying that this restaurant is #",
"finding all <small> tags with the CSS class tag for",
"exists in the tag_type dataframe type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)]",
"This function processes the menu # This gets the restaurant_name",
"class_=\"tag\"): # The second element of the <small> CSS class",
"dataframe type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] # If it doesn't",
"fail on restaurants not in London deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)',",
"sqlite3 import re from bs4 import BeautifulSoup # Parameters postcodes_list",
"is the <h6> with the CSS class # menu-index-page__item-title item_name",
"\\ menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text # The price is the <span> with",
"inside the div category_name = category.h3.text # Add the category",
"(tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_restaurants_for_postcode(postcode, tags_df,",
"<filename>deliveroo_scraping.py import urllib.request import pandas as pd import sqlite3 import",
"by finding all <small> tags with the CSS class tag",
"\"int64\", \"tag_id\": \"int64\"}) menu_sections = pd.DataFrame({\"restaurant_id\": [], \"name\": []})\\ .astype({\"restaurant_id\":",
"it is in pence. It is then converted to an",
"restaurants_to_locs) def process_all_restaurants(postcodes, db_name): # This function processes all of",
"pandas as pd import sqlite3 import re from bs4 import",
"tags_df = tags_df.append(entry, ignore_index=True) matches = tags_df[(tags_df == [name, type_matches.index[0]]).all(",
"by looking for <div> tags with the CSS class #",
"Drinks - # different for every restaurant though!) process the",
"efficient) tag_type = tag_type.append({\"name\": tagtype}, ignore_index=True) # Update the matches",
"= pd.DataFrame({\"restaurant_id\": [], \"tag_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"tag_id\": \"int64\"}) menu_sections",
"in enumerate(soup.find_all(\"a\")): print(i) # Get the destination of the link",
"tag with the CSS class # restaurant_name restaurant_name = doc.find(\"h1\",",
"[]})\\ .astype({\"restaurant_id\": \"int64\", \"loc_id\": \"int64\"}) for post_code in postcodes['post_code']: (tags_df,",
"len(matches) == 0: # Add it entry = {\"name\": name,",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) except Exception: print(f\"Fail on {url}\")",
"h3 inside the div category_name = category.h3.text # Add the",
"Write to db cnx = sqlite3.connect(db_name) postcodes.to_sql(\"POSTCODES\", cnx, index_label=\"id\") restaurants.to_sql(\"RESTAURANTS\",",
"restaurant_id, \"tag_id\": tag}, ignore_index=True) # For each category (in the",
"Return the updated dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"\"is_popular\": is_item_popular} ) # Add all the menu items in",
"cnx, index_label=\"id\") tags_df.to_sql(\"CATEGORIES\", cnx, index_label=\"id\") tag_type.to_sql(\"CATEGORY_TYPES\", cnx, index_label=\"id\") restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx,",
"# Get the destination of the link destination = link.get(\"href\")",
"deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # If this restaurant hasn't",
"# The second element of the <small> CSS class is",
"category_items category_items.append( {\"menu_section_id\": category_id, \"name\": item_name, \"price_in_pence\": item_price, \"is_popular\": is_item_popular}",
"= tag_type[(tag_type == [tagtype]).all(axis=1)] # If it doesn't if len(type_matches)",
"as pd import sqlite3 import re from bs4 import BeautifulSoup",
"Again this isn't very efficient restaurant_id = restaurants[ (restaurants ==",
"restaurants_to_locs) =\\ process_restaurants_for_postcode(post_code, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs,",
"efficient than doing this one at a time menu_items =",
"the menu_items data frame, # this is more efficient than",
"menu-index-page__item-title item_name = \\ menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text # The price is",
"post_code in postcodes['post_code']: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs)",
"\"int64\", \"name\": \"str\", \"price_in_pence\": \"int64\", \"is_popular\": \"bool\"}) restaurants_to_locs = pd.DataFrame({\"restaurant_id\":",
"Chrome # as opposed to a web scraper hdr =",
"restaurant_name by finding the <h1> tag with the CSS class",
"URL # This will fail on restaurants not in London",
"to a list of tags for that restaurant restaurant_tags.append(matches.index[0]) #",
"url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) except Exception: print(f\"Fail",
"\"https://deliveroo.co.uk/restaurants/london/camden\" \\ f\"?postcode={postcode}&sort=time\" # Create the HTTP request request =",
"# Get each of the items in that category category_items",
"# This functions gets the restaurant and then processes its",
"[], \"price_in_pence\": [], \"is_popular\": []}).astype( {\"menu_section_id\": \"int64\", \"name\": \"str\", \"price_in_pence\":",
"\"tag_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"tag_id\": \"int64\"}) menu_sections = pd.DataFrame({\"restaurant_id\": [],",
"what is inside the <small> name = tag.text # See",
"This functions gets the restaurant and then processes its menu",
"tries to find it, if it exists is_item_popular = True,",
"doc.find_all(\"small\", class_=\"tag\"): # The second element of the <small> CSS",
"menu_items) except Exception: print(f\"Fail on {url}\") # Get the postcode",
"for tag in restaurant_tags: # Add this to restaurants_to_tags df",
"of the <small> CSS class is the type of the",
"def process_restaurants_for_postcode(postcode, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes):",
"a <span> with the CSS class # menu-index-page__item-popular # So",
"\"is_popular\": []}).astype( {\"menu_section_id\": \"int64\", \"name\": \"str\", \"price_in_pence\": \"int64\", \"is_popular\": \"bool\"})",
"finding the <h1> tag with the CSS class # restaurant_name",
"cnx, index_label=\"id\") menu_sections.to_sql(\"MENU_SECTIONS\", cnx, index_label=\"id\") tags_df.to_sql(\"CATEGORIES\", cnx, index_label=\"id\") tag_type.to_sql(\"CATEGORY_TYPES\", cnx,",
"for category in categories: # the category name is inside",
"gets the restaurant_name by finding the <h1> tag with the",
"name, \"type\": type_matches.index[0]} tags_df = tags_df.append(entry, ignore_index=True) matches = tags_df[(tags_df",
"BeautifulSoup(page) # Try and process the menu, if it doesn't",
"the dataframes tags_df = pd.DataFrame({\"name\": [], \"type\": []})\\ .astype({\"name\": \"str\",",
"100 # so that it is in pence. It is",
"work handle it nicely try: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"<small> CSS class is the type of the tag #",
"\"name\": \"str\"}) menu_items = pd.DataFrame( {\"menu_section_id\": [], \"name\": [], \"price_in_pence\":",
"the CSS class # restaurant_name restaurant_name = doc.find(\"h1\", class_=\"restaurant__name\", text=True).text",
"# This adds this to the restaurants dataframe # This",
"[tagtype]).all(axis=1)] # See if the tag already exists in the",
"ignore_index=True) # Get the id in the menu_sections data frame",
"Create the HTTP request request = urllib.request.Request(url, headers=hdr) # Get",
"menu_item.find( \"span\", class_=\"menu-index-page__item-popular\") is not None # Add this menu_item",
"(again not very efficient) tag_type = tag_type.append({\"name\": tagtype}, ignore_index=True) #",
"__name__ == \"__main__\": postcodes_df = pd.DataFrame({ 'post_code': postcodes_list }) process_all_restaurants(postcodes_df,",
"= sqlite3.connect(db_name) postcodes.to_sql(\"POSTCODES\", cnx, index_label=\"id\") restaurants.to_sql(\"RESTAURANTS\", cnx, index_label=\"id\") restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx,",
"deliveroo_name by selecting the appropriate part from the # URL",
"class menu-index-page__item_content items_html = category.find_all(\"div\", class_=\"menu-index-page__item-content\") for menu_item in items_html:",
"restaurant_name = doc.find(\"h1\", class_=\"restaurant__name\", text=True).text # This gets the deliveroo_name",
"to restaurants_to_tags df restaurants_to_tags = restaurants_to_tags.append( {\"restaurant_id\": restaurant_id, \"tag_id\": tag},",
"restaurant_name restaurant_name = doc.find(\"h1\", class_=\"restaurant__name\", text=True).text # This gets the",
".astype({\"restaurant_id\": \"int64\", \"name\": \"str\"}) menu_items = pd.DataFrame( {\"menu_section_id\": [], \"name\":",
"process the menu, if it doesn't work handle it nicely",
"postcodes) # Write to db cnx = sqlite3.connect(db_name) postcodes.to_sql(\"POSTCODES\", cnx,",
"deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # This adds this to",
"dataframe using the deliveroo # name restaurant_index = \\ (restaurants['deliveroo_name']",
"\"int64\"}) for post_code in postcodes['post_code']: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) =\\ process_restaurants_for_postcode(post_code, tags_df, tag_type,",
"each tag for tag in restaurant_tags: # Add this to",
"restaurants[ (restaurants == [restaurant_name, deliveroo_name]).all( axis=1)].index[0] restaurant_tags = [] #",
"soup = BeautifulSoup(page) # For every link in the page",
"# Get the webpage request = urllib.request.Request(url, headers=hdr) page =",
"[], \"name\": []})\\ .astype({\"restaurant_id\": \"int64\", \"name\": \"str\"}) menu_items = pd.DataFrame(",
"etc. tagtype = tag['class'][1] # The name of the tag",
"the appropriate part from the # URL # This will",
"Add the category to the menu_sections data frame. Again this",
"to the menu_sections data frame. Again this isn't # efficient.",
"destination of the link destination = link.get(\"href\") # If it's",
"item_name, \"price_in_pence\": item_price, \"is_popular\": is_item_popular} ) # Add all the",
"menu items in that category to the menu_items data frame,",
"# Update the matches type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] #",
"This is found by looking for <div> tags with the",
"restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes): # This functions gets",
"items in that category category_items = [] # For each",
"get_restaurant_and_process_menu( \"https://deliveroo.co.uk\" + destination, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items,",
"axis=1)].index[0] restaurant_tags = [] # Deal with tags # Start",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) def get_restaurant_and_process_menu(url, tags_df, tag_type, restaurants,",
"request = urllib.request.Request(url, headers=hdr) page = urllib.request.urlopen(request) soup = BeautifulSoup(page)",
"process_restaurants_for_postcode(post_code, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) #",
"# This gets the restaurant_name by finding the <h1> tag",
"matches = tags_df[(tags_df == [name, type_matches.index[0]]).all( axis=1)] # Add the",
"# This gets the deliveroo_name by selecting the appropriate part",
"the menu items # This is found by looking for",
"items in that category to the menu_items data frame, #",
"postcode from the URL postcode = re.findall('(?<=\\\\?postcode=)(.)*', url)[0] # Find",
"id in the restaurants dataframe using the deliveroo # name",
"axis=1)] # Add the tag to a list of tags",
"get the restaurant and process the menu if \"/menu\" in",
"tags_df[ (tags_df == [name, type_matches.index[0]]).all(axis=1)] # If it doesn't if",
"the <span> with the CSS class # menu-index-page__item-price. The £",
"urllib.request import pandas as pd import sqlite3 import re from",
"Google Chrome # as opposed to a web scraper hdr",
"menu if \"/menu\" in destination: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) # Write to db cnx",
"with the CSS class # menu-index-page__item-price. The £ symbol is",
"so that it is in pence. It is then converted",
"all the menu items in that category to the menu_items",
"\\ get_restaurant_and_process_menu( \"https://deliveroo.co.uk\" + destination, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"page = urllib.request.urlopen(request) soup = BeautifulSoup(page) # Try and process",
"pd.DataFrame( {\"menu_section_id\": [], \"name\": [], \"price_in_pence\": [], \"is_popular\": []}).astype( {\"menu_section_id\":",
"This gets the restaurant_id by finding the index of what",
"'(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' + ';q=0.8', 'Accept-Charset':",
"= category.find_all(\"div\", class_=\"menu-index-page__item-content\") for menu_item in items_html: # The name",
"converted to an integer. # # https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency price_as_text = \\",
"destination: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) = \\",
"[]})\\ .astype({\"restaurant_id\": \"int64\", \"tag_id\": \"int64\"}) menu_sections = pd.DataFrame({\"restaurant_id\": [], \"name\":",
"the updated dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items)",
"use .append restaurants = restaurants.append( {\"name\": restaurant_name, \"deliveroo_name\": deliveroo_name}, ignore_index=True)",
"restaurants_to_locs, postcodes): # This functions gets the restaurant and then",
"postcode = re.findall('(?<=\\\\?postcode=)(.)*', url)[0] # Find where it is in",
"name from the url deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] #",
"100) # If an item is popular it has a",
"restaurant and then processes its menu if it # hasn't",
"Add this to restaurants_to_tags df restaurants_to_tags = restaurants_to_tags.append( {\"restaurant_id\": restaurant_id,",
"processes all of the postcodes # Create the dataframes tags_df",
"class # menu-index-page__item-title item_name = \\ menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text # The",
"import BeautifulSoup # Parameters postcodes_list = [\"W1F7EY\"] db_name = \"scraped.db\"",
"the tag is what is inside the <small> name =",
"Desserts, Drinks - # different for every restaurant though!) process",
"isn't # efficient. menu_sections = menu_sections.append( {\"restaurant_id\": restaurant_id, \"name\": category_name},",
"link in the page for i, link in enumerate(soup.find_all(\"a\")): print(i)",
"menu items # This is found by looking for <div>",
"# the category name is inside the h3 inside the",
"doesn't matter that it says camden, it # will update",
"'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} def process_menu(doc, url, tags_df, tag_type,",
"the deliveroo name from the url deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)',",
"url deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # If this restaurant",
"menu # This gets the restaurant_name by finding the <h1>",
"from the URL postcode = re.findall('(?<=\\\\?postcode=)(.)*', url)[0] # Find where",
"the HTTP request request = urllib.request.Request(url, headers=hdr) # Get the",
"restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) = \\ get_restaurant_and_process_menu( \"https://deliveroo.co.uk\" + destination,",
"tag_type.append({\"name\": tagtype}, ignore_index=True) # Update the matches type_matches = tag_type[(tag_type",
"menu if it # hasn't been processed before # Get",
"Deal with tags # Start by finding all <small> tags",
"data frame, # this is more efficient than doing this",
"= pd.DataFrame({\"name\": []}) restaurants = pd.DataFrame({\"name\": [], \"deliveroo_name\": []})\\ .astype({\"name\":",
"{'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11' + '(KHTML, like Gecko)",
"[tagtype]).all(axis=1)] # If it doesn't if len(type_matches) == 0: #",
"it # will update as appropriate. url = \"https://deliveroo.co.uk/restaurants/london/camden\" \\",
"the <small> CSS class is the type of the tag",
"# different for every restaurant though!) process the menu items",
"process_all_restaurants(postcodes, db_name): # This function processes all of the postcodes",
"it is in the postcodes data frame postcodes_index = (postcodes['post_code']",
"(tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) = \\ get_restaurant_and_process_menu(",
"\"loc_id\": postcodes_index}, ignore_index=True) # Return the amended dataframes return (tags_df,",
"that it says camden, it # will update as appropriate.",
"restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes): # This functions gets the",
"import urllib.request import pandas as pd import sqlite3 import re",
"tag is what is inside the <small> name = tag.text",
"if it exists is_item_popular = True, # False otherwise. is_item_popular",
"is inside the h3 inside the div category_name = category.h3.text",
"[]}) restaurants = pd.DataFrame({\"name\": [], \"deliveroo_name\": []})\\ .astype({\"name\": \"str\", \"deliveroo_name\":",
"\"name\": item_name, \"price_in_pence\": item_price, \"is_popular\": is_item_popular} ) # Add all",
"category to the menu_sections data frame. Again this isn't #",
"menu_sections data frame category_id = menu_sections[ (menu_sections == [restaurant_id, category_name]).all(",
"could be locale or food etc. tagtype = tag['class'][1] #",
"= menu_items.append(category_items, ignore_index=True) # Return the updated dataframes return (tags_df,",
"is inside the <small> name = tag.text # See if",
"get_restaurant_and_process_menu(url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes): #",
"deliveroo_name).index[0] # Add an entry to restaurants_to_locs saying that this",
"Add the postcode to the URL - it doesn't matter",
"# efficient. menu_sections = menu_sections.append( {\"restaurant_id\": restaurant_id, \"name\": category_name}, ignore_index=True)",
"like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' + ';q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',",
"i, link in enumerate(soup.find_all(\"a\")): print(i) # Get the destination of",
"the tagtype exists in the tag_type dataframe type_matches = tag_type[(tag_type",
"\"name\": \"str\", \"price_in_pence\": \"int64\", \"is_popular\": \"bool\"}) restaurants_to_locs = pd.DataFrame({\"restaurant_id\": [],",
"= re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # This adds this to the",
"# So this tries to find it, if it exists",
"processes its menu if it # hasn't been processed before",
"category_id = menu_sections[ (menu_sections == [restaurant_id, category_name]).all( axis=1)].index[0] # Get",
"not None # Add this menu_item to category_items category_items.append( {\"menu_section_id\":",
"page = urllib.request.urlopen(request) soup = BeautifulSoup(page) # For every link",
"restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) =\\ process_restaurants_for_postcode(post_code, tags_df, tag_type, restaurants,",
"# # https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency price_as_text = \\ menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\ .text[1:] price_as_float",
"this to restaurants_to_tags df restaurants_to_tags = restaurants_to_tags.append( {\"restaurant_id\": restaurant_id, \"tag_id\":",
"For each menu item. Found by looking for <div> inside",
"to a menu, get the restaurant and process the menu",
"# name restaurant_index = \\ (restaurants['deliveroo_name'] == deliveroo_name).index[0] # Add",
"Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' + ';q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding':",
"tag_type[(tag_type == [tagtype]).all(axis=1)] # If it doesn't if len(type_matches) ==",
"Get the id in the menu_sections data frame category_id =",
"restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) # Return the amended dataframes",
"URL postcode = re.findall('(?<=\\\\?postcode=)(.)*', url)[0] # Find where it is",
"= pd.DataFrame({\"name\": [], \"type\": []})\\ .astype({\"name\": \"str\", \"type\": \"int32\"}) tag_type",
"# Create the HTTP request request = urllib.request.Request(url, headers=hdr) #",
"item_name = \\ menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text # The price is the",
"[], \"deliveroo_name\": []})\\ .astype({\"name\": \"str\", \"deliveroo_name\": \"str\"}) restaurants_to_tags = pd.DataFrame({\"restaurant_id\":",
"'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} def process_menu(doc,",
"'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} def process_menu(doc, url,",
"dropped, it is then # converted to a floating-point number",
"scraper is Google Chrome # as opposed to a web",
"then processes its menu if it # hasn't been processed",
"all of the postcodes # Create the dataframes tags_df =",
"CSS class tag for tag in doc.find_all(\"small\", class_=\"tag\"): # The",
"the deliveroo # name restaurant_index = \\ (restaurants['deliveroo_name'] == deliveroo_name).index[0]",
"Add it entry = {\"name\": name, \"type\": type_matches.index[0]} tags_df =",
"# For each category (in the menu, e.g. Sides, Mains,",
"[], \"loc_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"loc_id\": \"int64\"}) for post_code in",
"url)[0] # This adds this to the restaurants dataframe #",
"This is so that Deliveroo think the scraper is Google",
"Add an entry to restaurants_to_locs saying that this restaurant is",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) # Return the",
"cnx, index_label=\"id\") cnx.close() if __name__ == \"__main__\": postcodes_df = pd.DataFrame({",
"is # available at this location restaurants_to_locs = restaurants_to_locs.append( {\"restaurant_id\":",
"(tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) def get_restaurant_and_process_menu(url, tags_df, tag_type,",
"category.find_all(\"div\", class_=\"menu-index-page__item-content\") for menu_item in items_html: # The name is",
"a list of tags for that restaurant restaurant_tags.append(matches.index[0]) # For",
"def get_restaurant_and_process_menu(url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes):",
"to restaurants_to_locs saying that this restaurant is # available at",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items): # This function processes the",
"menu-index-page__menu-category categories = doc.find_all(\"div\", class_=\"menu-index-page__menu-category\") for category in categories: #",
"# https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency price_as_text = \\ menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\ .text[1:] price_as_float =",
"= re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # If this restaurant hasn't been",
"menu_sections, menu_items, restaurants_to_locs, postcodes): # This function processes the restaurants",
"in pence. It is then converted to an integer. #",
"of the tag # this could be locale or food",
"menu_items, restaurants_to_locs) =\\ process_restaurants_for_postcode(post_code, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items,",
"doesn't work handle it nicely try: (tags_df, tag_type, restaurants, restaurants_to_tags,",
"[], \"is_popular\": []}).astype( {\"menu_section_id\": \"int64\", \"name\": \"str\", \"price_in_pence\": \"int64\", \"is_popular\":",
"\"deliveroo_name\": \"str\"}) restaurants_to_tags = pd.DataFrame({\"restaurant_id\": [], \"tag_id\": []})\\ .astype({\"restaurant_id\": \"int64\",",
"the restaurant and then processes its menu if it #",
"tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) # Write",
"== postcode).index[0] # Find the restaurants id in the restaurants",
"update as appropriate. url = \"https://deliveroo.co.uk/restaurants/london/camden\" \\ f\"?postcode={postcode}&sort=time\" # Create",
"menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\ .text[1:] price_as_float = float(price_as_text) item_price = int(price_as_float *",
"Get the webpage request = urllib.request.Request(url, headers=hdr) page = urllib.request.urlopen(request)",
"Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' + ';q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language':",
"= \\ menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\ .text[1:] price_as_float = float(price_as_text) item_price =",
"restaurants_to_locs = pd.DataFrame({\"restaurant_id\": [], \"loc_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"loc_id\": \"int64\"})",
"this is more efficient than doing this one at a",
"[] # For each menu item. Found by looking for",
"<h1> tag with the CSS class # restaurant_name restaurant_name =",
"'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11' + '(KHTML, like Gecko) Chrome/23.0.1271.64",
"this could be locale or food etc. tagtype = tag['class'][1]",
"so that Deliveroo think the scraper is Google Chrome #",
"'en-US,en;q=0.8', 'Connection': 'keep-alive'} def process_menu(doc, url, tags_df, tag_type, restaurants, restaurants_to_tags,",
"the tag # this could be locale or food etc.",
"Found by looking for <div> inside the category # with",
"= menu_sections[ (menu_sections == [restaurant_id, category_name]).all( axis=1)].index[0] # Get each",
"that category to the menu_items data frame, # this is",
"and process the menu, if it doesn't work handle it",
"{\"restaurant_id\": restaurant_id, \"tag_id\": tag}, ignore_index=True) # For each category (in",
"+ destination, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes)",
"menu_sections, menu_items, restaurants_to_locs) = \\ get_restaurant_and_process_menu( \"https://deliveroo.co.uk\" + destination, tags_df,",
"cnx, index_label=\"id\") menu_items.to_sql(\"MENU_ITEMS\", cnx, index_label=\"id\") menu_sections.to_sql(\"MENU_SECTIONS\", cnx, index_label=\"id\") tags_df.to_sql(\"CATEGORIES\", cnx,",
"# If it doesn't if len(matches) == 0: # Add",
"destination = link.get(\"href\") # If it's to a menu, get",
"menu-index-page__item-price. The £ symbol is dropped, it is then #",
"This isn't very efficient, if you were wanting to scrape",
"\"int64\", \"is_popular\": \"bool\"}) restaurants_to_locs = pd.DataFrame({\"restaurant_id\": [], \"loc_id\": []})\\ .astype({\"restaurant_id\":",
"=\\ process_restaurants_for_postcode(post_code, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes)",
"menu_items = pd.DataFrame( {\"menu_section_id\": [], \"name\": [], \"price_in_pence\": [], \"is_popular\":",
"it (again not very efficient) tag_type = tag_type.append({\"name\": tagtype}, ignore_index=True)",
"the <h6> with the CSS class # menu-index-page__item-title item_name =",
"with the CSS class tag for tag in doc.find_all(\"small\", class_=\"tag\"):",
"restaurants['deliveroo_name']: # Get the webpage request = urllib.request.Request(url, headers=hdr) page",
"Get the page page = urllib.request.urlopen(request) soup = BeautifulSoup(page) #",
"index_label=\"id\") menu_sections.to_sql(\"MENU_SECTIONS\", cnx, index_label=\"id\") tags_df.to_sql(\"CATEGORIES\", cnx, index_label=\"id\") tag_type.to_sql(\"CATEGORY_TYPES\", cnx, index_label=\"id\")",
"restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) # Write to db",
"If it's to a menu, get the restaurant and process",
"the restaurant_id by finding the index of what as inserted",
"tag # this could be locale or food etc. tagtype",
"# Add all the menu items in that category to",
"link destination = link.get(\"href\") # If it's to a menu,",
"menu, if it doesn't work handle it nicely try: (tags_df,",
"numbers # you wouldn't want to use .append restaurants =",
"restaurants_to_tags.append( {\"restaurant_id\": restaurant_id, \"tag_id\": tag}, ignore_index=True) # For each category",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes): # This functions",
"axis=1)].index[0] # Get each of the items in that category",
"second element of the <small> CSS class is the type",
"restaurants for the postcodes # Add the postcode to the",
"this location restaurants_to_locs = restaurants_to_locs.append( {\"restaurant_id\": restaurant_index, \"loc_id\": postcodes_index}, ignore_index=True)",
"menu_items, restaurants_to_locs) def process_all_restaurants(postcodes, db_name): # This function processes all",
"# Parameters postcodes_list = [\"W1F7EY\"] db_name = \"scraped.db\" # This",
"This adds this to the restaurants dataframe # This isn't",
"a web scraper hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)",
"with tags # Start by finding all <small> tags with",
"# Add the postcode to the URL - it doesn't",
"index_label=\"id\") restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx, index_label=\"id\") cnx.close() if __name__ == \"__main__\": postcodes_df",
"is_item_popular} ) # Add all the menu items in that",
"link in enumerate(soup.find_all(\"a\")): print(i) # Get the destination of the",
"tag_type[(tag_type == [tagtype]).all(axis=1)] # See if the tag already exists",
"# as opposed to a web scraper hdr = {'User-Agent':",
"# This function processes all of the postcodes # Create",
"menu_items, restaurants_to_locs, postcodes) # Write to db cnx = sqlite3.connect(db_name)",
"item_price, \"is_popular\": is_item_popular} ) # Add all the menu items",
"+ '(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' + ';q=0.8',",
"CSS class menu-index-page__item_content items_html = category.find_all(\"div\", class_=\"menu-index-page__item-content\") for menu_item in",
"if \"/menu\" in destination: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items,",
"= \\ get_restaurant_and_process_menu( \"https://deliveroo.co.uk\" + destination, tags_df, tag_type, restaurants, restaurants_to_tags,",
"restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) =\\ process_restaurants_for_postcode(post_code, tags_df, tag_type, restaurants, restaurants_to_tags,",
".text[1:] price_as_float = float(price_as_text) item_price = int(price_as_float * 100) #",
"restaurant restaurant_tags.append(matches.index[0]) # For each tag for tag in restaurant_tags:",
"menu_items.to_sql(\"MENU_ITEMS\", cnx, index_label=\"id\") menu_sections.to_sql(\"MENU_SECTIONS\", cnx, index_label=\"id\") tags_df.to_sql(\"CATEGORIES\", cnx, index_label=\"id\") tag_type.to_sql(\"CATEGORY_TYPES\",",
"tags_df dataframe matches = tags_df[ (tags_df == [name, type_matches.index[0]]).all(axis=1)] #",
"restaurants_to_locs) def process_restaurants_for_postcode(postcode, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs,",
"processes the restaurants for the postcodes # Add the postcode",
"a time menu_items = menu_items.append(category_items, ignore_index=True) # Return the updated",
"# If it doesn't if len(type_matches) == 0: # Add",
"process_restaurants_for_postcode(postcode, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes): #",
"in the tags_df dataframe matches = tags_df[ (tags_df == [name,",
"restaurants_to_locs.append( {\"restaurant_id\": restaurant_index, \"loc_id\": postcodes_index}, ignore_index=True) # Return the amended",
"on restaurants not in London deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0]",
"the menu # This gets the restaurant_name by finding the",
"ignore_index=True) matches = tags_df[(tags_df == [name, type_matches.index[0]]).all( axis=1)] # Add",
"tag_type dataframe type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] # If it",
"class # menu-index-page__item-popular # So this tries to find it,",
"processes the menu # This gets the restaurant_name by finding",
"tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items): # This function processes",
"pence. It is then converted to an integer. # #",
"tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes): # This",
"= tag['class'][1] # The name of the tag is what",
"wouldn't want to use .append restaurants = restaurants.append( {\"name\": restaurant_name,",
"tagtype = tag['class'][1] # The name of the tag is",
"doc.find_all(\"div\", class_=\"menu-index-page__menu-category\") for category in categories: # the category name",
"process_menu(soup, url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) except Exception:",
"in London deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # This adds",
"cnx, index_label=\"id\") restaurants.to_sql(\"RESTAURANTS\", cnx, index_label=\"id\") restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx, index_label=\"id\") menu_items.to_sql(\"MENU_ITEMS\", cnx,",
"class_=\"menu-index-page__item-content\") for menu_item in items_html: # The name is the",
"class_=\"menu-index-page__item-price\")\\ .text[1:] price_as_float = float(price_as_text) item_price = int(price_as_float * 100)",
"tags_df = pd.DataFrame({\"name\": [], \"type\": []})\\ .astype({\"name\": \"str\", \"type\": \"int32\"})",
"data frame. Again this isn't # efficient. menu_sections = menu_sections.append(",
"float(price_as_text) item_price = int(price_as_float * 100) # If an item",
"to a floating-point number (decimal), multiplied by 100 # so",
"tag to a list of tags for that restaurant restaurant_tags.append(matches.index[0])",
"(postcodes['post_code'] == postcode).index[0] # Find the restaurants id in the",
"that Deliveroo think the scraper is Google Chrome # as",
"enumerate(soup.find_all(\"a\")): print(i) # Get the destination of the link destination",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_all_restaurants(postcodes, db_name): #",
"symbol is dropped, it is then # converted to a",
"Return the amended dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"class # restaurant_name restaurant_name = doc.find(\"h1\", class_=\"restaurant__name\", text=True).text # This",
"for menu_item in items_html: # The name is the <h6>",
"and process the menu if \"/menu\" in destination: (tags_df, tag_type,",
"menu_sections, menu_items) except Exception: print(f\"Fail on {url}\") # Get the",
"dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def",
"= [] # For each menu item. Found by looking",
"by 100 # so that it is in pence. It",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) = process_menu(soup, url, tags_df, tag_type,",
"category_items.append( {\"menu_section_id\": category_id, \"name\": item_name, \"price_in_pence\": item_price, \"is_popular\": is_item_popular} )",
"or food etc. tagtype = tag['class'][1] # The name of",
"on {url}\") # Get the postcode from the URL postcode",
"The price is the <span> with the CSS class #",
"text=True).text # This gets the deliveroo_name by selecting the appropriate",
"been processed before # Get the deliveroo name from the",
"print(f\"Fail on {url}\") # Get the postcode from the URL",
"# menu-index-page__item-title item_name = \\ menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text # The price",
"the # URL # This will fail on restaurants not",
"# Write to db cnx = sqlite3.connect(db_name) postcodes.to_sql(\"POSTCODES\", cnx, index_label=\"id\")",
"hasn't been processed before # Get the deliveroo name from",
"looking for <div> inside the category # with the CSS",
"the CSS class # menu-index-page__item-price. The £ symbol is dropped,",
"name of the tag is what is inside the <small>",
"name is the <h6> with the CSS class # menu-index-page__item-title",
"£ symbol is dropped, it is then # converted to",
"to the URL - it doesn't matter that it says",
"deliveroo_name}, ignore_index=True) # This gets the restaurant_id by finding the",
"db cnx = sqlite3.connect(db_name) postcodes.to_sql(\"POSTCODES\", cnx, index_label=\"id\") restaurants.to_sql(\"RESTAURANTS\", cnx, index_label=\"id\")",
"restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) = \\ get_restaurant_and_process_menu( \"https://deliveroo.co.uk\" +",
"in the tag_type dataframe type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] #",
"category name is inside the h3 inside the div category_name",
"inside the category # with the CSS class menu-index-page__item_content items_html",
"were wanting to scrape large numbers # you wouldn't want",
"tags_df[(tags_df == [name, type_matches.index[0]]).all( axis=1)] # Add the tag to",
"';q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} def",
"scraper hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11' +",
"It is then converted to an integer. # # https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency",
"\"is_popular\": \"bool\"}) restaurants_to_locs = pd.DataFrame({\"restaurant_id\": [], \"loc_id\": []})\\ .astype({\"restaurant_id\": \"int64\",",
"So this tries to find it, if it exists is_item_popular",
"with the CSS class menu-index-page__item_content items_html = category.find_all(\"div\", class_=\"menu-index-page__item-content\") for",
"If this restaurant hasn't been seen before if deliveroo_name not",
"the div category_name = category.h3.text # Add the category to",
"tags_df.to_sql(\"CATEGORIES\", cnx, index_label=\"id\") tag_type.to_sql(\"CATEGORY_TYPES\", cnx, index_label=\"id\") restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx, index_label=\"id\") cnx.close()",
"is in pence. It is then converted to an integer.",
"restaurant hasn't been seen before if deliveroo_name not in restaurants['deliveroo_name']:",
"# Start by finding all <small> tags with the CSS",
"London deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # This adds this",
"at a time menu_items = menu_items.append(category_items, ignore_index=True) # Return the",
"in items_html: # The name is the <h6> with the",
"# you wouldn't want to use .append restaurants = restaurants.append(",
"in that category to the menu_items data frame, # this",
"restaurants_to_tags, menu_sections, menu_items) except Exception: print(f\"Fail on {url}\") # Get",
"doesn't if len(type_matches) == 0: # Add it (again not",
"restaurants_to_locs) = \\ get_restaurant_and_process_menu( \"https://deliveroo.co.uk\" + destination, tags_df, tag_type, restaurants,",
"name = tag.text # See if the tagtype exists in",
"the restaurant and process the menu if \"/menu\" in destination:",
"\"price_in_pence\": [], \"is_popular\": []}).astype( {\"menu_section_id\": \"int64\", \"name\": \"str\", \"price_in_pence\": \"int64\",",
"(tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) =\\ process_restaurants_for_postcode(post_code, tags_df,",
"restaurants_to_locs, postcodes) # Write to db cnx = sqlite3.connect(db_name) postcodes.to_sql(\"POSTCODES\",",
"restaurant and process the menu if \"/menu\" in destination: (tags_df,",
"items # This is found by looking for <div> tags",
"multiplied by 100 # so that it is in pence.",
"\"str\", \"deliveroo_name\": \"str\"}) restaurants_to_tags = pd.DataFrame({\"restaurant_id\": [], \"tag_id\": []})\\ .astype({\"restaurant_id\":",
"re from bs4 import BeautifulSoup # Parameters postcodes_list = [\"W1F7EY\"]",
"the items in that category category_items = [] # For",
"0: # Add it entry = {\"name\": name, \"type\": type_matches.index[0]}",
"that restaurant restaurant_tags.append(matches.index[0]) # For each tag for tag in",
"[restaurant_id, category_name]).all( axis=1)].index[0] # Get each of the items in",
"\"/menu\" in destination: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs)",
"(tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) = process_menu(soup, url, tags_df,",
"the postcodes # Create the dataframes tags_df = pd.DataFrame({\"name\": [],",
"menu_item to category_items category_items.append( {\"menu_section_id\": category_id, \"name\": item_name, \"price_in_pence\": item_price,",
"with the CSS class # restaurant_name restaurant_name = doc.find(\"h1\", class_=\"restaurant__name\",",
"for <div> tags with the CSS class # menu-index-page__menu-category categories",
"appropriate part from the # URL # This will fail",
"menu, e.g. Sides, Mains, Desserts, Drinks - # different for",
"price_as_float = float(price_as_text) item_price = int(price_as_float * 100) # If",
"tag for tag in doc.find_all(\"small\", class_=\"tag\"): # The second element",
"to find it, if it exists is_item_popular = True, #",
"restaurant_id, \"name\": category_name}, ignore_index=True) # Get the id in the",
"= restaurants_to_locs.append( {\"restaurant_id\": restaurant_index, \"loc_id\": postcodes_index}, ignore_index=True) # Return the",
"as inserted # Again this isn't very efficient restaurant_id =",
"= BeautifulSoup(page) # For every link in the page for",
"scrape large numbers # you wouldn't want to use .append",
"Add it (again not very efficient) tag_type = tag_type.append({\"name\": tagtype},",
"Update the matches type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] # See",
"item is popular it has a <span> with the CSS",
"restaurants = pd.DataFrame({\"name\": [], \"deliveroo_name\": []})\\ .astype({\"name\": \"str\", \"deliveroo_name\": \"str\"})",
"= tag.text # See if the tagtype exists in the",
"int(price_as_float * 100) # If an item is popular it",
"= process_menu(soup, url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) except",
"= float(price_as_text) item_price = int(price_as_float * 100) # If an",
"= doc.find(\"h1\", class_=\"restaurant__name\", text=True).text # This gets the deliveroo_name by",
"in the page for i, link in enumerate(soup.find_all(\"a\")): print(i) #",
"for that restaurant restaurant_tags.append(matches.index[0]) # For each tag for tag",
"{\"menu_section_id\": category_id, \"name\": item_name, \"price_in_pence\": item_price, \"is_popular\": is_item_popular} ) #",
"[]})\\ .astype({\"restaurant_id\": \"int64\", \"name\": \"str\"}) menu_items = pd.DataFrame( {\"menu_section_id\": [],",
"CSS class # menu-index-page__item-popular # So this tries to find",
"is_item_popular = True, # False otherwise. is_item_popular = menu_item.find( \"span\",",
"= (postcodes['post_code'] == postcode).index[0] # Find the restaurants id in",
"# Find the restaurants id in the restaurants dataframe using",
"a floating-point number (decimal), multiplied by 100 # so that",
"Add this menu_item to category_items category_items.append( {\"menu_section_id\": category_id, \"name\": item_name,",
"destination, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) #",
"[] # Deal with tags # Start by finding all",
"to the restaurants dataframe # This isn't very efficient, if",
"this to the restaurants dataframe # This isn't very efficient,",
"request request = urllib.request.Request(url, headers=hdr) # Get the page page",
"def process_all_restaurants(postcodes, db_name): # This function processes all of the",
"the id in the menu_sections data frame category_id = menu_sections[",
"# The price is the <span> with the CSS class",
"'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} def process_menu(doc, url, tags_df,",
"{\"menu_section_id\": [], \"name\": [], \"price_in_pence\": [], \"is_popular\": []}).astype( {\"menu_section_id\": \"int64\",",
"it # hasn't been processed before # Get the deliveroo",
"menu_items, restaurants_to_locs, postcodes) # Return the amended dataframes return (tags_df,",
"restaurants_to_locs, postcodes): # This function processes the restaurants for the",
"= tag_type[(tag_type == [tagtype]).all(axis=1)] # See if the tag already",
"\"int64\", \"name\": \"str\"}) menu_items = pd.DataFrame( {\"menu_section_id\": [], \"name\": [],",
"it's to a menu, get the restaurant and process the",
"<span> with the CSS class # menu-index-page__item-price. The £ symbol",
"= menu_item.find( \"span\", class_=\"menu-index-page__item-popular\") is not None # Add this",
"the <h1> tag with the CSS class # restaurant_name restaurant_name",
"the tag already exists in the tags_df dataframe matches =",
"# Add it entry = {\"name\": name, \"type\": type_matches.index[0]} tags_df",
"in categories: # the category name is inside the h3",
"not very efficient) tag_type = tag_type.append({\"name\": tagtype}, ignore_index=True) # Update",
"very efficient, if you were wanting to scrape large numbers",
"for <div> inside the category # with the CSS class",
"it doesn't work handle it nicely try: (tags_df, tag_type, restaurants,",
"== [name, type_matches.index[0]]).all( axis=1)] # Add the tag to a",
"if len(matches) == 0: # Add it entry = {\"name\":",
"(menu_sections == [restaurant_id, category_name]).all( axis=1)].index[0] # Get each of the",
"category_id, \"name\": item_name, \"price_in_pence\": item_price, \"is_popular\": is_item_popular} ) # Add",
"category_name}, ignore_index=True) # Get the id in the menu_sections data",
"restaurants, restaurants_to_tags, menu_sections, menu_items) = process_menu(soup, url, tags_df, tag_type, restaurants,",
"cnx, index_label=\"id\") tag_type.to_sql(\"CATEGORY_TYPES\", cnx, index_label=\"id\") restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx, index_label=\"id\") cnx.close() if",
"def process_menu(doc, url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items): #",
"category_name = category.h3.text # Add the category to the menu_sections",
"more efficient than doing this one at a time menu_items",
"Exception: print(f\"Fail on {url}\") # Get the postcode from the",
"index_label=\"id\") tags_df.to_sql(\"CATEGORIES\", cnx, index_label=\"id\") tag_type.to_sql(\"CATEGORY_TYPES\", cnx, index_label=\"id\") restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx, index_label=\"id\")",
"True, # False otherwise. is_item_popular = menu_item.find( \"span\", class_=\"menu-index-page__item-popular\") is",
"restaurants dataframe # This isn't very efficient, if you were",
"the tag to a list of tags for that restaurant",
"restaurant though!) process the menu items # This is found",
"one at a time menu_items = menu_items.append(category_items, ignore_index=True) # Return",
"menu_sections, menu_items, restaurants_to_locs) def process_restaurants_for_postcode(postcode, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"pd.DataFrame({\"restaurant_id\": [], \"loc_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"loc_id\": \"int64\"}) for post_code",
"<div> inside the category # with the CSS class menu-index-page__item_content",
"(tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_all_restaurants(postcodes, db_name):",
"the restaurants id in the restaurants dataframe using the deliveroo",
"of the postcodes # Create the dataframes tags_df = pd.DataFrame({\"name\":",
"bs4 import BeautifulSoup # Parameters postcodes_list = [\"W1F7EY\"] db_name =",
"# This gets the restaurant_id by finding the index of",
"category # with the CSS class menu-index-page__item_content items_html = category.find_all(\"div\",",
"is popular it has a <span> with the CSS class",
"\"price_in_pence\": item_price, \"is_popular\": is_item_popular} ) # Add all the menu",
"'(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # If this restaurant hasn't been seen before",
"restaurants_to_tags, menu_sections, menu_items) = process_menu(soup, url, tags_df, tag_type, restaurants, restaurants_to_tags,",
"\"str\"}) restaurants_to_tags = pd.DataFrame({\"restaurant_id\": [], \"tag_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"tag_id\":",
"\"scraped.db\" # This is so that Deliveroo think the scraper",
"The name of the tag is what is inside the",
"the URL postcode = re.findall('(?<=\\\\?postcode=)(.)*', url)[0] # Find where it",
"entry = {\"name\": name, \"type\": type_matches.index[0]} tags_df = tags_df.append(entry, ignore_index=True)",
"return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_restaurants_for_postcode(postcode,",
"\"str\"}) menu_items = pd.DataFrame( {\"menu_section_id\": [], \"name\": [], \"price_in_pence\": [],",
"class_=\"menu-index-page__item-popular\") is not None # Add this menu_item to category_items",
"want to use .append restaurants = restaurants.append( {\"name\": restaurant_name, \"deliveroo_name\":",
"url)[0] # Find where it is in the postcodes data",
"pd.DataFrame({\"restaurant_id\": [], \"tag_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"tag_id\": \"int64\"}) menu_sections =",
"for post_code in postcodes['post_code']: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items,",
"as opposed to a web scraper hdr = {'User-Agent': 'Mozilla/5.0",
"tags for that restaurant restaurant_tags.append(matches.index[0]) # For each tag for",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_restaurants_for_postcode(postcode, tags_df, tag_type,",
"HTTP request request = urllib.request.Request(url, headers=hdr) # Get the page",
"[]}).astype( {\"menu_section_id\": \"int64\", \"name\": \"str\", \"price_in_pence\": \"int64\", \"is_popular\": \"bool\"}) restaurants_to_locs",
"in the restaurants dataframe using the deliveroo # name restaurant_index",
"restaurants_to_tags = restaurants_to_tags.append( {\"restaurant_id\": restaurant_id, \"tag_id\": tag}, ignore_index=True) # For",
"available at this location restaurants_to_locs = restaurants_to_locs.append( {\"restaurant_id\": restaurant_index, \"loc_id\":",
"Mains, Desserts, Drinks - # different for every restaurant though!)",
"[], \"tag_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"tag_id\": \"int64\"}) menu_sections = pd.DataFrame({\"restaurant_id\":",
"{\"restaurant_id\": restaurant_id, \"name\": category_name}, ignore_index=True) # Get the id in",
"menu item. Found by looking for <div> inside the category",
"cnx, index_label=\"id\") restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx, index_label=\"id\") cnx.close() if __name__ == \"__main__\":",
"ignore_index=True) # Return the updated dataframes return (tags_df, tag_type, restaurants,",
"it says camden, it # will update as appropriate. url",
"# available at this location restaurants_to_locs = restaurants_to_locs.append( {\"restaurant_id\": restaurant_index,",
"the URL - it doesn't matter that it says camden,",
"the restaurants dataframe # This isn't very efficient, if you",
"cnx, index_label=\"id\") restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx, index_label=\"id\") menu_items.to_sql(\"MENU_ITEMS\", cnx, index_label=\"id\") menu_sections.to_sql(\"MENU_SECTIONS\", cnx,",
"tags # Start by finding all <small> tags with the",
"to the menu_items data frame, # this is more efficient",
"# False otherwise. is_item_popular = menu_item.find( \"span\", class_=\"menu-index-page__item-popular\") is not",
"tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) except Exception: print(f\"Fail on",
"== deliveroo_name).index[0] # Add an entry to restaurants_to_locs saying that",
"index_label=\"id\") menu_items.to_sql(\"MENU_ITEMS\", cnx, index_label=\"id\") menu_sections.to_sql(\"MENU_SECTIONS\", cnx, index_label=\"id\") tags_df.to_sql(\"CATEGORIES\", cnx, index_label=\"id\")",
"# See if the tag already exists in the tags_df",
"Find the restaurants id in the restaurants dataframe using the",
"restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_restaurants_for_postcode(postcode, tags_df, tag_type, restaurants, restaurants_to_tags,",
"is not None # Add this menu_item to category_items category_items.append(",
"category to the menu_items data frame, # this is more",
"each of the items in that category category_items = []",
"popular it has a <span> with the CSS class #",
"function processes the restaurants for the postcodes # Add the",
"category_items = [] # For each menu item. Found by",
"cnx.close() if __name__ == \"__main__\": postcodes_df = pd.DataFrame({ 'post_code': postcodes_list",
"[]})\\ .astype({\"name\": \"str\", \"type\": \"int32\"}) tag_type = pd.DataFrame({\"name\": []}) restaurants",
"the menu if \"/menu\" in destination: (tags_df, tag_type, restaurants, restaurants_to_tags,",
"\"bool\"}) restaurants_to_locs = pd.DataFrame({\"restaurant_id\": [], \"loc_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"loc_id\":",
"restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx, index_label=\"id\") menu_items.to_sql(\"MENU_ITEMS\", cnx, index_label=\"id\") menu_sections.to_sql(\"MENU_SECTIONS\", cnx, index_label=\"id\") tags_df.to_sql(\"CATEGORIES\",",
"menu_items = menu_items.append(category_items, ignore_index=True) # Return the updated dataframes return",
"sqlite3.connect(db_name) postcodes.to_sql(\"POSTCODES\", cnx, index_label=\"id\") restaurants.to_sql(\"RESTAURANTS\", cnx, index_label=\"id\") restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx, index_label=\"id\")",
"This will fail on restaurants not in London deliveroo_name =",
"If it doesn't if len(matches) == 0: # Add it",
"item_price = int(price_as_float * 100) # If an item is",
"The second element of the <small> CSS class is the",
"tag}, ignore_index=True) # For each category (in the menu, e.g.",
"this one at a time menu_items = menu_items.append(category_items, ignore_index=True) #",
"part from the # URL # This will fail on",
"# Get the id in the menu_sections data frame category_id",
"restaurants_to_tags = pd.DataFrame({\"restaurant_id\": [], \"tag_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"tag_id\": \"int64\"})",
"list of tags for that restaurant restaurant_tags.append(matches.index[0]) # For each",
"it, if it exists is_item_popular = True, # False otherwise.",
"postcodes data frame postcodes_index = (postcodes['post_code'] == postcode).index[0] # Find",
"the restaurants for the postcodes # Add the postcode to",
"= restaurants.append( {\"name\": restaurant_name, \"deliveroo_name\": deliveroo_name}, ignore_index=True) # This gets",
"converted to a floating-point number (decimal), multiplied by 100 #",
"urllib.request.Request(url, headers=hdr) page = urllib.request.urlopen(request) soup = BeautifulSoup(page) # Try",
"# Get the deliveroo name from the url deliveroo_name =",
"index_label=\"id\") cnx.close() if __name__ == \"__main__\": postcodes_df = pd.DataFrame({ 'post_code':",
"= urllib.request.urlopen(request) soup = BeautifulSoup(page) # For every link in",
"== \"__main__\": postcodes_df = pd.DataFrame({ 'post_code': postcodes_list }) process_all_restaurants(postcodes_df, db_name)",
"time menu_items = menu_items.append(category_items, ignore_index=True) # Return the updated dataframes",
"with the CSS class # menu-index-page__menu-category categories = doc.find_all(\"div\", class_=\"menu-index-page__menu-category\")",
"class_=\"restaurant__name\", text=True).text # This gets the deliveroo_name by selecting the",
"restaurants, restaurants_to_tags, menu_sections, menu_items): # This function processes the menu",
"# Get the postcode from the URL postcode = re.findall('(?<=\\\\?postcode=)(.)*',",
"class # menu-index-page__menu-category categories = doc.find_all(\"div\", class_=\"menu-index-page__menu-category\") for category in",
"if it doesn't work handle it nicely try: (tags_df, tag_type,",
"= \"scraped.db\" # This is so that Deliveroo think the",
"think the scraper is Google Chrome # as opposed to",
"hasn't been seen before if deliveroo_name not in restaurants['deliveroo_name']: #",
"pd.DataFrame({\"restaurant_id\": [], \"name\": []})\\ .astype({\"restaurant_id\": \"int64\", \"name\": \"str\"}) menu_items =",
"# this could be locale or food etc. tagtype =",
"is the <span> with the CSS class # menu-index-page__item-price. The",
"\"tag_id\": \"int64\"}) menu_sections = pd.DataFrame({\"restaurant_id\": [], \"name\": []})\\ .astype({\"restaurant_id\": \"int64\",",
"class # menu-index-page__item-price. The £ symbol is dropped, it is",
") # Add all the menu items in that category",
"gets the restaurant_id by finding the index of what as",
"is so that Deliveroo think the scraper is Google Chrome",
"= pd.DataFrame({\"name\": [], \"deliveroo_name\": []})\\ .astype({\"name\": \"str\", \"deliveroo_name\": \"str\"}) restaurants_to_tags",
"as appropriate. url = \"https://deliveroo.co.uk/restaurants/london/camden\" \\ f\"?postcode={postcode}&sort=time\" # Create the",
"doesn't if len(matches) == 0: # Add it entry =",
"Deliveroo think the scraper is Google Chrome # as opposed",
"restaurant is # available at this location restaurants_to_locs = restaurants_to_locs.append(",
"doing this one at a time menu_items = menu_items.append(category_items, ignore_index=True)",
"by selecting the appropriate part from the # URL #",
"frame, # this is more efficient than doing this one",
"This function processes all of the postcodes # Create the",
"type of the tag # this could be locale or",
"postcode).index[0] # Find the restaurants id in the restaurants dataframe",
"restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) # Return the amended",
"then converted to an integer. # # https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency price_as_text =",
"[], \"type\": []})\\ .astype({\"name\": \"str\", \"type\": \"int32\"}) tag_type = pd.DataFrame({\"name\":",
"by looking for <div> inside the category # with the",
"it is then # converted to a floating-point number (decimal),",
"the tag_type dataframe type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] # If",
"integer. # # https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency price_as_text = \\ menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\ .text[1:]",
"webpage request = urllib.request.Request(url, headers=hdr) page = urllib.request.urlopen(request) soup =",
"function processes all of the postcodes # Create the dataframes",
"restaurants, restaurants_to_tags, menu_sections, menu_items) def get_restaurant_and_process_menu(url, tags_df, tag_type, restaurants, restaurants_to_tags,",
"# The name of the tag is what is inside",
"this isn't very efficient restaurant_id = restaurants[ (restaurants == [restaurant_name,",
"all <small> tags with the CSS class tag for tag",
"items_html = category.find_all(\"div\", class_=\"menu-index-page__item-content\") for menu_item in items_html: # The",
".astype({\"restaurant_id\": \"int64\", \"loc_id\": \"int64\"}) for post_code in postcodes['post_code']: (tags_df, tag_type,",
"= pd.DataFrame({\"restaurant_id\": [], \"name\": []})\\ .astype({\"restaurant_id\": \"int64\", \"name\": \"str\"}) menu_items",
"* 100) # If an item is popular it has",
"\"type\": []})\\ .astype({\"name\": \"str\", \"type\": \"int32\"}) tag_type = pd.DataFrame({\"name\": []})",
"re.findall('(?<=\\\\?postcode=)(.)*', url)[0] # Find where it is in the postcodes",
"# Return the updated dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags,",
"if len(type_matches) == 0: # Add it (again not very",
"restaurant_id by finding the index of what as inserted #",
"updated dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) def",
"the scraper is Google Chrome # as opposed to a",
"it has a <span> with the CSS class # menu-index-page__item-popular",
"= doc.find_all(\"div\", class_=\"menu-index-page__menu-category\") for category in categories: # the category",
"= [] # Deal with tags # Start by finding",
"category in categories: # the category name is inside the",
"ignore_index=True) # This gets the restaurant_id by finding the index",
"the CSS class # menu-index-page__menu-category categories = doc.find_all(\"div\", class_=\"menu-index-page__menu-category\") for",
"in doc.find_all(\"small\", class_=\"tag\"): # The second element of the <small>",
"= category.h3.text # Add the category to the menu_sections data",
"in restaurant_tags: # Add this to restaurants_to_tags df restaurants_to_tags =",
"class_=\"menu-index-page__item-title\").text # The price is the <span> with the CSS",
"If an item is popular it has a <span> with",
"deliveroo_name not in restaurants['deliveroo_name']: # Get the webpage request =",
"that this restaurant is # available at this location restaurants_to_locs",
"[restaurant_name, deliveroo_name]).all( axis=1)].index[0] restaurant_tags = [] # Deal with tags",
"in the menu_sections data frame category_id = menu_sections[ (menu_sections ==",
"len(type_matches) == 0: # Add it (again not very efficient)",
"deliveroo name from the url deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0]",
".astype({\"name\": \"str\", \"type\": \"int32\"}) tag_type = pd.DataFrame({\"name\": []}) restaurants =",
"element of the <small> CSS class is the type of",
"= {\"name\": name, \"type\": type_matches.index[0]} tags_df = tags_df.append(entry, ignore_index=True) matches",
"data frame postcodes_index = (postcodes['post_code'] == postcode).index[0] # Find the",
"restaurants dataframe using the deliveroo # name restaurant_index = \\",
"[\"W1F7EY\"] db_name = \"scraped.db\" # This is so that Deliveroo",
"every restaurant though!) process the menu items # This is",
"menu_sections, menu_items, restaurants_to_locs, postcodes) # Return the amended dataframes return",
"type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] # If it doesn't if",
"location restaurants_to_locs = restaurants_to_locs.append( {\"restaurant_id\": restaurant_index, \"loc_id\": postcodes_index}, ignore_index=True) #",
"menu_sections, menu_items, restaurants_to_locs) def process_all_restaurants(postcodes, db_name): # This function processes",
"\"name\": [], \"price_in_pence\": [], \"is_popular\": []}).astype( {\"menu_section_id\": \"int64\", \"name\": \"str\",",
"# Try and process the menu, if it doesn't work",
"the postcode from the URL postcode = re.findall('(?<=\\\\?postcode=)(.)*', url)[0] #",
"doc.find(\"h1\", class_=\"restaurant__name\", text=True).text # This gets the deliveroo_name by selecting",
"category (in the menu, e.g. Sides, Mains, Desserts, Drinks -",
"by finding the <h1> tag with the CSS class #",
"== [tagtype]).all(axis=1)] # If it doesn't if len(type_matches) == 0:",
"== [restaurant_id, category_name]).all( axis=1)].index[0] # Get each of the items",
"matches = tags_df[ (tags_df == [name, type_matches.index[0]]).all(axis=1)] # If it",
"restaurants_to_tags df restaurants_to_tags = restaurants_to_tags.append( {\"restaurant_id\": restaurant_id, \"tag_id\": tag}, ignore_index=True)",
"div category_name = category.h3.text # Add the category to the",
"# This isn't very efficient, if you were wanting to",
"name restaurant_index = \\ (restaurants['deliveroo_name'] == deliveroo_name).index[0] # Add an",
"been seen before if deliveroo_name not in restaurants['deliveroo_name']: # Get",
"you wouldn't want to use .append restaurants = restaurants.append( {\"name\":",
"(restaurants['deliveroo_name'] == deliveroo_name).index[0] # Add an entry to restaurants_to_locs saying",
"tag.text # See if the tagtype exists in the tag_type",
"menu_items) = process_menu(soup, url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items)",
"= \\ (restaurants['deliveroo_name'] == deliveroo_name).index[0] # Add an entry to",
"= {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11' + '(KHTML, like",
"it entry = {\"name\": name, \"type\": type_matches.index[0]} tags_df = tags_df.append(entry,",
"wanting to scrape large numbers # you wouldn't want to",
"# For every link in the page for i, link",
"the matches type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] # See if",
"Find where it is in the postcodes data frame postcodes_index",
"menu, get the restaurant and process the menu if \"/menu\"",
".astype({\"restaurant_id\": \"int64\", \"tag_id\": \"int64\"}) menu_sections = pd.DataFrame({\"restaurant_id\": [], \"name\": []})\\",
"the type of the tag # this could be locale",
"restaurant_tags.append(matches.index[0]) # For each tag for tag in restaurant_tags: #",
"each category (in the menu, e.g. Sides, Mains, Desserts, Drinks",
"is found by looking for <div> tags with the CSS",
"large numbers # you wouldn't want to use .append restaurants",
"menu_sections = menu_sections.append( {\"restaurant_id\": restaurant_id, \"name\": category_name}, ignore_index=True) # Get",
"categories: # the category name is inside the h3 inside",
"id in the menu_sections data frame category_id = menu_sections[ (menu_sections",
"and then processes its menu if it # hasn't been",
"otherwise. is_item_popular = menu_item.find( \"span\", class_=\"menu-index-page__item-popular\") is not None #",
"restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes): # This function processes the",
"# URL # This will fail on restaurants not in",
"dataframes tags_df = pd.DataFrame({\"name\": [], \"type\": []})\\ .astype({\"name\": \"str\", \"type\":",
"menu-index-page__item-popular # So this tries to find it, if it",
"urllib.request.urlopen(request) soup = BeautifulSoup(page) # For every link in the",
"the menu, if it doesn't work handle it nicely try:",
"menu_sections, menu_items) = process_menu(soup, url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_all_restaurants(postcodes,",
"index_label=\"id\") restaurants.to_sql(\"RESTAURANTS\", cnx, index_label=\"id\") restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx, index_label=\"id\") menu_items.to_sql(\"MENU_ITEMS\", cnx, index_label=\"id\")",
"efficient. menu_sections = menu_sections.append( {\"restaurant_id\": restaurant_id, \"name\": category_name}, ignore_index=True) #",
"Get the deliveroo name from the url deliveroo_name = re.findall(",
"tags_df.append(entry, ignore_index=True) matches = tags_df[(tags_df == [name, type_matches.index[0]]).all( axis=1)] #",
"the index of what as inserted # Again this isn't",
"\"name\": category_name}, ignore_index=True) # Get the id in the menu_sections",
"it exists is_item_popular = True, # False otherwise. is_item_popular =",
"using the deliveroo # name restaurant_index = \\ (restaurants['deliveroo_name'] ==",
"db_name): # This function processes all of the postcodes #",
"deliveroo # name restaurant_index = \\ (restaurants['deliveroo_name'] == deliveroo_name).index[0] #",
"postcodes['post_code']: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) =\\ process_restaurants_for_postcode(post_code,",
"food etc. tagtype = tag['class'][1] # The name of the",
"then # converted to a floating-point number (decimal), multiplied by",
"= tag_type.append({\"name\": tagtype}, ignore_index=True) # Update the matches type_matches =",
"the page for i, link in enumerate(soup.find_all(\"a\")): print(i) # Get",
"this menu_item to category_items category_items.append( {\"menu_section_id\": category_id, \"name\": item_name, \"price_in_pence\":",
"# Find where it is in the postcodes data frame",
"# Get the page page = urllib.request.urlopen(request) soup = BeautifulSoup(page)",
"it doesn't if len(matches) == 0: # Add it entry",
"efficient restaurant_id = restaurants[ (restaurants == [restaurant_name, deliveroo_name]).all( axis=1)].index[0] restaurant_tags",
"an integer. # # https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency price_as_text = \\ menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\",
"for tag in doc.find_all(\"small\", class_=\"tag\"): # The second element of",
"= tags_df[ (tags_df == [name, type_matches.index[0]]).all(axis=1)] # If it doesn't",
"# Return the amended dataframes return (tags_df, tag_type, restaurants, restaurants_to_tags,",
"url = \"https://deliveroo.co.uk/restaurants/london/camden\" \\ f\"?postcode={postcode}&sort=time\" # Create the HTTP request",
"This gets the deliveroo_name by selecting the appropriate part from",
"is in the postcodes data frame postcodes_index = (postcodes['post_code'] ==",
"[name, type_matches.index[0]]).all(axis=1)] # If it doesn't if len(matches) == 0:",
"For each category (in the menu, e.g. Sides, Mains, Desserts,",
"menu_items): # This function processes the menu # This gets",
"to a web scraper hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux",
"not in restaurants['deliveroo_name']: # Get the webpage request = urllib.request.Request(url,",
"the destination of the link destination = link.get(\"href\") # If",
"urllib.request.Request(url, headers=hdr) # Get the page page = urllib.request.urlopen(request) soup",
"price is the <span> with the CSS class # menu-index-page__item-price.",
"import re from bs4 import BeautifulSoup # Parameters postcodes_list =",
"= restaurants[ (restaurants == [restaurant_name, deliveroo_name]).all( axis=1)].index[0] restaurant_tags = []",
"# This function processes the menu # This gets the",
"'Connection': 'keep-alive'} def process_menu(doc, url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"if you were wanting to scrape large numbers # you",
"is the type of the tag # this could be",
"\"deliveroo_name\": deliveroo_name}, ignore_index=True) # This gets the restaurant_id by finding",
"it doesn't if len(type_matches) == 0: # Add it (again",
"== [tagtype]).all(axis=1)] # See if the tag already exists in",
"found by looking for <div> tags with the CSS class",
"the category # with the CSS class menu-index-page__item_content items_html =",
"# This will fail on restaurants not in London deliveroo_name",
"appropriate. url = \"https://deliveroo.co.uk/restaurants/london/camden\" \\ f\"?postcode={postcode}&sort=time\" # Create the HTTP",
"tagtype}, ignore_index=True) # Update the matches type_matches = tag_type[(tag_type ==",
"link.get(\"href\") # If it's to a menu, get the restaurant",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) = \\ get_restaurant_and_process_menu( \"https://deliveroo.co.uk\"",
"type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)] # See if the tag",
"\"int64\"}) menu_sections = pd.DataFrame({\"restaurant_id\": [], \"name\": []})\\ .astype({\"restaurant_id\": \"int64\", \"name\":",
"gets the deliveroo_name by selecting the appropriate part from the",
"- # different for every restaurant though!) process the menu",
"tag_type.to_sql(\"CATEGORY_TYPES\", cnx, index_label=\"id\") restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx, index_label=\"id\") cnx.close() if __name__ ==",
"\"tag_id\": tag}, ignore_index=True) # For each category (in the menu,",
"headers=hdr) page = urllib.request.urlopen(request) soup = BeautifulSoup(page) # Try and",
"is Google Chrome # as opposed to a web scraper",
"\"span\", class_=\"menu-index-page__item-popular\") is not None # Add this menu_item to",
"\"str\", \"price_in_pence\": \"int64\", \"is_popular\": \"bool\"}) restaurants_to_locs = pd.DataFrame({\"restaurant_id\": [], \"loc_id\":",
"restaurants_to_locs saying that this restaurant is # available at this",
"[], \"name\": [], \"price_in_pence\": [], \"is_popular\": []}).astype( {\"menu_section_id\": \"int64\", \"name\":",
"tag in restaurant_tags: # Add this to restaurants_to_tags df restaurants_to_tags",
"to category_items category_items.append( {\"menu_section_id\": category_id, \"name\": item_name, \"price_in_pence\": item_price, \"is_popular\":",
"restaurant_id = restaurants[ (restaurants == [restaurant_name, deliveroo_name]).all( axis=1)].index[0] restaurant_tags =",
"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency price_as_text = \\ menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\ .text[1:] price_as_float = float(price_as_text)",
"every link in the page for i, link in enumerate(soup.find_all(\"a\")):",
"\"loc_id\": \"int64\"}) for post_code in postcodes['post_code']: (tags_df, tag_type, restaurants, restaurants_to_tags,",
"[]})\\ .astype({\"name\": \"str\", \"deliveroo_name\": \"str\"}) restaurants_to_tags = pd.DataFrame({\"restaurant_id\": [], \"tag_id\":",
"in destination: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) =",
"by finding the index of what as inserted # Again",
"# will update as appropriate. url = \"https://deliveroo.co.uk/restaurants/london/camden\" \\ f\"?postcode={postcode}&sort=time\"",
"where it is in the postcodes data frame postcodes_index =",
"If it doesn't if len(type_matches) == 0: # Add it",
"tag for tag in restaurant_tags: # Add this to restaurants_to_tags",
"'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' + ';q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection':",
"what as inserted # Again this isn't very efficient restaurant_id",
"False otherwise. is_item_popular = menu_item.find( \"span\", class_=\"menu-index-page__item-popular\") is not None",
"(X11; Linux x86_64) AppleWebKit/537.11' + '(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',",
"a menu, get the restaurant and process the menu if",
"df restaurants_to_tags = restaurants_to_tags.append( {\"restaurant_id\": restaurant_id, \"tag_id\": tag}, ignore_index=True) #",
"you were wanting to scrape large numbers # you wouldn't",
"'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' + ';q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8',",
"= urllib.request.Request(url, headers=hdr) page = urllib.request.urlopen(request) soup = BeautifulSoup(page) #",
"postcodes_index}, ignore_index=True) # Return the amended dataframes return (tags_df, tag_type,",
"camden, it # will update as appropriate. url = \"https://deliveroo.co.uk/restaurants/london/camden\"",
"restaurants.to_sql(\"RESTAURANTS\", cnx, index_label=\"id\") restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx, index_label=\"id\") menu_items.to_sql(\"MENU_ITEMS\", cnx, index_label=\"id\") menu_sections.to_sql(\"MENU_SECTIONS\",",
"Try and process the menu, if it doesn't work handle",
"of the items in that category category_items = [] #",
"index_label=\"id\") tag_type.to_sql(\"CATEGORY_TYPES\", cnx, index_label=\"id\") restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx, index_label=\"id\") cnx.close() if __name__",
"= pd.DataFrame({\"restaurant_id\": [], \"loc_id\": []})\\ .astype({\"restaurant_id\": \"int64\", \"loc_id\": \"int64\"}) for",
"'keep-alive'} def process_menu(doc, url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items):",
"in that category category_items = [] # For each menu",
"the CSS class # menu-index-page__item-title item_name = \\ menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text",
"with the CSS class # menu-index-page__item-title item_name = \\ menu_item.find(\"h6\",",
"menu_sections data frame. Again this isn't # efficient. menu_sections =",
"menu_sections, menu_items, restaurants_to_locs, postcodes): # This functions gets the restaurant",
"the postcodes data frame postcodes_index = (postcodes['post_code'] == postcode).index[0] #",
"postcode to the URL - it doesn't matter that it",
"\"deliveroo_name\": []})\\ .astype({\"name\": \"str\", \"deliveroo_name\": \"str\"}) restaurants_to_tags = pd.DataFrame({\"restaurant_id\": [],",
"inserted # Again this isn't very efficient restaurant_id = restaurants[",
"\"https://deliveroo.co.uk\" + destination, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs,",
"(decimal), multiplied by 100 # so that it is in",
"tags with the CSS class tag for tag in doc.find_all(\"small\",",
"looking for <div> tags with the CSS class # menu-index-page__menu-category",
"saying that this restaurant is # available at this location",
"Get the postcode from the URL postcode = re.findall('(?<=\\\\?postcode=)(.)*', url)[0]",
"matter that it says camden, it # will update as",
"the menu_sections data frame. Again this isn't # efficient. menu_sections",
"page for i, link in enumerate(soup.find_all(\"a\")): print(i) # Get the",
"items_html: # The name is the <h6> with the CSS",
"# Deal with tags # Start by finding all <small>",
"Get each of the items in that category category_items =",
"= link.get(\"href\") # If it's to a menu, get the",
"menu_items.append(category_items, ignore_index=True) # Return the updated dataframes return (tags_df, tag_type,",
"= pd.DataFrame( {\"menu_section_id\": [], \"name\": [], \"price_in_pence\": [], \"is_popular\": []}).astype(",
"will fail on restaurants not in London deliveroo_name = re.findall(",
"deliveroo_name]).all( axis=1)].index[0] restaurant_tags = [] # Deal with tags #",
"<small> tags with the CSS class tag for tag in",
"The name is the <h6> with the CSS class #",
"menu_items, restaurants_to_locs, postcodes): # This function processes the restaurants for",
"re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # This adds this to the restaurants",
"menu_items, restaurants_to_locs) = \\ get_restaurant_and_process_menu( \"https://deliveroo.co.uk\" + destination, tags_df, tag_type,",
"is what is inside the <small> name = tag.text #",
"print(i) # Get the destination of the link destination =",
"if the tagtype exists in the tag_type dataframe type_matches =",
".append restaurants = restaurants.append( {\"name\": restaurant_name, \"deliveroo_name\": deliveroo_name}, ignore_index=True) #",
"data frame category_id = menu_sections[ (menu_sections == [restaurant_id, category_name]).all( axis=1)].index[0]",
"if the tag already exists in the tags_df dataframe matches",
"menu_sections, menu_items) def get_restaurant_and_process_menu(url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items,",
"its menu if it # hasn't been processed before #",
"tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes): # This function",
"the page page = urllib.request.urlopen(request) soup = BeautifulSoup(page) # For",
"very efficient restaurant_id = restaurants[ (restaurants == [restaurant_name, deliveroo_name]).all( axis=1)].index[0]",
"gets the restaurant and then processes its menu if it",
"restaurants not in London deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] #",
"tagtype exists in the tag_type dataframe type_matches = tag_type[(tag_type ==",
"restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_all_restaurants(postcodes, db_name): # This",
"# If this restaurant hasn't been seen before if deliveroo_name",
"this isn't # efficient. menu_sections = menu_sections.append( {\"restaurant_id\": restaurant_id, \"name\":",
"restaurants_to_tags, menu_sections, menu_items) def get_restaurant_and_process_menu(url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,",
"processed before # Get the deliveroo name from the url",
"restaurants id in the restaurants dataframe using the deliveroo #",
"restaurants.append( {\"name\": restaurant_name, \"deliveroo_name\": deliveroo_name}, ignore_index=True) # This gets the",
"AppleWebKit/537.11' + '(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' +",
"[name, type_matches.index[0]]).all( axis=1)] # Add the tag to a list",
"exists is_item_popular = True, # False otherwise. is_item_popular = menu_item.find(",
"= menu_sections.append( {\"restaurant_id\": restaurant_id, \"name\": category_name}, ignore_index=True) # Get the",
"This function processes the restaurants for the postcodes # Add",
"== [restaurant_name, deliveroo_name]).all( axis=1)].index[0] restaurant_tags = [] # Deal with",
"tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes) # Return",
"postcodes # Create the dataframes tags_df = pd.DataFrame({\"name\": [], \"type\":",
"to scrape large numbers # you wouldn't want to use",
"= True, # False otherwise. is_item_popular = menu_item.find( \"span\", class_=\"menu-index-page__item-popular\")",
"import pandas as pd import sqlite3 import re from bs4",
"= BeautifulSoup(page) # Try and process the menu, if it",
"= restaurants_to_tags.append( {\"restaurant_id\": restaurant_id, \"tag_id\": tag}, ignore_index=True) # For each",
"menu_sections, menu_items): # This function processes the menu # This",
"the <small> name = tag.text # See if the tagtype",
"that it is in pence. It is then converted to",
"restaurant_tags: # Add this to restaurants_to_tags df restaurants_to_tags = restaurants_to_tags.append(",
"# Add this menu_item to category_items category_items.append( {\"menu_section_id\": category_id, \"name\":",
"ignore_index=True) # Return the amended dataframes return (tags_df, tag_type, restaurants,",
"type_matches.index[0]} tags_df = tags_df.append(entry, ignore_index=True) matches = tags_df[(tags_df == [name,",
"the postcodes # Add the postcode to the URL -",
"BeautifulSoup(page) # For every link in the page for i,",
"f\"?postcode={postcode}&sort=time\" # Create the HTTP request request = urllib.request.Request(url, headers=hdr)",
"= \\ menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text # The price is the <span>",
"# menu-index-page__item-price. The £ symbol is dropped, it is then",
"functions gets the restaurant and then processes its menu if",
"from the # URL # This will fail on restaurants",
"of the tag is what is inside the <small> name",
"to use .append restaurants = restaurants.append( {\"name\": restaurant_name, \"deliveroo_name\": deliveroo_name},",
"= \"https://deliveroo.co.uk/restaurants/london/camden\" \\ f\"?postcode={postcode}&sort=time\" # Create the HTTP request request",
"from the url deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # If",
"the menu_sections data frame category_id = menu_sections[ (menu_sections == [restaurant_id,",
"menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text # The price is the <span> with the",
"category_name]).all( axis=1)].index[0] # Get each of the items in that",
"category category_items = [] # For each menu item. Found",
"tag_type = tag_type.append({\"name\": tagtype}, ignore_index=True) # Update the matches type_matches",
"in the postcodes data frame postcodes_index = (postcodes['post_code'] == postcode).index[0]",
"= re.findall('(?<=\\\\?postcode=)(.)*', url)[0] # Find where it is in the",
"at this location restaurants_to_locs = restaurants_to_locs.append( {\"restaurant_id\": restaurant_index, \"loc_id\": postcodes_index},",
"restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs, postcodes): # This function processes",
"# Add an entry to restaurants_to_locs saying that this restaurant",
"restaurant_index, \"loc_id\": postcodes_index}, ignore_index=True) # Return the amended dataframes return",
"index_label=\"id\") restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx, index_label=\"id\") menu_items.to_sql(\"MENU_ITEMS\", cnx, index_label=\"id\") menu_sections.to_sql(\"MENU_SECTIONS\", cnx, index_label=\"id\")",
"the category name is inside the h3 inside the div",
"See if the tag already exists in the tags_df dataframe",
"This gets the restaurant_name by finding the <h1> tag with",
"that category category_items = [] # For each menu item.",
"= tags_df[(tags_df == [name, type_matches.index[0]]).all( axis=1)] # Add the tag",
"if it # hasn't been processed before # Get the",
"= int(price_as_float * 100) # If an item is popular",
"= urllib.request.Request(url, headers=hdr) # Get the page page = urllib.request.urlopen(request)",
"this tries to find it, if it exists is_item_popular =",
"db_name = \"scraped.db\" # This is so that Deliveroo think",
"of what as inserted # Again this isn't very efficient",
"different for every restaurant though!) process the menu items #",
"soup = BeautifulSoup(page) # Try and process the menu, if",
"<span> with the CSS class # menu-index-page__item-popular # So this",
"\"type\": \"int32\"}) tag_type = pd.DataFrame({\"name\": []}) restaurants = pd.DataFrame({\"name\": [],",
"frame category_id = menu_sections[ (menu_sections == [restaurant_id, category_name]).all( axis=1)].index[0] #",
"CSS class # menu-index-page__item-title item_name = \\ menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text #",
"locale or food etc. tagtype = tag['class'][1] # The name",
"# Again this isn't very efficient restaurant_id = restaurants[ (restaurants",
"class_=\"menu-index-page__menu-category\") for category in categories: # the category name is",
"for i, link in enumerate(soup.find_all(\"a\")): print(i) # Get the destination",
"pd.DataFrame({\"name\": [], \"deliveroo_name\": []})\\ .astype({\"name\": \"str\", \"deliveroo_name\": \"str\"}) restaurants_to_tags =",
"x86_64) AppleWebKit/537.11' + '(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*'",
"'(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # This adds this to the restaurants dataframe",
"For every link in the page for i, link in",
"Parameters postcodes_list = [\"W1F7EY\"] db_name = \"scraped.db\" # This is",
"= [\"W1F7EY\"] db_name = \"scraped.db\" # This is so that",
"# This is so that Deliveroo think the scraper is",
"CSS class is the type of the tag # this",
"e.g. Sides, Mains, Desserts, Drinks - # different for every",
"Again this isn't # efficient. menu_sections = menu_sections.append( {\"restaurant_id\": restaurant_id,",
"function processes the menu # This gets the restaurant_name by",
"the url deliveroo_name = re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # If this",
"# so that it is in pence. It is then",
"\"str\", \"type\": \"int32\"}) tag_type = pd.DataFrame({\"name\": []}) restaurants = pd.DataFrame({\"name\":",
"hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11' + '(KHTML,",
"menu_items data frame, # this is more efficient than doing",
"class tag for tag in doc.find_all(\"small\", class_=\"tag\"): # The second",
"Add the tag to a list of tags for that",
"\"price_in_pence\": \"int64\", \"is_popular\": \"bool\"}) restaurants_to_locs = pd.DataFrame({\"restaurant_id\": [], \"loc_id\": []})\\",
"restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx, index_label=\"id\") cnx.close() if __name__ == \"__main__\": postcodes_df =",
"before if deliveroo_name not in restaurants['deliveroo_name']: # Get the webpage",
"restaurants, restaurants_to_tags, menu_sections, menu_items, restaurants_to_locs) def process_restaurants_for_postcode(postcode, tags_df, tag_type, restaurants,",
"# If it's to a menu, get the restaurant and",
"an item is popular it has a <span> with the",
"frame postcodes_index = (postcodes['post_code'] == postcode).index[0] # Find the restaurants",
"before # Get the deliveroo name from the url deliveroo_name",
"re.findall( '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)', url)[0] # If this restaurant hasn't been seen",
"it nicely try: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) =",
"None # Add this menu_item to category_items category_items.append( {\"menu_section_id\": category_id,",
"handle it nicely try: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items)",
"nicely try: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) = process_menu(soup,",
"urllib.request.urlopen(request) soup = BeautifulSoup(page) # Try and process the menu,",
"postcodes_index = (postcodes['post_code'] == postcode).index[0] # Find the restaurants id",
"process the menu if \"/menu\" in destination: (tags_df, tag_type, restaurants,",
"with the CSS class # menu-index-page__item-popular # So this tries",
"the menu items in that category to the menu_items data",
"Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' + ';q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none',",
"web scraper hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11'",
"categories = doc.find_all(\"div\", class_=\"menu-index-page__menu-category\") for category in categories: # the",
"Create the dataframes tags_df = pd.DataFrame({\"name\": [], \"type\": []})\\ .astype({\"name\":",
"to db cnx = sqlite3.connect(db_name) postcodes.to_sql(\"POSTCODES\", cnx, index_label=\"id\") restaurants.to_sql(\"RESTAURANTS\", cnx,",
"See if the tagtype exists in the tag_type dataframe type_matches",
"the tags_df dataframe matches = tags_df[ (tags_df == [name, type_matches.index[0]]).all(axis=1)]",
"\\ menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\ .text[1:] price_as_float = float(price_as_text) item_price = int(price_as_float",
"request = urllib.request.Request(url, headers=hdr) # Get the page page =",
"menu_item in items_html: # The name is the <h6> with",
"# converted to a floating-point number (decimal), multiplied by 100",
"menu_items, restaurants_to_locs) def process_restaurants_for_postcode(postcode, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items,",
"if deliveroo_name not in restaurants['deliveroo_name']: # Get the webpage request",
"# menu-index-page__item-popular # So this tries to find it, if",
"page page = urllib.request.urlopen(request) soup = BeautifulSoup(page) # For every",
"tags with the CSS class # menu-index-page__menu-category categories = doc.find_all(\"div\",",
"return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) def get_restaurant_and_process_menu(url, tags_df,",
"says camden, it # will update as appropriate. url =",
"except Exception: print(f\"Fail on {url}\") # Get the postcode from",
"isn't very efficient restaurant_id = restaurants[ (restaurants == [restaurant_name, deliveroo_name]).all(",
"\"int64\", \"loc_id\": \"int64\"}) for post_code in postcodes['post_code']: (tags_df, tag_type, restaurants,",
"is_item_popular = menu_item.find( \"span\", class_=\"menu-index-page__item-popular\") is not None # Add",
"(tags_df == [name, type_matches.index[0]]).all(axis=1)] # If it doesn't if len(matches)",
"the webpage request = urllib.request.Request(url, headers=hdr) page = urllib.request.urlopen(request) soup",
"# This function processes the restaurants for the postcodes #",
"the postcode to the URL - it doesn't matter that",
"it doesn't matter that it says camden, it # will",
"in restaurants['deliveroo_name']: # Get the webpage request = urllib.request.Request(url, headers=hdr)",
"# Add this to restaurants_to_tags df restaurants_to_tags = restaurants_to_tags.append( {\"restaurant_id\":",
"tag['class'][1] # The name of the tag is what is",
"url, tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items): # This function",
"try: (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections, menu_items) = process_menu(soup, url,",
"The £ symbol is dropped, it is then # converted",
"{\"name\": restaurant_name, \"deliveroo_name\": deliveroo_name}, ignore_index=True) # This gets the restaurant_id",
"ignore_index=True) # For each category (in the menu, e.g. Sides,",
"restaurants, restaurants_to_tags, menu_sections, menu_items) except Exception: print(f\"Fail on {url}\") #",
"postcodes.to_sql(\"POSTCODES\", cnx, index_label=\"id\") restaurants.to_sql(\"RESTAURANTS\", cnx, index_label=\"id\") restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx, index_label=\"id\") menu_items.to_sql(\"MENU_ITEMS\","
] |
[] |
[
"in mins to query TTN Data: time_duration = 5 #",
"Initial Time Duration in mins to query TTN Data: time_duration",
"Email: <EMAIL> # Date: 19/01/2018 # Revision: version#1 # License:",
"duration in minutes querytime = str(time_duration) + 'm' params =",
"pd.DataFrame.from_dict(response) return df_raw def cleandf(df): ''' In this function we",
"in JSON format to clean and optimize the data. This",
"= df.drop(drop_cols, 1) df.reset_index() df = df.reindex(['TTNTimeStamp','Count'], axis=1) print(\"Latest Data:\")",
"Data and Automatically Storing it to a Google Spreadsheet #",
"df_raw = pd.DataFrame.from_dict(response) return df_raw def cleandf(df): ''' In this",
"query duration in minutes querytime = str(time_duration) + 'm' params",
"this function we pass as input the raw dataframe from",
"of Swagger API TimeStamps df['TTNTimeStamp'] = df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols = ['raw','device_id']",
"# Author: <NAME> # Email: <EMAIL> # Date: 19/01/2018 #",
"the raw dataframe from TTN in JSON format to clean",
"= pd.DataFrame.from_dict(response) return df_raw def cleandf(df): ''' In this function",
"customized and unique to every dataset ''' df.rename(columns={'time': 'TTNTimeStamp'}, inplace=True)",
"loop df_raw = queryttndata(time_duration) df_clean = cleandf(df_raw) d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True) #",
"df_clean = cleandf(df_raw) d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True) # Write dataframe to Google",
"Increment query duration by 1 mins at the end of",
"df['TTNTimeStamp'] + pd.Timedelta(hours=1) ## Offset Time by 1 hour to",
"## Set Initial Time Duration in mins to query TTN",
"df.reset_index() df = df.reindex(['TTNTimeStamp','Count'], axis=1) print(\"Latest Data:\") print(df.tail(1),'\\n') return df",
"pass as input the raw dataframe from TTN in JSON",
"%H:%M:%S\",index=True) # Save DataFrame locally time.sleep(60) # Call function every",
"to fix TimeZone Error of Swagger API TimeStamps df['TTNTimeStamp'] =",
"#### Reading Data from The Things Network Data and Automatically",
"Author: <NAME> # Email: <EMAIL> # Date: 19/01/2018 # Revision:",
"as an input ''' headers = {'Accept': 'application/json','Authorization': 'key <KEY>'}",
"optimize the data. This function is customized and unique to",
"duration by 1 mins at the end of every function",
"Storing it to a Google Spreadsheet # Author: <NAME> #",
"True: #begin your infinite loop df_raw = queryttndata(time_duration) df_clean =",
"from TTN in JSON format to clean and optimize the",
"The Things Network Data and Automatically Storing it to a",
"API based on a time duration which is given as",
"<EMAIL> # Date: 19/01/2018 # Revision: version#1 # License: MIT",
"while True: #begin your infinite loop df_raw = queryttndata(time_duration) df_clean",
"60 seconds time_duration += 1 ## Increment query duration by",
"Name wks_name = 'Sheet1' def queryttndata(time_duration): ''' This function queries",
"Time by 1 hour to fix TimeZone Error of Swagger",
"= queryttndata(time_duration) df_clean = cleandf(df_raw) d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True) # Write dataframe",
"as input the raw dataframe from TTN in JSON format",
"MIT License import pandas as pd import requests from df2gspread",
"queryttndata(time_duration) df_clean = cleandf(df_raw) d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True) # Write dataframe to",
"Write dataframe to Google Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv', date_format=\"%d/%m/%Y %H:%M:%S\",index=True) # Save",
"+ pd.Timedelta(hours=1) ## Offset Time by 1 hour to fix",
"df['TTNTimeStamp'] = df['TTNTimeStamp'] + pd.Timedelta(hours=1) ## Offset Time by 1",
"## Google SpreadSheet Title: TTN_Live_DataLogger # Insert Sheet Name wks_name",
"duration which is given as an input ''' headers =",
"time ## Set Initial Time Duration in mins to query",
"'application/json','Authorization': 'key <KEY>'} ## Set query duration in minutes querytime",
"Set query duration in minutes querytime = str(time_duration) + 'm'",
"every dataset ''' df.rename(columns={'time': 'TTNTimeStamp'}, inplace=True) df['TTNTimeStamp'] = pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp']",
"Save DataFrame locally time.sleep(60) # Call function every 60 seconds",
"+ 'm' params = (('last', querytime),) response = requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers,",
"df['TTNTimeStamp'] = df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols = ['raw','device_id'] df = df.drop(drop_cols, 1)",
"based on a time duration which is given as an",
"TimeZone Error of Swagger API TimeStamps df['TTNTimeStamp'] = df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols",
"querytime = str(time_duration) + 'm' params = (('last', querytime),) response",
"TTN Data: time_duration = 5 # Insert spreadsheet file id",
"input ''' headers = {'Accept': 'application/json','Authorization': 'key <KEY>'} ## Set",
"and Automatically Storing it to a Google Spreadsheet # Author:",
"a Google Spreadsheet # Author: <NAME> # Email: <EMAIL> #",
"## Set query duration in minutes querytime = str(time_duration) +",
"an input ''' headers = {'Accept': 'application/json','Authorization': 'key <KEY>'} ##",
"df.rename(columns={'time': 'TTNTimeStamp'}, inplace=True) df['TTNTimeStamp'] = pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp'] = df['TTNTimeStamp'] +",
"Swagger API TimeStamps df['TTNTimeStamp'] = df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols = ['raw','device_id'] df",
"19/01/2018 # Revision: version#1 # License: MIT License import pandas",
"Network Data and Automatically Storing it to a Google Spreadsheet",
"df_raw = queryttndata(time_duration) df_clean = cleandf(df_raw) d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True) # Write",
"'Sheet1' def queryttndata(time_duration): ''' This function queries data from TTN",
"JSON format to clean and optimize the data. This function",
"License: MIT License import pandas as pd import requests from",
"pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp'] = df['TTNTimeStamp'] + pd.Timedelta(hours=1) ## Offset Time by",
"params=params).json() df_raw = pd.DataFrame.from_dict(response) return df_raw def cleandf(df): ''' In",
"Spreadsheet spreadsheet = '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ## Google SpreadSheet Title: TTN_Live_DataLogger #",
"Automatically Storing it to a Google Spreadsheet # Author: <NAME>",
"df_clean.to_csv('TTN_VehicleCountData.csv', date_format=\"%d/%m/%Y %H:%M:%S\",index=True) # Save DataFrame locally time.sleep(60) # Call",
"<filename>DataWrangling/TTNData2Gsheet_Auto.py #### Reading Data from The Things Network Data and",
"= pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp'] = df['TTNTimeStamp'] + pd.Timedelta(hours=1) ## Offset Time",
"data. This function is customized and unique to every dataset",
"time.sleep(60) # Call function every 60 seconds time_duration += 1",
"cleandf(df): ''' In this function we pass as input the",
"given as an input ''' headers = {'Accept': 'application/json','Authorization': 'key",
"= df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols = ['raw','device_id'] df = df.drop(drop_cols, 1) df.reset_index()",
"This function queries data from TTN Swagger API based on",
"of Google Spreadsheet spreadsheet = '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ## Google SpreadSheet Title:",
"from df2gspread import df2gspread as d2g import time ## Set",
"pd.Timedelta(hours=1) ## Offset Time by 1 hour to fix TimeZone",
"pd import requests from df2gspread import df2gspread as d2g import",
"infinite loop df_raw = queryttndata(time_duration) df_clean = cleandf(df_raw) d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True)",
"Swagger API based on a time duration which is given",
"Sheet Name wks_name = 'Sheet1' def queryttndata(time_duration): ''' This function",
"function is customized and unique to every dataset ''' df.rename(columns={'time':",
"is customized and unique to every dataset ''' df.rename(columns={'time': 'TTNTimeStamp'},",
"Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv', date_format=\"%d/%m/%Y %H:%M:%S\",index=True) # Save DataFrame locally time.sleep(60) #",
"'1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ## Google SpreadSheet Title: TTN_Live_DataLogger # Insert Sheet Name",
"Google SpreadSheet Title: TTN_Live_DataLogger # Insert Sheet Name wks_name =",
"date_format=\"%d/%m/%Y %H:%M:%S\",index=True) # Save DataFrame locally time.sleep(60) # Call function",
"Set Initial Time Duration in mins to query TTN Data:",
"it to a Google Spreadsheet # Author: <NAME> # Email:",
"querytime),) response = requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers, params=params).json() df_raw = pd.DataFrame.from_dict(response) return",
"API TimeStamps df['TTNTimeStamp'] = df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols = ['raw','device_id'] df =",
"1 ## Increment query duration by 1 mins at the",
"function every 60 seconds time_duration += 1 ## Increment query",
"as pd import requests from df2gspread import df2gspread as d2g",
"1 hour to fix TimeZone Error of Swagger API TimeStamps",
"Things Network Data and Automatically Storing it to a Google",
"spreadsheet file id of Google Spreadsheet spreadsheet = '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ##",
"This function is customized and unique to every dataset '''",
"and unique to every dataset ''' df.rename(columns={'time': 'TTNTimeStamp'}, inplace=True) df['TTNTimeStamp']",
"version#1 # License: MIT License import pandas as pd import",
"Offset Time by 1 hour to fix TimeZone Error of",
"= str(time_duration) + 'm' params = (('last', querytime),) response =",
"df.reindex(['TTNTimeStamp','Count'], axis=1) print(\"Latest Data:\") print(df.tail(1),'\\n') return df while True: #begin",
"on a time duration which is given as an input",
"inplace=True) df['TTNTimeStamp'] = pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp'] = df['TTNTimeStamp'] + pd.Timedelta(hours=1) ##",
"TTN Swagger API based on a time duration which is",
"Call function every 60 seconds time_duration += 1 ## Increment",
"queryttndata(time_duration): ''' This function queries data from TTN Swagger API",
"from The Things Network Data and Automatically Storing it to",
"# Write dataframe to Google Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv', date_format=\"%d/%m/%Y %H:%M:%S\",index=True) #",
"pandas as pd import requests from df2gspread import df2gspread as",
"query TTN Data: time_duration = 5 # Insert spreadsheet file",
"from TTN Swagger API based on a time duration which",
"in minutes querytime = str(time_duration) + 'm' params = (('last',",
"import df2gspread as d2g import time ## Set Initial Time",
"Title: TTN_Live_DataLogger # Insert Sheet Name wks_name = 'Sheet1' def",
"df = df.reindex(['TTNTimeStamp','Count'], axis=1) print(\"Latest Data:\") print(df.tail(1),'\\n') return df while",
"d2g import time ## Set Initial Time Duration in mins",
"DataFrame locally time.sleep(60) # Call function every 60 seconds time_duration",
"input the raw dataframe from TTN in JSON format to",
"to clean and optimize the data. This function is customized",
"<KEY>'} ## Set query duration in minutes querytime = str(time_duration)",
"Date: 19/01/2018 # Revision: version#1 # License: MIT License import",
"fix TimeZone Error of Swagger API TimeStamps df['TTNTimeStamp'] = df['TTNTimeStamp'].values.astype('datetime64[s]')",
"function we pass as input the raw dataframe from TTN",
"Insert spreadsheet file id of Google Spreadsheet spreadsheet = '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o'",
"df_raw def cleandf(df): ''' In this function we pass as",
"''' df.rename(columns={'time': 'TTNTimeStamp'}, inplace=True) df['TTNTimeStamp'] = pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp'] = df['TTNTimeStamp']",
"## Increment query duration by 1 mins at the end",
"1) df.reset_index() df = df.reindex(['TTNTimeStamp','Count'], axis=1) print(\"Latest Data:\") print(df.tail(1),'\\n') return",
"## Offset Time by 1 hour to fix TimeZone Error",
"TTN in JSON format to clean and optimize the data.",
"unique to every dataset ''' df.rename(columns={'time': 'TTNTimeStamp'}, inplace=True) df['TTNTimeStamp'] =",
"time_duration += 1 ## Increment query duration by 1 mins",
"df2gspread import df2gspread as d2g import time ## Set Initial",
"dataset ''' df.rename(columns={'time': 'TTNTimeStamp'}, inplace=True) df['TTNTimeStamp'] = pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp'] =",
"requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers, params=params).json() df_raw = pd.DataFrame.from_dict(response) return df_raw def cleandf(df):",
"Google Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv', date_format=\"%d/%m/%Y %H:%M:%S\",index=True) # Save DataFrame locally time.sleep(60)",
"= 'Sheet1' def queryttndata(time_duration): ''' This function queries data from",
"str(time_duration) + 'm' params = (('last', querytime),) response = requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query',",
"id of Google Spreadsheet spreadsheet = '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ## Google SpreadSheet",
"cleandf(df_raw) d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True) # Write dataframe to Google Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv',",
"and optimize the data. This function is customized and unique",
"function queries data from TTN Swagger API based on a",
"queries data from TTN Swagger API based on a time",
"the data. This function is customized and unique to every",
"df.drop(drop_cols, 1) df.reset_index() df = df.reindex(['TTNTimeStamp','Count'], axis=1) print(\"Latest Data:\") print(df.tail(1),'\\n')",
"df2gspread as d2g import time ## Set Initial Time Duration",
"import time ## Set Initial Time Duration in mins to",
"to a Google Spreadsheet # Author: <NAME> # Email: <EMAIL>",
"which is given as an input ''' headers = {'Accept':",
"response = requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers, params=params).json() df_raw = pd.DataFrame.from_dict(response) return df_raw",
"= df['TTNTimeStamp'] + pd.Timedelta(hours=1) ## Offset Time by 1 hour",
"headers = {'Accept': 'application/json','Authorization': 'key <KEY>'} ## Set query duration",
"Reading Data from The Things Network Data and Automatically Storing",
"d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True) # Write dataframe to Google Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv', date_format=\"%d/%m/%Y",
"# Email: <EMAIL> # Date: 19/01/2018 # Revision: version#1 #",
"SpreadSheet Title: TTN_Live_DataLogger # Insert Sheet Name wks_name = 'Sheet1'",
"Revision: version#1 # License: MIT License import pandas as pd",
"a time duration which is given as an input '''",
"= {'Accept': 'application/json','Authorization': 'key <KEY>'} ## Set query duration in",
"''' In this function we pass as input the raw",
"#begin your infinite loop df_raw = queryttndata(time_duration) df_clean = cleandf(df_raw)",
"def cleandf(df): ''' In this function we pass as input",
"Error of Swagger API TimeStamps df['TTNTimeStamp'] = df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols =",
"seconds time_duration += 1 ## Increment query duration by 1",
"format to clean and optimize the data. This function is",
"Spreadsheet # Author: <NAME> # Email: <EMAIL> # Date: 19/01/2018",
"'key <KEY>'} ## Set query duration in minutes querytime =",
"to Google Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv', date_format=\"%d/%m/%Y %H:%M:%S\",index=True) # Save DataFrame locally",
"''' This function queries data from TTN Swagger API based",
"raw dataframe from TTN in JSON format to clean and",
"import pandas as pd import requests from df2gspread import df2gspread",
"License import pandas as pd import requests from df2gspread import",
"requests from df2gspread import df2gspread as d2g import time ##",
"spreadsheet = '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ## Google SpreadSheet Title: TTN_Live_DataLogger # Insert",
"= df.reindex(['TTNTimeStamp','Count'], axis=1) print(\"Latest Data:\") print(df.tail(1),'\\n') return df while True:",
"time duration which is given as an input ''' headers",
"is given as an input ''' headers = {'Accept': 'application/json','Authorization':",
"we pass as input the raw dataframe from TTN in",
"# Insert spreadsheet file id of Google Spreadsheet spreadsheet =",
"dataframe from TTN in JSON format to clean and optimize",
"hour to fix TimeZone Error of Swagger API TimeStamps df['TTNTimeStamp']",
"print(df.tail(1),'\\n') return df while True: #begin your infinite loop df_raw",
"# Save DataFrame locally time.sleep(60) # Call function every 60",
"df = df.drop(drop_cols, 1) df.reset_index() df = df.reindex(['TTNTimeStamp','Count'], axis=1) print(\"Latest",
"# Date: 19/01/2018 # Revision: version#1 # License: MIT License",
"axis=1) print(\"Latest Data:\") print(df.tail(1),'\\n') return df while True: #begin your",
"locally time.sleep(60) # Call function every 60 seconds time_duration +=",
"headers=headers, params=params).json() df_raw = pd.DataFrame.from_dict(response) return df_raw def cleandf(df): '''",
"every 60 seconds time_duration += 1 ## Increment query duration",
"def queryttndata(time_duration): ''' This function queries data from TTN Swagger",
"return df while True: #begin your infinite loop df_raw =",
"+= 1 ## Increment query duration by 1 mins at",
"df['TTNTimeStamp'] = pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp'] = df['TTNTimeStamp'] + pd.Timedelta(hours=1) ## Offset",
"by 1 hour to fix TimeZone Error of Swagger API",
"minutes querytime = str(time_duration) + 'm' params = (('last', querytime),)",
"your infinite loop df_raw = queryttndata(time_duration) df_clean = cleandf(df_raw) d2g.upload(df_clean,",
"# Revision: version#1 # License: MIT License import pandas as",
"'m' params = (('last', querytime),) response = requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers, params=params).json()",
"= '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ## Google SpreadSheet Title: TTN_Live_DataLogger # Insert Sheet",
"{'Accept': 'application/json','Authorization': 'key <KEY>'} ## Set query duration in minutes",
"''' headers = {'Accept': 'application/json','Authorization': 'key <KEY>'} ## Set query",
"TimeStamps df['TTNTimeStamp'] = df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols = ['raw','device_id'] df = df.drop(drop_cols,",
"Duration in mins to query TTN Data: time_duration = 5",
"TTN_Live_DataLogger # Insert Sheet Name wks_name = 'Sheet1' def queryttndata(time_duration):",
"import requests from df2gspread import df2gspread as d2g import time",
"return df_raw def cleandf(df): ''' In this function we pass",
"df while True: #begin your infinite loop df_raw = queryttndata(time_duration)",
"data from TTN Swagger API based on a time duration",
"= cleandf(df_raw) d2g.upload(df_clean, spreadsheet,wks_name,col_names=True,clean=True) # Write dataframe to Google Spreadsheet",
"query duration by 1 mins at the end of every",
"as d2g import time ## Set Initial Time Duration in",
"'TTNTimeStamp'}, inplace=True) df['TTNTimeStamp'] = pd.to_datetime(df['TTNTimeStamp']) df['TTNTimeStamp'] = df['TTNTimeStamp'] + pd.Timedelta(hours=1)",
"= requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers, params=params).json() df_raw = pd.DataFrame.from_dict(response) return df_raw def",
"time_duration = 5 # Insert spreadsheet file id of Google",
"(('last', querytime),) response = requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers, params=params).json() df_raw = pd.DataFrame.from_dict(response)",
"spreadsheet,wks_name,col_names=True,clean=True) # Write dataframe to Google Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv', date_format=\"%d/%m/%Y %H:%M:%S\",index=True)",
"Data: time_duration = 5 # Insert spreadsheet file id of",
"wks_name = 'Sheet1' def queryttndata(time_duration): ''' This function queries data",
"clean and optimize the data. This function is customized and",
"# Insert Sheet Name wks_name = 'Sheet1' def queryttndata(time_duration): '''",
"print(\"Latest Data:\") print(df.tail(1),'\\n') return df while True: #begin your infinite",
"Data from The Things Network Data and Automatically Storing it",
"drop_cols = ['raw','device_id'] df = df.drop(drop_cols, 1) df.reset_index() df =",
"= 5 # Insert spreadsheet file id of Google Spreadsheet",
"Data:\") print(df.tail(1),'\\n') return df while True: #begin your infinite loop",
"Google Spreadsheet spreadsheet = '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ## Google SpreadSheet Title: TTN_Live_DataLogger",
"Insert Sheet Name wks_name = 'Sheet1' def queryttndata(time_duration): ''' This",
"In this function we pass as input the raw dataframe",
"by 1 mins at the end of every function call",
"# License: MIT License import pandas as pd import requests",
"5 # Insert spreadsheet file id of Google Spreadsheet spreadsheet",
"= (('last', querytime),) response = requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers, params=params).json() df_raw =",
"to every dataset ''' df.rename(columns={'time': 'TTNTimeStamp'}, inplace=True) df['TTNTimeStamp'] = pd.to_datetime(df['TTNTimeStamp'])",
"# Call function every 60 seconds time_duration += 1 ##",
"file id of Google Spreadsheet spreadsheet = '1ftXlebCTDp5tTxvlm5K3Sv1oNttDHR7s1xTi-i-ZR_o' ## Google",
"<NAME> # Email: <EMAIL> # Date: 19/01/2018 # Revision: version#1",
"dataframe to Google Spreadsheet df_clean.to_csv('TTN_VehicleCountData.csv', date_format=\"%d/%m/%Y %H:%M:%S\",index=True) # Save DataFrame",
"Time Duration in mins to query TTN Data: time_duration =",
"to query TTN Data: time_duration = 5 # Insert spreadsheet",
"= ['raw','device_id'] df = df.drop(drop_cols, 1) df.reset_index() df = df.reindex(['TTNTimeStamp','Count'],",
"Google Spreadsheet # Author: <NAME> # Email: <EMAIL> # Date:",
"df['TTNTimeStamp'].values.astype('datetime64[s]') drop_cols = ['raw','device_id'] df = df.drop(drop_cols, 1) df.reset_index() df",
"mins to query TTN Data: time_duration = 5 # Insert",
"params = (('last', querytime),) response = requests.get('https://vehiclecounter.data.thethingsnetwork.org/api/v2/query', headers=headers, params=params).json() df_raw",
"['raw','device_id'] df = df.drop(drop_cols, 1) df.reset_index() df = df.reindex(['TTNTimeStamp','Count'], axis=1)"
] |
[
"ReactiveProperty(self.init_value, self.read_only, self.modifier, validate) class PropertyData(ReactiveValue.Data[T]): def __init__( self, name:",
"Mypy fails to resolve pipeline.pipe(). Should investigate later. # noinspection",
"identity from returns.maybe import Maybe, Nothing from rx import Observable",
". import ReactiveValue, ReactiveView from .value import Modifier T =",
"validator(obj, self.validator(obj, v)) return ReactiveProperty(self.init_value, self.read_only, self.modifier, validate) class PropertyData(ReactiveValue.Data[T]):",
"ReactiveProperty[T]: if validator is None: raise ValueError(\"Argument 'modifier' is required.\")",
"# FIXME: Not sure why both PyCharm and Mypy fails",
"returns.maybe import Maybe, Nothing from rx import Observable from rx.subject",
".value import Modifier T = TypeVar(\"T\") class ReactiveProperty(Generic[T], ReactiveValue[T]): def",
"obs = self._property else: obs = rx.empty() super().__init__(name, obs, modifier)",
"not None self._check_disposed() self._property.on_completed() super().dispose() def _create_data(self, obj: Any) ->",
"BehaviorSubject(init_value.map(validator).unwrap()) obs = self._property else: obs = rx.empty() super().__init__(name, obs,",
"is not None def validate(v: T) -> T: return self.validator(obj,",
"None assert validator is not None self._validator = validator self._property:",
"self.PropertyData(self.name, self.init_value, self.modifier(obj), validate) def _get_data(self, obj: Any) -> PropertyData:",
"Tuple import rx from returns import pipeline from returns.functions import",
"import annotations from typing import TypeVar, Generic, Callable, Optional, Any,",
"None self._check_disposed() self._property.on_completed() super().dispose() def _create_data(self, obj: Any) -> PropertyData:",
"def __init__( self, name: str, init_value: Maybe[T], modifier: Modifier, validator:",
"stack(obj: Any): # FIXME: Not sure why both PyCharm and",
"init_value self._modifier = modifier self._validator = validator @property def init_value(self)",
"Observable if init_value != Nothing: self._property = BehaviorSubject(init_value.map(validator).unwrap()) obs =",
"self._init_value = init_value self._modifier = modifier self._validator = validator @property",
"Nothing from rx import Observable from rx.subject import BehaviorSubject from",
"Maybe[T], modifier: Modifier, validator: Callable[[T], T]): assert name is not",
"is required.\") def validate(obj: Any, v: T) -> T: return",
"obj: Any) -> PropertyData: assert obj is not None return",
"self._property: Optional[BehaviorSubject] = None obs: Observable if init_value != Nothing:",
"validator: Callable[[Any, T], T] = lambda _, v: v) ->",
"T: return self.validator(obj, v) return self.PropertyData(self.name, self.init_value, self.modifier(obj), validate) def",
"self._property is not None self._property.on_next(self.validator(value)) else: self._property = BehaviorSubject(self.validator(value)) self.observable",
"is not None self._property.on_next(self.validator(value)) else: self._property = BehaviorSubject(self.validator(value)) self.observable =",
"_get_data(self, obj: Any) -> PropertyData: assert obj is not None",
"@property def validator(self) -> Callable[[T, Any], T]: return self._validator @property",
"is not None assert self.name is not None def validate(v:",
"not None return cast(ReactiveProperty.PropertyData, super()._get_data(obj)) def _set_value(self, obj: Any, data:",
"def validate(obj: Any, v: T) -> T: return validator(obj, self.validator(obj,",
"-> None: assert obj is not None assert isinstance(data, ReactiveProperty.PropertyData)",
"noinspection PyUnresolvedReferences return pipeline.pipe(*([self.modifier(obj)] + list(modifiers(obj)))) # type:ignore return ReactiveProperty(self.init_value,",
"from . import ReactiveValue, ReactiveView from .value import Modifier T",
"def validate(v: T) -> T: return self.validator(obj, v) return self.PropertyData(self.name,",
"rx import Observable from rx.subject import BehaviorSubject from . import",
"return validator(obj, self.validator(obj, v)) return ReactiveProperty(self.init_value, self.read_only, self.modifier, validate) class",
"v)) return ReactiveProperty(self.init_value, self.read_only, self.modifier, validate) class PropertyData(ReactiveValue.Data[T]): def __init__(",
"!= Nothing: self._property = BehaviorSubject(init_value.map(validator).unwrap()) obs = self._property else: obs",
"T] = lambda _, v: v) -> None: super().__init__(read_only) self._init_value",
"init_value != Nothing: self._property = BehaviorSubject(init_value.map(validator).unwrap()) obs = self._property else:",
"not None assert self.name is not None def validate(v: T)",
"pipe(self, modifiers: Callable[[Any], Tuple[Modifier, ...]]) -> ReactiveProperty: def stack(obj: Any):",
"return ReactiveView(self.context, self.read_only) def pipe(self, modifiers: Callable[[Any], Tuple[Modifier, ...]]) ->",
"super()._get_data(obj)) def _set_value(self, obj: Any, data: ReactiveValue.Data, value: Any) ->",
"Maybe[T]: return self._init_value @property def validator(self) -> Callable[[T, Any], T]:",
"Any, cast, Tuple import rx from returns import pipeline from",
"self._check_disposed() if self.initialized: assert self._property is not None self._property.on_next(self.validator(value)) else:",
"# Must override to appease Mypy... I hate Python. @property",
"pipeline.pipe(). Should investigate later. # noinspection PyUnresolvedReferences return pipeline.pipe(*([self.modifier(obj)] +",
"assert name is not None assert init_value is not None",
"self._property @property def validator(self) -> Callable[[T], T]: return self._validator def",
"validate(v: T) -> T: return self.validator(obj, v) return self.PropertyData(self.name, self.init_value,",
"else: self._property = BehaviorSubject(self.validator(value)) self.observable = self._property @property def validator(self)",
"self._check_disposed() self._property.on_completed() super().dispose() def _create_data(self, obj: Any) -> PropertyData: assert",
"assert self._property is not None self._check_disposed() self._property.on_completed() super().dispose() def _create_data(self,",
"Any, data: ReactiveValue.Data, value: Any) -> None: assert obj is",
"class ReactiveProperty(Generic[T], ReactiveValue[T]): def __init__( self, init_value: Maybe[T] = Nothing,",
"__init__( self, name: str, init_value: Maybe[T], modifier: Modifier, validator: Callable[[T],",
"self._property = BehaviorSubject(self.validator(value)) self.observable = self._property @property def validator(self) ->",
"def dispose(self) -> None: assert self._property is not None self._check_disposed()",
"raise ValueError(\"Argument 'modifier' is required.\") def validate(obj: Any, v: T)",
"if validator is None: raise ValueError(\"Argument 'modifier' is required.\") def",
"-> PropertyData: assert obj is not None assert self.name is",
"def modifier(self) -> Callable[[Any], Modifier]: return self._modifier def as_view(self) ->",
"modifier: Callable[[Any], Modifier] = lambda _: identity, validator: Callable[[Any, T],",
"# type:ignore return ReactiveProperty(self.init_value, self.read_only, stack, self.validator) def validate(self, validator:",
"import TypeVar, Generic, Callable, Optional, Any, cast, Tuple import rx",
"import pipeline from returns.functions import identity from returns.maybe import Maybe,",
"data: ReactiveValue.Data, value: Any) -> None: assert obj is not",
"as_view(self) -> ReactiveView[T]: return ReactiveView(self.context, self.read_only) def pipe(self, modifiers: Callable[[Any],",
"validate) def _get_data(self, obj: Any) -> PropertyData: assert obj is",
"name is not None assert init_value is not None assert",
"type:ignore return ReactiveProperty(self.init_value, self.read_only, stack, self.validator) def validate(self, validator: Callable[[Any,",
"to resolve pipeline.pipe(). Should investigate later. # noinspection PyUnresolvedReferences return",
"Maybe, Nothing from rx import Observable from rx.subject import BehaviorSubject",
"init_value: Maybe[T], modifier: Modifier, validator: Callable[[T], T]): assert name is",
"assert obj is not None assert self.name is not None",
"return cast(ReactiveProperty.PropertyData, super()._get_data(obj)) def _set_value(self, obj: Any, data: ReactiveValue.Data, value:",
"pipeline from returns.functions import identity from returns.maybe import Maybe, Nothing",
"hate Python. @property def value(self) -> T: return super().value @value.setter",
"Callable[[Any, T], T] = lambda _, v: v) -> None:",
"T]: return self._validator def dispose(self) -> None: assert self._property is",
"...]]) -> ReactiveProperty: def stack(obj: Any): # FIXME: Not sure",
"T]): assert name is not None assert init_value is not",
"Not sure why both PyCharm and Mypy fails to resolve",
"assert obj is not None assert isinstance(data, ReactiveProperty.PropertyData) data.value =",
"None assert init_value is not None assert modifier is not",
"import rx from returns import pipeline from returns.functions import identity",
"return pipeline.pipe(*([self.modifier(obj)] + list(modifiers(obj)))) # type:ignore return ReactiveProperty(self.init_value, self.read_only, stack,",
"str, init_value: Maybe[T], modifier: Modifier, validator: Callable[[T], T]): assert name",
"value(self, value: T): self._check_disposed() if self.initialized: assert self._property is not",
"super().dispose() def _create_data(self, obj: Any) -> PropertyData: assert obj is",
"is not None assert modifier is not None assert validator",
"T], T]) -> ReactiveProperty[T]: if validator is None: raise ValueError(\"Argument",
"def _set_value(self, obj: Any, data: ReactiveValue.Data, value: Any) -> None:",
"read_only=False, modifier: Callable[[Any], Modifier] = lambda _: identity, validator: Callable[[Any,",
"None: assert self._property is not None self._check_disposed() self._property.on_completed() super().dispose() def",
"def __init__( self, init_value: Maybe[T] = Nothing, read_only=False, modifier: Callable[[Any],",
"value(self) -> T: return super().value @value.setter def value(self, value: T):",
"not None assert modifier is not None assert validator is",
"self.validator(obj, v)) return ReactiveProperty(self.init_value, self.read_only, self.modifier, validate) class PropertyData(ReactiveValue.Data[T]): def",
"validate(self, validator: Callable[[Any, T], T]) -> ReactiveProperty[T]: if validator is",
"Callable[[Any, T], T]) -> ReactiveProperty[T]: if validator is None: raise",
"None assert modifier is not None assert validator is not",
"T) -> T: return self.validator(obj, v) return self.PropertyData(self.name, self.init_value, self.modifier(obj),",
"= modifier self._validator = validator @property def init_value(self) -> Maybe[T]:",
"returns.functions import identity from returns.maybe import Maybe, Nothing from rx",
"override to appease Mypy... I hate Python. @property def value(self)",
"to appease Mypy... I hate Python. @property def value(self) ->",
"= TypeVar(\"T\") class ReactiveProperty(Generic[T], ReactiveValue[T]): def __init__( self, init_value: Maybe[T]",
"Any): # FIXME: Not sure why both PyCharm and Mypy",
"v) return self.PropertyData(self.name, self.init_value, self.modifier(obj), validate) def _get_data(self, obj: Any)",
"-> ReactiveView[T]: return ReactiveView(self.context, self.read_only) def pipe(self, modifiers: Callable[[Any], Tuple[Modifier,",
"modifier: Modifier, validator: Callable[[T], T]): assert name is not None",
"-> T: return super().value @value.setter def value(self, value: T): self._check_disposed()",
"modifier(self) -> Callable[[Any], Modifier]: return self._modifier def as_view(self) -> ReactiveView[T]:",
"Modifier T = TypeVar(\"T\") class ReactiveProperty(Generic[T], ReactiveValue[T]): def __init__( self,",
"from returns import pipeline from returns.functions import identity from returns.maybe",
"Must override to appease Mypy... I hate Python. @property def",
"ReactiveProperty(self.init_value, self.read_only, stack, self.validator) def validate(self, validator: Callable[[Any, T], T])",
"ValueError(\"Argument 'modifier' is required.\") def validate(obj: Any, v: T) ->",
"is not None assert init_value is not None assert modifier",
"return self._validator def dispose(self) -> None: assert self._property is not",
"_create_data(self, obj: Any) -> PropertyData: assert obj is not None",
"name: str, init_value: Maybe[T], modifier: Modifier, validator: Callable[[T], T]): assert",
"if self.initialized: assert self._property is not None self._property.on_next(self.validator(value)) else: self._property",
"@property def validator(self) -> Callable[[T], T]: return self._validator def dispose(self)",
"None self._validator = validator self._property: Optional[BehaviorSubject] = None obs: Observable",
"rx from returns import pipeline from returns.functions import identity from",
"import Modifier T = TypeVar(\"T\") class ReactiveProperty(Generic[T], ReactiveValue[T]): def __init__(",
"identity, validator: Callable[[Any, T], T] = lambda _, v: v)",
"Any) -> None: assert obj is not None assert isinstance(data,",
"= Nothing, read_only=False, modifier: Callable[[Any], Modifier] = lambda _: identity,",
"return self._modifier def as_view(self) -> ReactiveView[T]: return ReactiveView(self.context, self.read_only) def",
"ReactiveProperty(Generic[T], ReactiveValue[T]): def __init__( self, init_value: Maybe[T] = Nothing, read_only=False,",
"PropertyData(ReactiveValue.Data[T]): def __init__( self, name: str, init_value: Maybe[T], modifier: Modifier,",
"-> ReactiveProperty: def stack(obj: Any): # FIXME: Not sure why",
"T: return super().value @value.setter def value(self, value: T): self._check_disposed() if",
"self._property is not None self._check_disposed() self._property.on_completed() super().dispose() def _create_data(self, obj:",
"init_value: Maybe[T] = Nothing, read_only=False, modifier: Callable[[Any], Modifier] = lambda",
"cast, Tuple import rx from returns import pipeline from returns.functions",
"Mypy... I hate Python. @property def value(self) -> T: return",
"None self._property.on_next(self.validator(value)) else: self._property = BehaviorSubject(self.validator(value)) self.observable = self._property @property",
"self._property.on_next(self.validator(value)) else: self._property = BehaviorSubject(self.validator(value)) self.observable = self._property @property def",
"@property def init_value(self) -> Maybe[T]: return self._init_value @property def validator(self)",
"lambda _, v: v) -> None: super().__init__(read_only) self._init_value = init_value",
"import identity from returns.maybe import Maybe, Nothing from rx import",
"self._validator = validator self._property: Optional[BehaviorSubject] = None obs: Observable if",
"-> None: assert self._property is not None self._check_disposed() self._property.on_completed() super().dispose()",
"Callable[[Any], Modifier]: return self._modifier def as_view(self) -> ReactiveView[T]: return ReactiveView(self.context,",
"if init_value != Nothing: self._property = BehaviorSubject(init_value.map(validator).unwrap()) obs = self._property",
"obj is not None assert isinstance(data, ReactiveProperty.PropertyData) data.value = value",
"init_value is not None assert modifier is not None assert",
"def stack(obj: Any): # FIXME: Not sure why both PyCharm",
"import BehaviorSubject from . import ReactiveValue, ReactiveView from .value import",
"self.observable = self._property @property def validator(self) -> Callable[[T], T]: return",
"v: v) -> None: super().__init__(read_only) self._init_value = init_value self._modifier =",
"Modifier]: return self._modifier def as_view(self) -> ReactiveView[T]: return ReactiveView(self.context, self.read_only)",
"'modifier' is required.\") def validate(obj: Any, v: T) -> T:",
"self._property = BehaviorSubject(init_value.map(validator).unwrap()) obs = self._property else: obs = rx.empty()",
"= None obs: Observable if init_value != Nothing: self._property =",
"-> T: return self.validator(obj, v) return self.PropertyData(self.name, self.init_value, self.modifier(obj), validate)",
"= rx.empty() super().__init__(name, obs, modifier) # Must override to appease",
"from __future__ import annotations from typing import TypeVar, Generic, Callable,",
"self.read_only, self.modifier, validate) class PropertyData(ReactiveValue.Data[T]): def __init__( self, name: str,",
"def init_value(self) -> Maybe[T]: return self._init_value @property def validator(self) ->",
"def as_view(self) -> ReactiveView[T]: return ReactiveView(self.context, self.read_only) def pipe(self, modifiers:",
"assert obj is not None return cast(ReactiveProperty.PropertyData, super()._get_data(obj)) def _set_value(self,",
"Maybe[T] = Nothing, read_only=False, modifier: Callable[[Any], Modifier] = lambda _:",
"assert self.name is not None def validate(v: T) -> T:",
"self, init_value: Maybe[T] = Nothing, read_only=False, modifier: Callable[[Any], Modifier] =",
"super().__init__(read_only) self._init_value = init_value self._modifier = modifier self._validator = validator",
"modifier self._validator = validator @property def init_value(self) -> Maybe[T]: return",
"not None assert init_value is not None assert modifier is",
"= BehaviorSubject(init_value.map(validator).unwrap()) obs = self._property else: obs = rx.empty() super().__init__(name,",
"return self.validator(obj, v) return self.PropertyData(self.name, self.init_value, self.modifier(obj), validate) def _get_data(self,",
"validator: Callable[[Any, T], T]) -> ReactiveProperty[T]: if validator is None:",
"@value.setter def value(self, value: T): self._check_disposed() if self.initialized: assert self._property",
"returns import pipeline from returns.functions import identity from returns.maybe import",
"def validate(self, validator: Callable[[Any, T], T]) -> ReactiveProperty[T]: if validator",
"rx.empty() super().__init__(name, obs, modifier) # Must override to appease Mypy...",
"None assert self.name is not None def validate(v: T) ->",
"modifiers: Callable[[Any], Tuple[Modifier, ...]]) -> ReactiveProperty: def stack(obj: Any): #",
"self._validator = validator @property def init_value(self) -> Maybe[T]: return self._init_value",
"T): self._check_disposed() if self.initialized: assert self._property is not None self._property.on_next(self.validator(value))",
"validator: Callable[[T], T]): assert name is not None assert init_value",
"is not None self._validator = validator self._property: Optional[BehaviorSubject] = None",
"Python. @property def value(self) -> T: return super().value @value.setter def",
"Observable from rx.subject import BehaviorSubject from . import ReactiveValue, ReactiveView",
"Modifier, validator: Callable[[T], T]): assert name is not None assert",
"assert self._property is not None self._property.on_next(self.validator(value)) else: self._property = BehaviorSubject(self.validator(value))",
"rx.subject import BehaviorSubject from . import ReactiveValue, ReactiveView from .value",
"Nothing, read_only=False, modifier: Callable[[Any], Modifier] = lambda _: identity, validator:",
"lambda _: identity, validator: Callable[[Any, T], T] = lambda _,",
"= BehaviorSubject(self.validator(value)) self.observable = self._property @property def validator(self) -> Callable[[T],",
"import Observable from rx.subject import BehaviorSubject from . import ReactiveValue,",
"ReactiveView[T]: return ReactiveView(self.context, self.read_only) def pipe(self, modifiers: Callable[[Any], Tuple[Modifier, ...]])",
"Optional[BehaviorSubject] = None obs: Observable if init_value != Nothing: self._property",
"required.\") def validate(obj: Any, v: T) -> T: return validator(obj,",
"import Maybe, Nothing from rx import Observable from rx.subject import",
"T], T] = lambda _, v: v) -> None: super().__init__(read_only)",
"Should investigate later. # noinspection PyUnresolvedReferences return pipeline.pipe(*([self.modifier(obj)] + list(modifiers(obj))))",
"self.modifier, validate) class PropertyData(ReactiveValue.Data[T]): def __init__( self, name: str, init_value:",
"self.init_value, self.modifier(obj), validate) def _get_data(self, obj: Any) -> PropertyData: assert",
"is not None return cast(ReactiveProperty.PropertyData, super()._get_data(obj)) def _set_value(self, obj: Any,",
"Optional, Any, cast, Tuple import rx from returns import pipeline",
"from returns.functions import identity from returns.maybe import Maybe, Nothing from",
"BehaviorSubject(self.validator(value)) self.observable = self._property @property def validator(self) -> Callable[[T], T]:",
"self._validator @property def modifier(self) -> Callable[[Any], Modifier]: return self._modifier def",
"Callable[[T], T]: return self._validator def dispose(self) -> None: assert self._property",
"BehaviorSubject from . import ReactiveValue, ReactiveView from .value import Modifier",
"self.modifier(obj), validate) def _get_data(self, obj: Any) -> PropertyData: assert obj",
"validate(obj: Any, v: T) -> T: return validator(obj, self.validator(obj, v))",
"validator(self) -> Callable[[T], T]: return self._validator def dispose(self) -> None:",
"assert modifier is not None assert validator is not None",
"obj: Any) -> PropertyData: assert obj is not None assert",
"None obs: Observable if init_value != Nothing: self._property = BehaviorSubject(init_value.map(validator).unwrap())",
"obj is not None return cast(ReactiveProperty.PropertyData, super()._get_data(obj)) def _set_value(self, obj:",
"= lambda _: identity, validator: Callable[[Any, T], T] = lambda",
"None return cast(ReactiveProperty.PropertyData, super()._get_data(obj)) def _set_value(self, obj: Any, data: ReactiveValue.Data,",
"validator @property def init_value(self) -> Maybe[T]: return self._init_value @property def",
"value: T): self._check_disposed() if self.initialized: assert self._property is not None",
"from returns.maybe import Maybe, Nothing from rx import Observable from",
"None: super().__init__(read_only) self._init_value = init_value self._modifier = modifier self._validator =",
"T = TypeVar(\"T\") class ReactiveProperty(Generic[T], ReactiveValue[T]): def __init__( self, init_value:",
"is not None self._check_disposed() self._property.on_completed() super().dispose() def _create_data(self, obj: Any)",
"value: Any) -> None: assert obj is not None assert",
"= validator @property def init_value(self) -> Maybe[T]: return self._init_value @property",
"obs, modifier) # Must override to appease Mypy... I hate",
"return self.PropertyData(self.name, self.init_value, self.modifier(obj), validate) def _get_data(self, obj: Any) ->",
"ReactiveValue.Data, value: Any) -> None: assert obj is not None",
"= validator self._property: Optional[BehaviorSubject] = None obs: Observable if init_value",
"PyUnresolvedReferences return pipeline.pipe(*([self.modifier(obj)] + list(modifiers(obj)))) # type:ignore return ReactiveProperty(self.init_value, self.read_only,",
"not None assert validator is not None self._validator = validator",
"list(modifiers(obj)))) # type:ignore return ReactiveProperty(self.init_value, self.read_only, stack, self.validator) def validate(self,",
"assert validator is not None self._validator = validator self._property: Optional[BehaviorSubject]",
"return self._init_value @property def validator(self) -> Callable[[T, Any], T]: return",
"FIXME: Not sure why both PyCharm and Mypy fails to",
"Callable[[T, Any], T]: return self._validator @property def modifier(self) -> Callable[[Any],",
"validator is not None self._validator = validator self._property: Optional[BehaviorSubject] =",
"T]) -> ReactiveProperty[T]: if validator is None: raise ValueError(\"Argument 'modifier'",
"dispose(self) -> None: assert self._property is not None self._check_disposed() self._property.on_completed()",
"@property def value(self) -> T: return super().value @value.setter def value(self,",
"from .value import Modifier T = TypeVar(\"T\") class ReactiveProperty(Generic[T], ReactiveValue[T]):",
"self._property.on_completed() super().dispose() def _create_data(self, obj: Any) -> PropertyData: assert obj",
"T) -> T: return validator(obj, self.validator(obj, v)) return ReactiveProperty(self.init_value, self.read_only,",
"investigate later. # noinspection PyUnresolvedReferences return pipeline.pipe(*([self.modifier(obj)] + list(modifiers(obj)))) #",
"is not None assert validator is not None self._validator =",
"not None self._validator = validator self._property: Optional[BehaviorSubject] = None obs:",
"-> None: super().__init__(read_only) self._init_value = init_value self._modifier = modifier self._validator",
"annotations from typing import TypeVar, Generic, Callable, Optional, Any, cast,",
"from typing import TypeVar, Generic, Callable, Optional, Any, cast, Tuple",
"= init_value self._modifier = modifier self._validator = validator @property def",
"None def validate(v: T) -> T: return self.validator(obj, v) return",
"@property def modifier(self) -> Callable[[Any], Modifier]: return self._modifier def as_view(self)",
"def validator(self) -> Callable[[T], T]: return self._validator def dispose(self) ->",
"assert init_value is not None assert modifier is not None",
"self._init_value @property def validator(self) -> Callable[[T, Any], T]: return self._validator",
"ReactiveValue, ReactiveView from .value import Modifier T = TypeVar(\"T\") class",
"+ list(modifiers(obj)))) # type:ignore return ReactiveProperty(self.init_value, self.read_only, stack, self.validator) def",
"PropertyData: assert obj is not None return cast(ReactiveProperty.PropertyData, super()._get_data(obj)) def",
"super().value @value.setter def value(self, value: T): self._check_disposed() if self.initialized: assert",
"and Mypy fails to resolve pipeline.pipe(). Should investigate later. #",
"return ReactiveProperty(self.init_value, self.read_only, stack, self.validator) def validate(self, validator: Callable[[Any, T],",
"Any], T]: return self._validator @property def modifier(self) -> Callable[[Any], Modifier]:",
"Callable[[Any], Modifier] = lambda _: identity, validator: Callable[[Any, T], T]",
"self._property else: obs = rx.empty() super().__init__(name, obs, modifier) # Must",
"return super().value @value.setter def value(self, value: T): self._check_disposed() if self.initialized:",
"PyCharm and Mypy fails to resolve pipeline.pipe(). Should investigate later.",
"T: return validator(obj, self.validator(obj, v)) return ReactiveProperty(self.init_value, self.read_only, self.modifier, validate)",
"validator(self) -> Callable[[T, Any], T]: return self._validator @property def modifier(self)",
"None: assert obj is not None assert isinstance(data, ReactiveProperty.PropertyData) data.value",
"= lambda _, v: v) -> None: super().__init__(read_only) self._init_value =",
"= self._property else: obs = rx.empty() super().__init__(name, obs, modifier) #",
"T]: return self._validator @property def modifier(self) -> Callable[[Any], Modifier]: return",
"from rx.subject import BehaviorSubject from . import ReactiveValue, ReactiveView from",
"def _get_data(self, obj: Any) -> PropertyData: assert obj is not",
"self.initialized: assert self._property is not None self._property.on_next(self.validator(value)) else: self._property =",
"return self._validator @property def modifier(self) -> Callable[[Any], Modifier]: return self._modifier",
"_, v: v) -> None: super().__init__(read_only) self._init_value = init_value self._modifier",
"def pipe(self, modifiers: Callable[[Any], Tuple[Modifier, ...]]) -> ReactiveProperty: def stack(obj:",
"self.read_only, stack, self.validator) def validate(self, validator: Callable[[Any, T], T]) ->",
"Modifier] = lambda _: identity, validator: Callable[[Any, T], T] =",
"self._modifier def as_view(self) -> ReactiveView[T]: return ReactiveView(self.context, self.read_only) def pipe(self,",
"Callable[[T], T]): assert name is not None assert init_value is",
"self.validator) def validate(self, validator: Callable[[Any, T], T]) -> ReactiveProperty[T]: if",
"later. # noinspection PyUnresolvedReferences return pipeline.pipe(*([self.modifier(obj)] + list(modifiers(obj)))) # type:ignore",
"# noinspection PyUnresolvedReferences return pipeline.pipe(*([self.modifier(obj)] + list(modifiers(obj)))) # type:ignore return",
"I hate Python. @property def value(self) -> T: return super().value",
"__init__( self, init_value: Maybe[T] = Nothing, read_only=False, modifier: Callable[[Any], Modifier]",
"ReactiveProperty: def stack(obj: Any): # FIXME: Not sure why both",
"Any, v: T) -> T: return validator(obj, self.validator(obj, v)) return",
"init_value(self) -> Maybe[T]: return self._init_value @property def validator(self) -> Callable[[T,",
"obs: Observable if init_value != Nothing: self._property = BehaviorSubject(init_value.map(validator).unwrap()) obs",
"obj is not None assert self.name is not None def",
"self.validator(obj, v) return self.PropertyData(self.name, self.init_value, self.modifier(obj), validate) def _get_data(self, obj:",
"Callable[[Any], Tuple[Modifier, ...]]) -> ReactiveProperty: def stack(obj: Any): # FIXME:",
"both PyCharm and Mypy fails to resolve pipeline.pipe(). Should investigate",
"self._modifier = modifier self._validator = validator @property def init_value(self) ->",
"sure why both PyCharm and Mypy fails to resolve pipeline.pipe().",
"-> T: return validator(obj, self.validator(obj, v)) return ReactiveProperty(self.init_value, self.read_only, self.modifier,",
"return ReactiveProperty(self.init_value, self.read_only, self.modifier, validate) class PropertyData(ReactiveValue.Data[T]): def __init__( self,",
"v: T) -> T: return validator(obj, self.validator(obj, v)) return ReactiveProperty(self.init_value,",
"validate) class PropertyData(ReactiveValue.Data[T]): def __init__( self, name: str, init_value: Maybe[T],",
"def validator(self) -> Callable[[T, Any], T]: return self._validator @property def",
"-> Callable[[Any], Modifier]: return self._modifier def as_view(self) -> ReactiveView[T]: return",
"= self._property @property def validator(self) -> Callable[[T], T]: return self._validator",
"None: raise ValueError(\"Argument 'modifier' is required.\") def validate(obj: Any, v:",
"modifier is not None assert validator is not None self._validator",
"-> Maybe[T]: return self._init_value @property def validator(self) -> Callable[[T, Any],",
"modifier) # Must override to appease Mypy... I hate Python.",
"appease Mypy... I hate Python. @property def value(self) -> T:",
"-> Callable[[T], T]: return self._validator def dispose(self) -> None: assert",
"ReactiveView from .value import Modifier T = TypeVar(\"T\") class ReactiveProperty(Generic[T],",
"Any) -> PropertyData: assert obj is not None assert self.name",
"resolve pipeline.pipe(). Should investigate later. # noinspection PyUnresolvedReferences return pipeline.pipe(*([self.modifier(obj)]",
"__future__ import annotations from typing import TypeVar, Generic, Callable, Optional,",
"-> PropertyData: assert obj is not None return cast(ReactiveProperty.PropertyData, super()._get_data(obj))",
"_: identity, validator: Callable[[Any, T], T] = lambda _, v:",
"is None: raise ValueError(\"Argument 'modifier' is required.\") def validate(obj: Any,",
"Nothing: self._property = BehaviorSubject(init_value.map(validator).unwrap()) obs = self._property else: obs =",
"ReactiveView(self.context, self.read_only) def pipe(self, modifiers: Callable[[Any], Tuple[Modifier, ...]]) -> ReactiveProperty:",
"cast(ReactiveProperty.PropertyData, super()._get_data(obj)) def _set_value(self, obj: Any, data: ReactiveValue.Data, value: Any)",
"why both PyCharm and Mypy fails to resolve pipeline.pipe(). Should",
"from rx import Observable from rx.subject import BehaviorSubject from .",
"self.read_only) def pipe(self, modifiers: Callable[[Any], Tuple[Modifier, ...]]) -> ReactiveProperty: def",
"-> ReactiveProperty[T]: if validator is None: raise ValueError(\"Argument 'modifier' is",
"_set_value(self, obj: Any, data: ReactiveValue.Data, value: Any) -> None: assert",
"def value(self, value: T): self._check_disposed() if self.initialized: assert self._property is",
"self, name: str, init_value: Maybe[T], modifier: Modifier, validator: Callable[[T], T]):",
"not None self._property.on_next(self.validator(value)) else: self._property = BehaviorSubject(self.validator(value)) self.observable = self._property",
"not None def validate(v: T) -> T: return self.validator(obj, v)",
"Tuple[Modifier, ...]]) -> ReactiveProperty: def stack(obj: Any): # FIXME: Not",
"ReactiveValue[T]): def __init__( self, init_value: Maybe[T] = Nothing, read_only=False, modifier:",
"v) -> None: super().__init__(read_only) self._init_value = init_value self._modifier = modifier",
"super().__init__(name, obs, modifier) # Must override to appease Mypy... I",
"else: obs = rx.empty() super().__init__(name, obs, modifier) # Must override",
"def _create_data(self, obj: Any) -> PropertyData: assert obj is not",
"validator is None: raise ValueError(\"Argument 'modifier' is required.\") def validate(obj:",
"fails to resolve pipeline.pipe(). Should investigate later. # noinspection PyUnresolvedReferences",
"Callable, Optional, Any, cast, Tuple import rx from returns import",
"Generic, Callable, Optional, Any, cast, Tuple import rx from returns",
"self._validator def dispose(self) -> None: assert self._property is not None",
"-> Callable[[T, Any], T]: return self._validator @property def modifier(self) ->",
"typing import TypeVar, Generic, Callable, Optional, Any, cast, Tuple import",
"def value(self) -> T: return super().value @value.setter def value(self, value:",
"Any) -> PropertyData: assert obj is not None return cast(ReactiveProperty.PropertyData,",
"TypeVar(\"T\") class ReactiveProperty(Generic[T], ReactiveValue[T]): def __init__( self, init_value: Maybe[T] =",
"stack, self.validator) def validate(self, validator: Callable[[Any, T], T]) -> ReactiveProperty[T]:",
"pipeline.pipe(*([self.modifier(obj)] + list(modifiers(obj)))) # type:ignore return ReactiveProperty(self.init_value, self.read_only, stack, self.validator)",
"self.name is not None def validate(v: T) -> T: return",
"validator self._property: Optional[BehaviorSubject] = None obs: Observable if init_value !=",
"PropertyData: assert obj is not None assert self.name is not",
"TypeVar, Generic, Callable, Optional, Any, cast, Tuple import rx from",
"obj: Any, data: ReactiveValue.Data, value: Any) -> None: assert obj",
"import ReactiveValue, ReactiveView from .value import Modifier T = TypeVar(\"T\")",
"class PropertyData(ReactiveValue.Data[T]): def __init__( self, name: str, init_value: Maybe[T], modifier:",
"obs = rx.empty() super().__init__(name, obs, modifier) # Must override to"
] |
[
"metavar='FILE', required=True, help='input file with CVAT annotation in xml format'",
"tqdm import tqdm def parse_args(): \"\"\"Parse arguments of command line\"\"\"",
"the mask format.\" ) parser.add_argument( '--mask-bitness', type=int, choices=[8, 24], default=8,",
"args = parse_args() anno = parse_anno_file(args.cvat_xml) color_map = {} dim",
"\" + \"be interpreted in accordance with the mask format.\"",
"box['xbr'], box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda x: int(x.get('z_order', 0))) anno.append(image) return anno",
"(C) 2018 Intel Corporation # # SPDX-License-Identifier: MIT from __future__",
"argparse import os import glog as log import numpy as",
"accordance with the mask format.\" ) parser.add_argument( '--mask-bitness', type=int, choices=[8,",
"CVAT annotation in xml format' ) parser.add_argument( '--background-color', metavar='COLOR_BGR', default=\"0,0,0\",",
"os.path.join(args.output_dir, os.path.splitext(image['name'])[0] + '.png') mask_dir = os.path.dirname(mask_path) if mask_dir: os.makedirs(mask_dir,",
"p in shape['points'].split(';')] points = np.array([(int(p[0]), int(p[1])) for p in",
"arguments of command line\"\"\" parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT",
"= {} for key, value in image_tag.items(): image[key] = value",
"# SPDX-License-Identifier: MIT from __future__ import absolute_import, division, print_function import",
"print_function import argparse import os import glog as log import",
"0))) anno.append(image) return anno def create_mask_file(mask_path, width, height, bitness, color_map,",
"// 8), dtype=np.uint8) for shape in shapes: color = color_map.get(shape['label'],",
"{'type': 'polygon'} for key, value in poly_tag.items(): polygon[key] = value",
"box = {'type': 'box'} for key, value in box_tag.items(): box[key]",
"color (e.g. 255 or 255,0,0). The color will \" +",
"args.mask_bitness // 8 for item in args.label_color: label, color =",
"key, value in poly_tag.items(): polygon[key] = value image['shapes'].append(polygon) for box_tag",
"dim = args.mask_bitness // 8 for item in args.label_color: label,",
"= list(map(int, str.split(','))) if len(scalar) < dim: scalar.extend([scalar[-1]] * dim)",
"str.split(','))) if len(scalar) < dim: scalar.extend([scalar[-1]] * dim) return tuple(scalar[0:dim])",
"points = [tuple(map(float, p.split(','))) for p in shape['points'].split(';')] points =",
"key, value in box_tag.items(): box[key] = value box['points'] = \"{0},{1};{2},{1};{2},{3};{0},{3}\".format(",
"from __future__ import absolute_import, division, print_function import argparse import os",
"def main(): args = parse_args() anno = parse_anno_file(args.cvat_xml) color_map =",
"desc='Generate masks'): mask_path = os.path.join(args.output_dir, os.path.splitext(image['name'])[0] + '.png') mask_dir =",
"background, shapes): mask = np.zeros((height, width, bitness // 8), dtype=np.uint8)",
"= [] for poly_tag in image_tag.iter('polygon'): polygon = {'type': 'polygon'}",
"# # Copyright (C) 2018 Intel Corporation # # SPDX-License-Identifier:",
"poly_tag in image_tag.iter('polygon'): polygon = {'type': 'polygon'} for key, value",
"python # # Copyright (C) 2018 Intel Corporation # #",
"= to_scalar(color, dim) background = to_scalar(args.background_color, dim) for image in",
"* dim) return tuple(scalar[0:dim]) def main(): args = parse_args() anno",
"[] for image_tag in root.iter('image'): image = {} for key,",
"= value box['points'] = \"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'], box['ytl'], box['xbr'], box['ybr']) image['shapes'].append(box)",
"width, bitness // 8), dtype=np.uint8) for shape in shapes: color",
"in accordance with the mask format.\" ) parser.add_argument( '--mask-bitness', type=int,",
"p.split(','))) for p in shape['points'].split(';')] points = np.array([(int(p[0]), int(p[1])) for",
"np.array([(int(p[0]), int(p[1])) for p in points]) mask = cv2.fillPoly(mask, [points],",
"root = etree.parse(cvat_xml).getroot() anno = [] for image_tag in root.iter('image'):",
"image['shapes'] = [] for poly_tag in image_tag.iter('polygon'): polygon = {'type':",
"metavar='LABEL:COLOR_BGR', action='append', default=[], help=\"specify a label's color (e.g. 255 or",
"mask format.\" ) parser.add_argument( '--mask-bitness', type=int, choices=[8, 24], default=8, help='choose",
"'--mask-bitness', type=int, choices=[8, 24], default=8, help='choose bitness for masks' )",
"= os.path.join(args.output_dir, os.path.splitext(image['name'])[0] + '.png') mask_dir = os.path.dirname(mask_path) if mask_dir:",
"scalar = list(map(int, str.split(','))) if len(scalar) < dim: scalar.extend([scalar[-1]] *",
"[] for poly_tag in image_tag.iter('polygon'): polygon = {'type': 'polygon'} for",
"image['shapes'].append(polygon) for box_tag in image_tag.iter('box'): box = {'type': 'box'} for",
"mask_path = os.path.join(args.output_dir, os.path.splitext(image['name'])[0] + '.png') mask_dir = os.path.dirname(mask_path) if",
"= color_map.get(shape['label'], background) points = [tuple(map(float, p.split(','))) for p in",
"to_scalar(args.background_color, dim) for image in tqdm(anno, desc='Generate masks'): mask_path =",
"255,0,0). The color will \" + \"be interpreted in accordance",
"type=int, choices=[8, 24], default=8, help='choose bitness for masks' ) parser.add_argument(",
"numpy as np import cv2 from lxml import etree from",
"in image_tag.iter('polygon'): polygon = {'type': 'polygon'} for key, value in",
"= os.path.dirname(mask_path) if mask_dir: os.makedirs(mask_dir, exist_ok=True) create_mask_file(mask_path, int(image['width']), int(image['height']), args.mask_bitness,",
"if len(scalar) < dim: scalar.extend([scalar[-1]] * dim) return tuple(scalar[0:dim]) def",
"color_map[label] = to_scalar(color, dim) background = to_scalar(args.background_color, dim) for image",
"output masks' ) return parser.parse_args() def parse_anno_file(cvat_xml): root = etree.parse(cvat_xml).getroot()",
"anno.append(image) return anno def create_mask_file(mask_path, width, height, bitness, color_map, background,",
"to_scalar(color, dim) background = to_scalar(args.background_color, dim) for image in tqdm(anno,",
"for poly_tag in image_tag.iter('polygon'): polygon = {'type': 'polygon'} for key,",
"def parse_args(): \"\"\"Parse arguments of command line\"\"\" parser = argparse.ArgumentParser(",
"value box['points'] = \"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'], box['ytl'], box['xbr'], box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda",
"{'type': 'box'} for key, value in box_tag.items(): box[key] = value",
"= {'type': 'box'} for key, value in box_tag.items(): box[key] =",
"interpreted in accordance with the mask format.\" ) parser.add_argument( '--mask-bitness',",
"file with CVAT annotation in xml format' ) parser.add_argument( '--background-color',",
"help=\"specify a label's color (e.g. 255 or 255,0,0). The color",
"box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda x: int(x.get('z_order', 0))) anno.append(image) return anno def",
"= np.zeros((height, width, bitness // 8), dtype=np.uint8) for shape in",
"to masks' ) parser.add_argument( '--cvat-xml', metavar='FILE', required=True, help='input file with",
"__future__ import absolute_import, division, print_function import argparse import os import",
"for key, value in poly_tag.items(): polygon[key] = value image['shapes'].append(polygon) for",
"key, value in image_tag.items(): image[key] = value image['shapes'] = []",
"image_tag.iter('polygon'): polygon = {'type': 'polygon'} for key, value in poly_tag.items():",
"os.path.dirname(mask_path) if mask_dir: os.makedirs(mask_dir, exist_ok=True) create_mask_file(mask_path, int(image['width']), int(image['height']), args.mask_bitness, color_map,",
"\"\"\"Parse arguments of command line\"\"\" parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert",
"\"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'], box['ytl'], box['xbr'], box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda x: int(x.get('z_order', 0)))",
"x: int(x.get('z_order', 0))) anno.append(image) return anno def create_mask_file(mask_path, width, height,",
"int(p[1])) for p in points]) mask = cv2.fillPoly(mask, [points], color=color)",
"division, print_function import argparse import os import glog as log",
"background) points = [tuple(map(float, p.split(','))) for p in shape['points'].split(';')] points",
"import glog as log import numpy as np import cv2",
"exist_ok=True) create_mask_file(mask_path, int(image['width']), int(image['height']), args.mask_bitness, color_map, background, image['shapes']) if __name__",
"dim) return tuple(scalar[0:dim]) def main(): args = parse_args() anno =",
"color_map, background, shapes): mask = np.zeros((height, width, bitness // 8),",
"background color (by default: 0,0,0)' ) parser.add_argument( '--label-color', metavar='LABEL:COLOR_BGR', action='append',",
"#!/usr/bin/env python # # Copyright (C) 2018 Intel Corporation #",
"parse_anno_file(args.cvat_xml) color_map = {} dim = args.mask_bitness // 8 for",
"0,0,0)' ) parser.add_argument( '--label-color', metavar='LABEL:COLOR_BGR', action='append', default=[], help=\"specify a label's",
"value in poly_tag.items(): polygon[key] = value image['shapes'].append(polygon) for box_tag in",
"label, color = item.split(':') color_map[label] = to_scalar(color, dim) background =",
"os import glog as log import numpy as np import",
"8 for item in args.label_color: label, color = item.split(':') color_map[label]",
"= {'type': 'polygon'} for key, value in poly_tag.items(): polygon[key] =",
"np import cv2 from lxml import etree from tqdm import",
"parse_args() anno = parse_anno_file(args.cvat_xml) color_map = {} dim = args.mask_bitness",
"fromfile_prefix_chars='@', description='Convert CVAT XML annotations to masks' ) parser.add_argument( '--cvat-xml',",
") parser.add_argument( '--background-color', metavar='COLOR_BGR', default=\"0,0,0\", help='specify background color (by default:",
"box[key] = value box['points'] = \"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'], box['ytl'], box['xbr'], box['ybr'])",
"SPDX-License-Identifier: MIT from __future__ import absolute_import, division, print_function import argparse",
"box['ytl'], box['xbr'], box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda x: int(x.get('z_order', 0))) anno.append(image) return",
") parser.add_argument( '--label-color', metavar='LABEL:COLOR_BGR', action='append', default=[], help=\"specify a label's color",
"points]) mask = cv2.fillPoly(mask, [points], color=color) cv2.imwrite(mask_path, mask) def to_scalar(str,",
"help='choose bitness for masks' ) parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True, help='directory",
"item.split(':') color_map[label] = to_scalar(color, dim) background = to_scalar(args.background_color, dim) for",
"required=True, help='directory for output masks' ) return parser.parse_args() def parse_anno_file(cvat_xml):",
"for item in args.label_color: label, color = item.split(':') color_map[label] =",
"mask = np.zeros((height, width, bitness // 8), dtype=np.uint8) for shape",
"+ \"be interpreted in accordance with the mask format.\" )",
"line\"\"\" parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT XML annotations to",
"for masks' ) parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True, help='directory for output",
"'--output-dir', metavar='DIRECTORY', required=True, help='directory for output masks' ) return parser.parse_args()",
"def to_scalar(str, dim): scalar = list(map(int, str.split(','))) if len(scalar) <",
"mask_dir: os.makedirs(mask_dir, exist_ok=True) create_mask_file(mask_path, int(image['width']), int(image['height']), args.mask_bitness, color_map, background, image['shapes'])",
"'box'} for key, value in box_tag.items(): box[key] = value box['points']",
"[points], color=color) cv2.imwrite(mask_path, mask) def to_scalar(str, dim): scalar = list(map(int,",
"in root.iter('image'): image = {} for key, value in image_tag.items():",
"image = {} for key, value in image_tag.items(): image[key] =",
"value in box_tag.items(): box[key] = value box['points'] = \"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'],",
"in args.label_color: label, color = item.split(':') color_map[label] = to_scalar(color, dim)",
"in box_tag.items(): box[key] = value box['points'] = \"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'], box['ytl'],",
"description='Convert CVAT XML annotations to masks' ) parser.add_argument( '--cvat-xml', metavar='FILE',",
"import etree from tqdm import tqdm def parse_args(): \"\"\"Parse arguments",
"format' ) parser.add_argument( '--background-color', metavar='COLOR_BGR', default=\"0,0,0\", help='specify background color (by",
"box_tag.items(): box[key] = value box['points'] = \"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'], box['ytl'], box['xbr'],",
"from lxml import etree from tqdm import tqdm def parse_args():",
"for p in points]) mask = cv2.fillPoly(mask, [points], color=color) cv2.imwrite(mask_path,",
"int(image['width']), int(image['height']), args.mask_bitness, color_map, background, image['shapes']) if __name__ == \"__main__\":",
"(by default: 0,0,0)' ) parser.add_argument( '--label-color', metavar='LABEL:COLOR_BGR', action='append', default=[], help=\"specify",
"for key, value in box_tag.items(): box[key] = value box['points'] =",
"'--label-color', metavar='LABEL:COLOR_BGR', action='append', default=[], help=\"specify a label's color (e.g. 255",
"to_scalar(str, dim): scalar = list(map(int, str.split(','))) if len(scalar) < dim:",
"annotations to masks' ) parser.add_argument( '--cvat-xml', metavar='FILE', required=True, help='input file",
"bitness for masks' ) parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True, help='directory for",
"= to_scalar(args.background_color, dim) for image in tqdm(anno, desc='Generate masks'): mask_path",
"parse_anno_file(cvat_xml): root = etree.parse(cvat_xml).getroot() anno = [] for image_tag in",
"= value image['shapes'] = [] for poly_tag in image_tag.iter('polygon'): polygon",
"return anno def create_mask_file(mask_path, width, height, bitness, color_map, background, shapes):",
"root.iter('image'): image = {} for key, value in image_tag.items(): image[key]",
"= etree.parse(cvat_xml).getroot() anno = [] for image_tag in root.iter('image'): image",
"glog as log import numpy as np import cv2 from",
"metavar='COLOR_BGR', default=\"0,0,0\", help='specify background color (by default: 0,0,0)' ) parser.add_argument(",
"cv2.fillPoly(mask, [points], color=color) cv2.imwrite(mask_path, mask) def to_scalar(str, dim): scalar =",
"def create_mask_file(mask_path, width, height, bitness, color_map, background, shapes): mask =",
"create_mask_file(mask_path, width, height, bitness, color_map, background, shapes): mask = np.zeros((height,",
"help='input file with CVAT annotation in xml format' ) parser.add_argument(",
"tqdm(anno, desc='Generate masks'): mask_path = os.path.join(args.output_dir, os.path.splitext(image['name'])[0] + '.png') mask_dir",
"in image_tag.items(): image[key] = value image['shapes'] = [] for poly_tag",
"bitness // 8), dtype=np.uint8) for shape in shapes: color =",
"image_tag.items(): image[key] = value image['shapes'] = [] for poly_tag in",
"< dim: scalar.extend([scalar[-1]] * dim) return tuple(scalar[0:dim]) def main(): args",
") parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True, help='directory for output masks' )",
"etree.parse(cvat_xml).getroot() anno = [] for image_tag in root.iter('image'): image =",
"for image in tqdm(anno, desc='Generate masks'): mask_path = os.path.join(args.output_dir, os.path.splitext(image['name'])[0]",
"in shape['points'].split(';')] points = np.array([(int(p[0]), int(p[1])) for p in points])",
"np.zeros((height, width, bitness // 8), dtype=np.uint8) for shape in shapes:",
"dim): scalar = list(map(int, str.split(','))) if len(scalar) < dim: scalar.extend([scalar[-1]]",
"MIT from __future__ import absolute_import, division, print_function import argparse import",
"item in args.label_color: label, color = item.split(':') color_map[label] = to_scalar(color,",
"{} for key, value in image_tag.items(): image[key] = value image['shapes']",
"= item.split(':') color_map[label] = to_scalar(color, dim) background = to_scalar(args.background_color, dim)",
"with CVAT annotation in xml format' ) parser.add_argument( '--background-color', metavar='COLOR_BGR',",
"XML annotations to masks' ) parser.add_argument( '--cvat-xml', metavar='FILE', required=True, help='input",
"anno = [] for image_tag in root.iter('image'): image = {}",
"= argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT XML annotations to masks' )",
"in xml format' ) parser.add_argument( '--background-color', metavar='COLOR_BGR', default=\"0,0,0\", help='specify background",
"def parse_anno_file(cvat_xml): root = etree.parse(cvat_xml).getroot() anno = [] for image_tag",
"default: 0,0,0)' ) parser.add_argument( '--label-color', metavar='LABEL:COLOR_BGR', action='append', default=[], help=\"specify a",
"+ '.png') mask_dir = os.path.dirname(mask_path) if mask_dir: os.makedirs(mask_dir, exist_ok=True) create_mask_file(mask_path,",
"[tuple(map(float, p.split(','))) for p in shape['points'].split(';')] points = np.array([(int(p[0]), int(p[1]))",
"import os import glog as log import numpy as np",
"'--background-color', metavar='COLOR_BGR', default=\"0,0,0\", help='specify background color (by default: 0,0,0)' )",
"= parse_args() anno = parse_anno_file(args.cvat_xml) color_map = {} dim =",
"parser.add_argument( '--mask-bitness', type=int, choices=[8, 24], default=8, help='choose bitness for masks'",
"image[key] = value image['shapes'] = [] for poly_tag in image_tag.iter('polygon'):",
"default=\"0,0,0\", help='specify background color (by default: 0,0,0)' ) parser.add_argument( '--label-color',",
"value image['shapes'].append(polygon) for box_tag in image_tag.iter('box'): box = {'type': 'box'}",
"create_mask_file(mask_path, int(image['width']), int(image['height']), args.mask_bitness, color_map, background, image['shapes']) if __name__ ==",
"mask) def to_scalar(str, dim): scalar = list(map(int, str.split(','))) if len(scalar)",
"of command line\"\"\" parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT XML",
"image in tqdm(anno, desc='Generate masks'): mask_path = os.path.join(args.output_dir, os.path.splitext(image['name'])[0] +",
"{} dim = args.mask_bitness // 8 for item in args.label_color:",
"parser.add_argument( '--background-color', metavar='COLOR_BGR', default=\"0,0,0\", help='specify background color (by default: 0,0,0)'",
"width, height, bitness, color_map, background, shapes): mask = np.zeros((height, width,",
"= np.array([(int(p[0]), int(p[1])) for p in points]) mask = cv2.fillPoly(mask,",
"for key, value in image_tag.items(): image[key] = value image['shapes'] =",
"label's color (e.g. 255 or 255,0,0). The color will \"",
"list(map(int, str.split(','))) if len(scalar) < dim: scalar.extend([scalar[-1]] * dim) return",
"p in points]) mask = cv2.fillPoly(mask, [points], color=color) cv2.imwrite(mask_path, mask)",
"for output masks' ) return parser.parse_args() def parse_anno_file(cvat_xml): root =",
"background = to_scalar(args.background_color, dim) for image in tqdm(anno, desc='Generate masks'):",
") parser.add_argument( '--mask-bitness', type=int, choices=[8, 24], default=8, help='choose bitness for",
"masks' ) parser.add_argument( '--cvat-xml', metavar='FILE', required=True, help='input file with CVAT",
"= [] for image_tag in root.iter('image'): image = {} for",
"parser.add_argument( '--cvat-xml', metavar='FILE', required=True, help='input file with CVAT annotation in",
") return parser.parse_args() def parse_anno_file(cvat_xml): root = etree.parse(cvat_xml).getroot() anno =",
"color_map = {} dim = args.mask_bitness // 8 for item",
"\"be interpreted in accordance with the mask format.\" ) parser.add_argument(",
"with the mask format.\" ) parser.add_argument( '--mask-bitness', type=int, choices=[8, 24],",
"import absolute_import, division, print_function import argparse import os import glog",
"import cv2 from lxml import etree from tqdm import tqdm",
"mask_dir = os.path.dirname(mask_path) if mask_dir: os.makedirs(mask_dir, exist_ok=True) create_mask_file(mask_path, int(image['width']), int(image['height']),",
"color=color) cv2.imwrite(mask_path, mask) def to_scalar(str, dim): scalar = list(map(int, str.split(',')))",
"'polygon'} for key, value in poly_tag.items(): polygon[key] = value image['shapes'].append(polygon)",
"parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT XML annotations to masks'",
"value image['shapes'] = [] for poly_tag in image_tag.iter('polygon'): polygon =",
"= {} dim = args.mask_bitness // 8 for item in",
"in tqdm(anno, desc='Generate masks'): mask_path = os.path.join(args.output_dir, os.path.splitext(image['name'])[0] + '.png')",
"color (by default: 0,0,0)' ) parser.add_argument( '--label-color', metavar='LABEL:COLOR_BGR', action='append', default=[],",
"color = item.split(':') color_map[label] = to_scalar(color, dim) background = to_scalar(args.background_color,",
"in points]) mask = cv2.fillPoly(mask, [points], color=color) cv2.imwrite(mask_path, mask) def",
"(e.g. 255 or 255,0,0). The color will \" + \"be",
"command line\"\"\" parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT XML annotations",
"color will \" + \"be interpreted in accordance with the",
"Intel Corporation # # SPDX-License-Identifier: MIT from __future__ import absolute_import,",
"image['shapes'].append(box) image['shapes'].sort(key=lambda x: int(x.get('z_order', 0))) anno.append(image) return anno def create_mask_file(mask_path,",
"tuple(scalar[0:dim]) def main(): args = parse_args() anno = parse_anno_file(args.cvat_xml) color_map",
"tqdm def parse_args(): \"\"\"Parse arguments of command line\"\"\" parser =",
"action='append', default=[], help=\"specify a label's color (e.g. 255 or 255,0,0).",
"dtype=np.uint8) for shape in shapes: color = color_map.get(shape['label'], background) points",
"CVAT XML annotations to masks' ) parser.add_argument( '--cvat-xml', metavar='FILE', required=True,",
"dim: scalar.extend([scalar[-1]] * dim) return tuple(scalar[0:dim]) def main(): args =",
"Corporation # # SPDX-License-Identifier: MIT from __future__ import absolute_import, division,",
"choices=[8, 24], default=8, help='choose bitness for masks' ) parser.add_argument( '--output-dir',",
"for p in shape['points'].split(';')] points = np.array([(int(p[0]), int(p[1])) for p",
"xml format' ) parser.add_argument( '--background-color', metavar='COLOR_BGR', default=\"0,0,0\", help='specify background color",
"polygon[key] = value image['shapes'].append(polygon) for box_tag in image_tag.iter('box'): box =",
"from tqdm import tqdm def parse_args(): \"\"\"Parse arguments of command",
"= [tuple(map(float, p.split(','))) for p in shape['points'].split(';')] points = np.array([(int(p[0]),",
"len(scalar) < dim: scalar.extend([scalar[-1]] * dim) return tuple(scalar[0:dim]) def main():",
"metavar='DIRECTORY', required=True, help='directory for output masks' ) return parser.parse_args() def",
"default=8, help='choose bitness for masks' ) parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True,",
"box['xtl'], box['ytl'], box['xbr'], box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda x: int(x.get('z_order', 0))) anno.append(image)",
"anno = parse_anno_file(args.cvat_xml) color_map = {} dim = args.mask_bitness //",
"anno def create_mask_file(mask_path, width, height, bitness, color_map, background, shapes): mask",
"shape in shapes: color = color_map.get(shape['label'], background) points = [tuple(map(float,",
"polygon = {'type': 'polygon'} for key, value in poly_tag.items(): polygon[key]",
"return tuple(scalar[0:dim]) def main(): args = parse_args() anno = parse_anno_file(args.cvat_xml)",
"= \"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'], box['ytl'], box['xbr'], box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda x: int(x.get('z_order',",
"argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT XML annotations to masks' ) parser.add_argument(",
"255 or 255,0,0). The color will \" + \"be interpreted",
"= parse_anno_file(args.cvat_xml) color_map = {} dim = args.mask_bitness // 8",
"8), dtype=np.uint8) for shape in shapes: color = color_map.get(shape['label'], background)",
"main(): args = parse_args() anno = parse_anno_file(args.cvat_xml) color_map = {}",
"value in image_tag.items(): image[key] = value image['shapes'] = [] for",
"masks'): mask_path = os.path.join(args.output_dir, os.path.splitext(image['name'])[0] + '.png') mask_dir = os.path.dirname(mask_path)",
"= cv2.fillPoly(mask, [points], color=color) cv2.imwrite(mask_path, mask) def to_scalar(str, dim): scalar",
"'--cvat-xml', metavar='FILE', required=True, help='input file with CVAT annotation in xml",
"image_tag in root.iter('image'): image = {} for key, value in",
"import tqdm def parse_args(): \"\"\"Parse arguments of command line\"\"\" parser",
"box['points'] = \"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'], box['ytl'], box['xbr'], box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda x:",
"for image_tag in root.iter('image'): image = {} for key, value",
"mask = cv2.fillPoly(mask, [points], color=color) cv2.imwrite(mask_path, mask) def to_scalar(str, dim):",
"'.png') mask_dir = os.path.dirname(mask_path) if mask_dir: os.makedirs(mask_dir, exist_ok=True) create_mask_file(mask_path, int(image['width']),",
"bitness, color_map, background, shapes): mask = np.zeros((height, width, bitness //",
"24], default=8, help='choose bitness for masks' ) parser.add_argument( '--output-dir', metavar='DIRECTORY',",
"a label's color (e.g. 255 or 255,0,0). The color will",
"shape['points'].split(';')] points = np.array([(int(p[0]), int(p[1])) for p in points]) mask",
"args.label_color: label, color = item.split(':') color_map[label] = to_scalar(color, dim) background",
"int(x.get('z_order', 0))) anno.append(image) return anno def create_mask_file(mask_path, width, height, bitness,",
"masks' ) return parser.parse_args() def parse_anno_file(cvat_xml): root = etree.parse(cvat_xml).getroot() anno",
"cv2 from lxml import etree from tqdm import tqdm def",
") parser.add_argument( '--cvat-xml', metavar='FILE', required=True, help='input file with CVAT annotation",
"as np import cv2 from lxml import etree from tqdm",
"image['shapes'].sort(key=lambda x: int(x.get('z_order', 0))) anno.append(image) return anno def create_mask_file(mask_path, width,",
"for shape in shapes: color = color_map.get(shape['label'], background) points =",
"2018 Intel Corporation # # SPDX-License-Identifier: MIT from __future__ import",
"Copyright (C) 2018 Intel Corporation # # SPDX-License-Identifier: MIT from",
"os.makedirs(mask_dir, exist_ok=True) create_mask_file(mask_path, int(image['width']), int(image['height']), args.mask_bitness, color_map, background, image['shapes']) if",
"or 255,0,0). The color will \" + \"be interpreted in",
"cv2.imwrite(mask_path, mask) def to_scalar(str, dim): scalar = list(map(int, str.split(','))) if",
"log import numpy as np import cv2 from lxml import",
"absolute_import, division, print_function import argparse import os import glog as",
"will \" + \"be interpreted in accordance with the mask",
"format.\" ) parser.add_argument( '--mask-bitness', type=int, choices=[8, 24], default=8, help='choose bitness",
"as log import numpy as np import cv2 from lxml",
"import numpy as np import cv2 from lxml import etree",
"shapes: color = color_map.get(shape['label'], background) points = [tuple(map(float, p.split(','))) for",
"if mask_dir: os.makedirs(mask_dir, exist_ok=True) create_mask_file(mask_path, int(image['width']), int(image['height']), args.mask_bitness, color_map, background,",
"parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True, help='directory for output masks' ) return",
"image_tag.iter('box'): box = {'type': 'box'} for key, value in box_tag.items():",
"masks' ) parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True, help='directory for output masks'",
"help='specify background color (by default: 0,0,0)' ) parser.add_argument( '--label-color', metavar='LABEL:COLOR_BGR',",
"height, bitness, color_map, background, shapes): mask = np.zeros((height, width, bitness",
"etree from tqdm import tqdm def parse_args(): \"\"\"Parse arguments of",
"int(image['height']), args.mask_bitness, color_map, background, image['shapes']) if __name__ == \"__main__\": main()",
"= args.mask_bitness // 8 for item in args.label_color: label, color",
"in poly_tag.items(): polygon[key] = value image['shapes'].append(polygon) for box_tag in image_tag.iter('box'):",
"points = np.array([(int(p[0]), int(p[1])) for p in points]) mask =",
"parser.parse_args() def parse_anno_file(cvat_xml): root = etree.parse(cvat_xml).getroot() anno = [] for",
"lxml import etree from tqdm import tqdm def parse_args(): \"\"\"Parse",
"poly_tag.items(): polygon[key] = value image['shapes'].append(polygon) for box_tag in image_tag.iter('box'): box",
"= value image['shapes'].append(polygon) for box_tag in image_tag.iter('box'): box = {'type':",
"color_map.get(shape['label'], background) points = [tuple(map(float, p.split(','))) for p in shape['points'].split(';')]",
"return parser.parse_args() def parse_anno_file(cvat_xml): root = etree.parse(cvat_xml).getroot() anno = []",
"dim) background = to_scalar(args.background_color, dim) for image in tqdm(anno, desc='Generate",
"help='directory for output masks' ) return parser.parse_args() def parse_anno_file(cvat_xml): root",
"dim) for image in tqdm(anno, desc='Generate masks'): mask_path = os.path.join(args.output_dir,",
"annotation in xml format' ) parser.add_argument( '--background-color', metavar='COLOR_BGR', default=\"0,0,0\", help='specify",
"shapes): mask = np.zeros((height, width, bitness // 8), dtype=np.uint8) for",
"default=[], help=\"specify a label's color (e.g. 255 or 255,0,0). The",
"in image_tag.iter('box'): box = {'type': 'box'} for key, value in",
"# Copyright (C) 2018 Intel Corporation # # SPDX-License-Identifier: MIT",
"# # SPDX-License-Identifier: MIT from __future__ import absolute_import, division, print_function",
"parse_args(): \"\"\"Parse arguments of command line\"\"\" parser = argparse.ArgumentParser( fromfile_prefix_chars='@',",
"parser.add_argument( '--label-color', metavar='LABEL:COLOR_BGR', action='append', default=[], help=\"specify a label's color (e.g.",
"import argparse import os import glog as log import numpy",
"box_tag in image_tag.iter('box'): box = {'type': 'box'} for key, value",
"in shapes: color = color_map.get(shape['label'], background) points = [tuple(map(float, p.split(',')))",
"color = color_map.get(shape['label'], background) points = [tuple(map(float, p.split(','))) for p",
"os.path.splitext(image['name'])[0] + '.png') mask_dir = os.path.dirname(mask_path) if mask_dir: os.makedirs(mask_dir, exist_ok=True)",
"scalar.extend([scalar[-1]] * dim) return tuple(scalar[0:dim]) def main(): args = parse_args()",
"// 8 for item in args.label_color: label, color = item.split(':')",
"The color will \" + \"be interpreted in accordance with",
"for box_tag in image_tag.iter('box'): box = {'type': 'box'} for key,",
"required=True, help='input file with CVAT annotation in xml format' )"
] |
[
"tracking_params which we will pass to the AFQ object #",
"object to use bundles from both # the standard and",
"tracking_params=tracking_params) ########################################################################## # Visualizing bundles and tract profiles: # ---------------------------------------",
"as afd ########################################################################## # Get some example data # ---------------------",
"bundles list (api.BUNDLES) plus the # callosal bundle list. This",
"both # the standard and callosal templates. myafq = api.AFQ(bids_path=op.join(afd.afq_home,",
"and callosal templates. myafq = api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), dmriprep='vistasoft', bundle_info=api.BUNDLES +",
"<reponame>gkiar/pyAFQ \"\"\" ========================== Callosal bundles using AFQ API ========================== An",
"# # Retrieves `Stanford HARDI dataset <https://purl.stanford.edu/ng782rw8378>`_. # afd.organize_stanford_data(clear_previous_afq=True) ##########################################################################",
"to find callosal bundles using the templates from: http://hdl.handle.net/1773/34926 \"\"\"",
"Retrieves `Stanford HARDI dataset <https://purl.stanford.edu/ng782rw8378>`_. # afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## # Set",
"# We make this tracking_params which we will pass to",
"AFQ.mask import RoiMask import AFQ.data as afd ########################################################################## # Get",
"the AFQ API to find callosal bundles using the templates",
"# We only do this to make this example faster",
"script and visualize the bundles using the plotly # interactive",
"example faster and consume less space. tracking_params = dict(seed_mask=RoiMask(), n_seeds=10000,",
"# Retrieves `Stanford HARDI dataset <https://purl.stanford.edu/ng782rw8378>`_. # afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## #",
"which specifies that we want 100,000 seeds randomly distributed #",
"# afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## # Set tractography parameters (optional) # ---------------------",
"the plotly # interactive visualization, which should automatically open in",
"using AFQ API ========================== An example using the AFQ API",
"consume less space. tracking_params = dict(seed_mask=RoiMask(), n_seeds=10000, random_seeds=True, rng_seed=42) ##########################################################################",
"AFQ API to find callosal bundles using the templates from:",
"seeds randomly distributed # in the ROIs of every bundle.",
"# --------------------- # # Retrieves `Stanford HARDI dataset <https://purl.stanford.edu/ng782rw8378>`_. #",
"# # We specify bundle_info as the default bundles list",
"the ROIs of every bundle. # # We only do",
"specifies that we want 100,000 seeds randomly distributed # in",
"and visualize the bundles using the plotly # interactive visualization,",
"# Get some example data # --------------------- # # Retrieves",
"afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## # Set tractography parameters (optional) # --------------------- #",
"parameters (optional) # --------------------- # We make this tracking_params which",
"+ api.CALLOSUM_BUNDLES, tracking_params=tracking_params) ########################################################################## # Visualizing bundles and tract profiles:",
"api from AFQ.mask import RoiMask import AFQ.data as afd ##########################################################################",
"AFQ.data as afd ########################################################################## # Get some example data #",
"# which specifies that we want 100,000 seeds randomly distributed",
"AFQ object: # ------------------------- # # We specify bundle_info as",
"http://hdl.handle.net/1773/34926 \"\"\" import os.path as op import plotly from AFQ",
"of every bundle. # # We only do this to",
"random_seeds=True, rng_seed=42) ########################################################################## # Initialize an AFQ object: # -------------------------",
"bundles and tract profiles: # --------------------------------------- # This would run",
"open in a # new browser window. bundle_html = myafq.viz_bundles(export=True,",
"interactive visualization, which should automatically open in a # new",
"AFQ API ========================== An example using the AFQ API to",
"from: http://hdl.handle.net/1773/34926 \"\"\" import os.path as op import plotly from",
"use bundles from both # the standard and callosal templates.",
"`Stanford HARDI dataset <https://purl.stanford.edu/ng782rw8378>`_. # afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## # Set tractography",
"\"\"\" import os.path as op import plotly from AFQ import",
"tractography parameters (optional) # --------------------- # We make this tracking_params",
"bundle list. This tells the AFQ object to use bundles",
"callosal bundles using the templates from: http://hdl.handle.net/1773/34926 \"\"\" import os.path",
"########################################################################## # Visualizing bundles and tract profiles: # --------------------------------------- #",
"import RoiMask import AFQ.data as afd ########################################################################## # Get some",
"(api.BUNDLES) plus the # callosal bundle list. This tells the",
"example using the AFQ API to find callosal bundles using",
"------------------------- # # We specify bundle_info as the default bundles",
"'stanford_hardi'), dmriprep='vistasoft', bundle_info=api.BUNDLES + api.CALLOSUM_BUNDLES, tracking_params=tracking_params) ########################################################################## # Visualizing bundles",
"RoiMask import AFQ.data as afd ########################################################################## # Get some example",
"the # callosal bundle list. This tells the AFQ object",
"we will pass to the AFQ object # which specifies",
"from AFQ import api from AFQ.mask import RoiMask import AFQ.data",
"the default bundles list (api.BUNDLES) plus the # callosal bundle",
"this example faster and consume less space. tracking_params = dict(seed_mask=RoiMask(),",
"templates. myafq = api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), dmriprep='vistasoft', bundle_info=api.BUNDLES + api.CALLOSUM_BUNDLES, tracking_params=tracking_params)",
"<https://purl.stanford.edu/ng782rw8378>`_. # afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## # Set tractography parameters (optional) #",
"myafq = api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), dmriprep='vistasoft', bundle_info=api.BUNDLES + api.CALLOSUM_BUNDLES, tracking_params=tracking_params) ##########################################################################",
"os.path as op import plotly from AFQ import api from",
"make this example faster and consume less space. tracking_params =",
"bundles from both # the standard and callosal templates. myafq",
"100,000 seeds randomly distributed # in the ROIs of every",
"data # --------------------- # # Retrieves `Stanford HARDI dataset <https://purl.stanford.edu/ng782rw8378>`_.",
"should automatically open in a # new browser window. bundle_html",
"# This would run the script and visualize the bundles",
"some example data # --------------------- # # Retrieves `Stanford HARDI",
"tells the AFQ object to use bundles from both #",
"would run the script and visualize the bundles using the",
"and consume less space. tracking_params = dict(seed_mask=RoiMask(), n_seeds=10000, random_seeds=True, rng_seed=42)",
"templates from: http://hdl.handle.net/1773/34926 \"\"\" import os.path as op import plotly",
"less space. tracking_params = dict(seed_mask=RoiMask(), n_seeds=10000, random_seeds=True, rng_seed=42) ########################################################################## #",
"example data # --------------------- # # Retrieves `Stanford HARDI dataset",
"space. tracking_params = dict(seed_mask=RoiMask(), n_seeds=10000, random_seeds=True, rng_seed=42) ########################################################################## # Initialize",
"the standard and callosal templates. myafq = api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), dmriprep='vistasoft',",
"this tracking_params which we will pass to the AFQ object",
"to make this example faster and consume less space. tracking_params",
"pass to the AFQ object # which specifies that we",
"Visualizing bundles and tract profiles: # --------------------------------------- # This would",
"Get some example data # --------------------- # # Retrieves `Stanford",
"using the AFQ API to find callosal bundles using the",
"the AFQ object to use bundles from both # the",
"This would run the script and visualize the bundles using",
"a # new browser window. bundle_html = myafq.viz_bundles(export=True, n_points=50) plotly.io.show(bundle_html[0])",
"op import plotly from AFQ import api from AFQ.mask import",
"\"\"\" ========================== Callosal bundles using AFQ API ========================== An example",
"default bundles list (api.BUNDLES) plus the # callosal bundle list.",
"from both # the standard and callosal templates. myafq =",
"########################################################################## # Set tractography parameters (optional) # --------------------- # We",
"will pass to the AFQ object # which specifies that",
"We only do this to make this example faster and",
"# ------------------------- # # We specify bundle_info as the default",
"We make this tracking_params which we will pass to the",
"= api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), dmriprep='vistasoft', bundle_info=api.BUNDLES + api.CALLOSUM_BUNDLES, tracking_params=tracking_params) ########################################################################## #",
"# Visualizing bundles and tract profiles: # --------------------------------------- # This",
"the AFQ object # which specifies that we want 100,000",
"faster and consume less space. tracking_params = dict(seed_mask=RoiMask(), n_seeds=10000, random_seeds=True,",
"# the standard and callosal templates. myafq = api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'),",
"plus the # callosal bundle list. This tells the AFQ",
"distributed # in the ROIs of every bundle. # #",
"which we will pass to the AFQ object # which",
"profiles: # --------------------------------------- # This would run the script and",
"object # which specifies that we want 100,000 seeds randomly",
"Initialize an AFQ object: # ------------------------- # # We specify",
"object: # ------------------------- # # We specify bundle_info as the",
"to use bundles from both # the standard and callosal",
"api.CALLOSUM_BUNDLES, tracking_params=tracking_params) ########################################################################## # Visualizing bundles and tract profiles: #",
"specify bundle_info as the default bundles list (api.BUNDLES) plus the",
"only do this to make this example faster and consume",
"list (api.BUNDLES) plus the # callosal bundle list. This tells",
"API ========================== An example using the AFQ API to find",
"list. This tells the AFQ object to use bundles from",
"do this to make this example faster and consume less",
"api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), dmriprep='vistasoft', bundle_info=api.BUNDLES + api.CALLOSUM_BUNDLES, tracking_params=tracking_params) ########################################################################## # Visualizing",
"the templates from: http://hdl.handle.net/1773/34926 \"\"\" import os.path as op import",
"import AFQ.data as afd ########################################################################## # Get some example data",
"plotly from AFQ import api from AFQ.mask import RoiMask import",
"========================== Callosal bundles using AFQ API ========================== An example using",
"AFQ object # which specifies that we want 100,000 seeds",
"--------------------------------------- # This would run the script and visualize the",
"as op import plotly from AFQ import api from AFQ.mask",
"========================== An example using the AFQ API to find callosal",
"from AFQ.mask import RoiMask import AFQ.data as afd ########################################################################## #",
"# # We only do this to make this example",
"this to make this example faster and consume less space.",
"automatically open in a # new browser window. bundle_html =",
"run the script and visualize the bundles using the plotly",
"bundles using the plotly # interactive visualization, which should automatically",
"the script and visualize the bundles using the plotly #",
"in a # new browser window. bundle_html = myafq.viz_bundles(export=True, n_points=50)",
"that we want 100,000 seeds randomly distributed # in the",
"import plotly from AFQ import api from AFQ.mask import RoiMask",
"(optional) # --------------------- # We make this tracking_params which we",
"in the ROIs of every bundle. # # We only",
"using the plotly # interactive visualization, which should automatically open",
"--------------------- # We make this tracking_params which we will pass",
"dmriprep='vistasoft', bundle_info=api.BUNDLES + api.CALLOSUM_BUNDLES, tracking_params=tracking_params) ########################################################################## # Visualizing bundles and",
"# We specify bundle_info as the default bundles list (api.BUNDLES)",
"We specify bundle_info as the default bundles list (api.BUNDLES) plus",
"find callosal bundles using the templates from: http://hdl.handle.net/1773/34926 \"\"\" import",
"Callosal bundles using AFQ API ========================== An example using the",
"# callosal bundle list. This tells the AFQ object to",
"An example using the AFQ API to find callosal bundles",
"# Set tractography parameters (optional) # --------------------- # We make",
"bundles using the templates from: http://hdl.handle.net/1773/34926 \"\"\" import os.path as",
"--------------------- # # Retrieves `Stanford HARDI dataset <https://purl.stanford.edu/ng782rw8378>`_. # afd.organize_stanford_data(clear_previous_afq=True)",
"ROIs of every bundle. # # We only do this",
"bundle. # # We only do this to make this",
"########################################################################## # Initialize an AFQ object: # ------------------------- # #",
"tracking_params = dict(seed_mask=RoiMask(), n_seeds=10000, random_seeds=True, rng_seed=42) ########################################################################## # Initialize an",
"callosal bundle list. This tells the AFQ object to use",
"visualization, which should automatically open in a # new browser",
"afd ########################################################################## # Get some example data # --------------------- #",
"to the AFQ object # which specifies that we want",
"bundle_info=api.BUNDLES + api.CALLOSUM_BUNDLES, tracking_params=tracking_params) ########################################################################## # Visualizing bundles and tract",
"bundles using AFQ API ========================== An example using the AFQ",
"# in the ROIs of every bundle. # # We",
"import api from AFQ.mask import RoiMask import AFQ.data as afd",
"make this tracking_params which we will pass to the AFQ",
"dict(seed_mask=RoiMask(), n_seeds=10000, random_seeds=True, rng_seed=42) ########################################################################## # Initialize an AFQ object:",
"we want 100,000 seeds randomly distributed # in the ROIs",
"AFQ import api from AFQ.mask import RoiMask import AFQ.data as",
"API to find callosal bundles using the templates from: http://hdl.handle.net/1773/34926",
"dataset <https://purl.stanford.edu/ng782rw8378>`_. # afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## # Set tractography parameters (optional)",
"# interactive visualization, which should automatically open in a #",
"randomly distributed # in the ROIs of every bundle. #",
"# Initialize an AFQ object: # ------------------------- # # We",
"and tract profiles: # --------------------------------------- # This would run the",
"standard and callosal templates. myafq = api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), dmriprep='vistasoft', bundle_info=api.BUNDLES",
"import os.path as op import plotly from AFQ import api",
"the bundles using the plotly # interactive visualization, which should",
"This tells the AFQ object to use bundles from both",
"as the default bundles list (api.BUNDLES) plus the # callosal",
"AFQ object to use bundles from both # the standard",
"Set tractography parameters (optional) # --------------------- # We make this",
"bundle_info as the default bundles list (api.BUNDLES) plus the #",
"visualize the bundles using the plotly # interactive visualization, which",
"an AFQ object: # ------------------------- # # We specify bundle_info",
"want 100,000 seeds randomly distributed # in the ROIs of",
"every bundle. # # We only do this to make",
"# --------------------- # We make this tracking_params which we will",
"using the templates from: http://hdl.handle.net/1773/34926 \"\"\" import os.path as op",
"which should automatically open in a # new browser window.",
"= dict(seed_mask=RoiMask(), n_seeds=10000, random_seeds=True, rng_seed=42) ########################################################################## # Initialize an AFQ",
"########################################################################## # Get some example data # --------------------- # #",
"n_seeds=10000, random_seeds=True, rng_seed=42) ########################################################################## # Initialize an AFQ object: #",
"plotly # interactive visualization, which should automatically open in a",
"tract profiles: # --------------------------------------- # This would run the script",
"HARDI dataset <https://purl.stanford.edu/ng782rw8378>`_. # afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## # Set tractography parameters",
"# --------------------------------------- # This would run the script and visualize",
"callosal templates. myafq = api.AFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), dmriprep='vistasoft', bundle_info=api.BUNDLES + api.CALLOSUM_BUNDLES,",
"rng_seed=42) ########################################################################## # Initialize an AFQ object: # ------------------------- #"
] |
[
"self.inc = size/4 if self.inc<1: self.inc = 1 self.base =",
"'' else: family = socket.AF_PACKET proto = ETH_P_IP eth =",
"0)) # self.ifname npacket+=1 if not npacket%self.cooldown[0]: time.sleep(self.cooldown[1]) else: break",
"0 self.events['send'].wait() target = hosts[0] while self.events['send'].isSet(): try: target =",
"Generator(object): def __init__(self, size): self.size = size self.inc = size/4",
"in self.ifname: family = socket.AF_INET proto = socket.IPPROTO_RAW eth =",
"nparts host_parts.append((start, end)) start = end else: host_parts.append((start, hosts[1])) break",
"threading.Thread(target=s.run, args=(q, self.event)) self.thread.append(t) t.setDaemon(True) t.start() self.queues[script] = q def",
"ETH_P_IP).pack() sock = socket.socket(family, socket.SOCK_RAW, proto) transport = self.__Transport(srcp, 0)",
"check = True else: ackn = struct.unpack('!L', data[28:32])[0] flags =",
"= 0x0800 # IP protocol ETH_P_ALL = 0x0003 # Every",
"True: if len(host_parts)<n-1: end = start + nparts host_parts.append((start, end))",
"self.ifname: family = socket.AF_INET proto = socket.IPPROTO_RAW eth = ''",
"ssdp:all\\r\\n\\r\\n') } class Generator(object): def __init__(self, size): self.size = size",
"'' else: transport.payload = PAYLOAD.get(transport.dstp, '\\x00\\r\\n\\r\\n') packed = transport.pack(src, dst)",
"sock.sendto(packet, (dec2dot(target), 0)) # self.ifname npacket+=1 if not npacket%self.cooldown[0]: time.sleep(self.cooldown[1])",
"= struct.unpack('!H', data[22:24])[0] if self.stype==socket.IPPROTO_UDP: if dstp==self.srcp: check = True",
"if not npacket%self.cooldown[0]: time.sleep(self.cooldown[1]) else: break logging.info('[SEND] Sent: {} packets'.format(npacket))",
"+ self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src, iph.dst) sock.sendto(packet, (dec2dot(target), 0)) #",
"else: break logging.info('[SEND] Sent: {} packets'.format(npacket)) sock.close() def recv(self): sock",
"return srcp def Extract(packet): src = socket.inet_ntoa(packet[12:16]) srcp = struct.unpack('!H',",
"hosts, n): ''' Split host range into n parts (multithreaded)",
"self.threads, self.events, self.queue, generators def run(self): self.events['send'].set() self.events['recv'].set() for t",
"port in range(port_list[0], port_list[1]): if self.events['send'].isSet(): transport.dstp = port packet",
"while Alive(self.thread): time.sleep(10) class nscan(object): def __init__(self, options): self.options =",
"init(self): generators = [] for h in self.hosts: g =",
"break return srcp def Extract(packet): src = socket.inet_ntoa(packet[12:16]) srcp =",
"= True else: ackn = struct.unpack('!L', data[28:32])[0] flags = struct.unpack('B',",
"1 host_parts = [] start = hosts[0] while True: if",
"DNS Lookup 161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02' '\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06' '\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'), # SNMP GetNextRequest|public|2c version|1.3.6.1.2.1 123:('\\x17\\x00\\x02\\x05'),",
"= Queue.Queue() s = __import__('{}.{}'.format(NSCRIPT_PATH, script), fromlist=[NSCRIPT_PATH]) t = threading.Thread(target=s.run,",
"__Transport(self, src, dst=0): if self.stype==socket.IPPROTO_TCP: transport = tcp.TCP(src, dst) transport.seqn",
"= udp.UDP(src, dst) return transport def __Pack(self, transport, src, dst):",
"self.inc return self.num def next_base(self): self.base = 0 self.base-= self.index",
"in thread_list: if t.isAlive(): alive = True break return alive",
"= options.count self.cooldown = options.cooldown self.queue = Queue.Queue() if options.stype.upper()=='U':",
"= struct.unpack('B', data[33])[0] & 0b010010 # SYN-ACK if dstp==self.srcp and",
"self.sport: self.sport.append(srcp) break return srcp def Extract(packet): src = socket.inet_ntoa(packet[12:16])",
"iph.dst) #tcph.pack(iph.src, iph.dst) sock.sendto(packet, (dec2dot(target), 0)) # self.ifname npacket+=1 if",
"save bandwidth) 1900:('M-SEARCH * HTTP/1.1\\r\\nHOST: 192.168.127.12:1900\\r\\n' 'MAN: \"ssdp:discover\"\\r\\nMX: 2\\r\\nST: ssdp:all\\r\\n\\r\\n')",
"sa_ll = sock.recvfrom(65535) if self.__CookieCheck(data): self.queue.put(Extract(data)) counter += 1 if",
"def send(self, hosts, srcp, gen): if 'ppp' in self.ifname: family",
"self.events['send'].set() self.events['recv'].set() for t in self.threads['send']: t.start() self.threads['recv'].start() def send(self,",
"g.resume(*self.options.indexes[i]) i+=1 return self.threads, self.events, self.queue, generators def run(self): self.events['send'].set()",
"num, index): self.size = size self.inc = inc self.base =",
"2\\r\\nST: ssdp:all\\r\\n\\r\\n') } class Generator(object): def __init__(self, size): self.size =",
"socket.IPPROTO_TCP self.events = { 'send': threading.Event(), 'recv': threading.Event()} self.threads =",
"= 'nscript' # NSCRIPT PATH PAYLOAD = { 53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06' 'google\\x03com\\x00\\x00\\x01\\x00\\x01'),",
"38 null bytes (just to save bandwidth) 1900:('M-SEARCH * HTTP/1.1\\r\\nHOST:",
"logging.info('[RECV] Received: {} packets'.format(counter)) def split(self, hosts, n): ''' Split",
"0 for g in generators: g.resume(*self.options.indexes[i]) i+=1 return self.threads, self.events,",
"self def next(self): if (self.num+self.inc)>=self.size: self.next_index() self.next_base() self.num = self.num",
"(self.num+self.inc)>=self.size: self.next_index() self.next_base() self.num = self.num + self.inc return self.num",
"= socket.IPPROTO_TCP self.events = { 'send': threading.Event(), 'recv': threading.Event()} self.threads",
"socket.socket(socket.AF_INET, socket.SOCK_RAW, self.stype) sock.bind(('', self.srcp)) sock.settimeout(5) self.events['recv'].wait() counter = 0",
"imports self.event = threading.Event() self.queues = {} self.thread = []",
"options.diface self.banner = options.banner self.count = options.count self.cooldown = options.cooldown",
"self.index def resume(self, size, inc, base, num, index): self.size =",
"Extract(packet): src = socket.inet_ntoa(packet[12:16]) srcp = struct.unpack('!H', packet[20:22])[0] return src,",
"Feed(self, host, port): for scr in self.imports: for r in",
"GetNextRequest|public|2c version|1.3.6.1.2.1 123:('\\x17\\x00\\x02\\x05'), # NTP systats commands lacks 38 null",
"= hosts[0] while self.events['send'].isSet(): try: target = hosts[0] + gen.next()",
"for h in self.hosts: g = Generator(h[1]-h[0]) generators.append(g) t =",
"return self.num def next_base(self): self.base = 0 self.base-= self.index self.num",
"self.thread.append(t) t.setDaemon(True) t.start() self.queues[script] = q def Feed(self, host, port):",
"False for t in thread_list: if t.isAlive(): alive = True",
"hosts[0] + gen.next() iph = ip.IP(self.diface, dec2dot(target), self.stype) except StopIteration:",
"of hosts nparts = nhosts/n + 1 host_parts = []",
"-self.inc self.num = self.base self.index = 0 def __iter__(self): return",
"socket.IPPROTO_UDP else: self.stype = socket.IPPROTO_TCP self.events = { 'send': threading.Event(),",
"self.events, self.queue, generators def run(self): self.events['send'].set() self.events['recv'].set() for t in",
"if port in xrange(r[0], r[1]): self.queues[scr].put((host, port)) break def Cleanup(self):",
"# Every packet NSCRIPT_PATH = 'nscript' # NSCRIPT PATH PAYLOAD",
"123:('\\x17\\x00\\x02\\x05'), # NTP systats commands lacks 38 null bytes (just",
"class nscan(object): def __init__(self, options): self.options = options self.hosts =",
"Alive(self.thread): time.sleep(10) class nscan(object): def __init__(self, options): self.options = options",
"t = threading.Thread(target=self.recv) t.setDaemon(True) self.threads['recv'] = t if 'resume' in",
"self.ports: for port in range(port_list[0], port_list[1]): if self.events['send'].isSet(): transport.dstp =",
"socket.SOCK_RAW, proto) transport = self.__Transport(srcp, 0) npacket = 0 self.events['send'].wait()",
"NSCRIPT PATH PAYLOAD = { 53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06' 'google\\x03com\\x00\\x00\\x01\\x00\\x01'), # 'google.com' DNS",
"self.stype==socket.IPPROTO_TCP: transport.payload = '' else: transport.payload = PAYLOAD.get(transport.dstp, '\\x00\\r\\n\\r\\n') packed",
"to save bandwidth) 1900:('M-SEARCH * HTTP/1.1\\r\\nHOST: 192.168.127.12:1900\\r\\n' 'MAN: \"ssdp:discover\"\\r\\nMX: 2\\r\\nST:",
"except StopIteration: break for port_list in self.ports: for port in",
"gen): if 'ppp' in self.ifname: family = socket.AF_INET proto =",
"break return host_parts def PickPort(self): while True: srcp = random.randrange(10000,",
"t = threading.Thread(target=self.send, args=(h, self.srcp, g)) t.setDaemon(True) self.threads['send'].append(t) t =",
"0xDEADC0DE else: transport = udp.UDP(src, dst) return transport def __Pack(self,",
"npacket+=1 if not npacket%self.cooldown[0]: time.sleep(self.cooldown[1]) else: break logging.info('[SEND] Sent: {}",
"parts (multithreaded) ''' nhosts = hosts[1] - hosts[0] # number",
"# SNMP GetNextRequest|public|2c version|1.3.6.1.2.1 123:('\\x17\\x00\\x02\\x05'), # NTP systats commands lacks",
"def __init__(self, size): self.size = size self.inc = size/4 if",
"else: family = socket.AF_PACKET proto = ETH_P_IP eth = ethernet.ETHER(mac2byte(self.smac),",
"self.queue, generators def run(self): self.events['send'].set() self.events['recv'].set() for t in self.threads['send']:",
"transport.payload = PAYLOAD.get(transport.dstp, '\\x00\\r\\n\\r\\n') packed = transport.pack(src, dst) return packed",
"PAYLOAD.get(transport.dstp, '\\x00\\r\\n\\r\\n') packed = transport.pack(src, dst) return packed + transport.payload",
"time import Queue import random import socket import struct import",
"src, dst): if self.stype==socket.IPPROTO_TCP: transport.payload = '' else: transport.payload =",
"generators.append(g) t = threading.Thread(target=self.send, args=(h, self.srcp, g)) t.setDaemon(True) self.threads['send'].append(t) t",
"self.num def next_base(self): self.base = 0 self.base-= self.index self.num =",
"def Cleanup(self): while Alive(self.thread): time.sleep(10) class nscan(object): def __init__(self, options):",
"range(port_list[0], port_list[1]): if self.events['send'].isSet(): transport.dstp = port packet = eth",
"transport = udp.UDP(src, dst) return transport def __Pack(self, transport, src,",
"suspend(self): return self.size, self.inc, self.base, self.num, self.index def resume(self, size,",
"self.diface = options.diface self.banner = options.banner self.count = options.count self.cooldown",
"= False for t in thread_list: if t.isAlive(): alive =",
"sock.bind(('', self.srcp)) sock.settimeout(5) self.events['recv'].wait() counter = 0 while self.events['recv'].isSet(): try:",
"= 0 while self.events['recv'].isSet(): try: data, sa_ll = sock.recvfrom(65535) if",
"nhosts = hosts[1] - hosts[0] # number of hosts nparts",
"= end else: host_parts.append((start, hosts[1])) break return host_parts def PickPort(self):",
"Cleanup(self): while Alive(self.thread): time.sleep(10) class nscan(object): def __init__(self, options): self.options",
"self.count = options.count self.cooldown = options.cooldown self.queue = Queue.Queue() if",
"None} def __Transport(self, src, dst=0): if self.stype==socket.IPPROTO_TCP: transport = tcp.TCP(src,",
"= 0x0003 # Every packet NSCRIPT_PATH = 'nscript' # NSCRIPT",
"transport, src, dst): if self.stype==socket.IPPROTO_TCP: transport.payload = '' else: transport.payload",
"= False dstp = struct.unpack('!H', data[22:24])[0] if self.stype==socket.IPPROTO_UDP: if dstp==self.srcp:",
"not in self.sport: self.sport.append(srcp) break return srcp def Extract(packet): src",
"+ transport.payload def __CookieCheck(self, data): check = False dstp =",
"= socket.AF_PACKET proto = ETH_P_IP eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack()",
"q = Queue.Queue() s = __import__('{}.{}'.format(NSCRIPT_PATH, script), fromlist=[NSCRIPT_PATH]) t =",
"if options.stype.upper()=='U': self.stype = socket.IPPROTO_UDP else: self.stype = socket.IPPROTO_TCP self.events",
"target = hosts[0] while self.events['send'].isSet(): try: target = hosts[0] +",
"nparts = nhosts/n + 1 host_parts = [] start =",
"next_base(self): self.base = 0 self.base-= self.index self.num = self.base def",
"data[22:24])[0] if self.stype==socket.IPPROTO_UDP: if dstp==self.srcp: check = True else: ackn",
"target = hosts[0] + gen.next() iph = ip.IP(self.diface, dec2dot(target), self.stype)",
"def next(self): if (self.num+self.inc)>=self.size: self.next_index() self.next_base() self.num = self.num +",
"n): ''' Split host range into n parts (multithreaded) '''",
"0b010010 # SYN-ACK if dstp==self.srcp and ackn==0xDEADC0DF and flags==18: check",
"proto = ETH_P_IP eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack() sock =",
"ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack() sock = socket.socket(family, socket.SOCK_RAW, proto) transport =",
"options.stype.upper()=='U': self.stype = socket.IPPROTO_UDP else: self.stype = socket.IPPROTO_TCP self.events =",
"53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06' 'google\\x03com\\x00\\x00\\x01\\x00\\x01'), # 'google.com' DNS Lookup 161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02' '\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06' '\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'), #",
"options.smac self.dmac = options.dmac self.ifname = options.ifname self.siface = options.siface",
"self.event)) self.thread.append(t) t.setDaemon(True) t.start() self.queues[script] = q def Feed(self, host,",
"t = threading.Thread(target=s.run, args=(q, self.event)) self.thread.append(t) t.setDaemon(True) t.start() self.queues[script] =",
"if 'ppp' in self.ifname: family = socket.AF_INET proto = socket.IPPROTO_RAW",
"class Generator(object): def __init__(self, size): self.size = size self.inc =",
"options self.hosts = self.split(options.hosts, options.threads) self.ports = options.ports self.srcp =",
"hosts, srcp, gen): if 'ppp' in self.ifname: family = socket.AF_INET",
"from protocol import ethernet, ip, tcp, udp ETH_P_IP = 0x0800",
"sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.stype) sock.bind(('', self.srcp)) sock.settimeout(5) self.events['recv'].wait() counter",
"self.index self.num = self.base def next_index(self): self.index+=1 if self.index>=self.inc: raise",
"in self.imports: for r in self.imports[scr]: if port in xrange(r[0],",
"self.num = num self.index = index class ScriptEngine(object): def __init__(self,",
"host_parts = [] start = hosts[0] while True: if len(host_parts)<n-1:",
"= nhosts/n + 1 host_parts = [] start = hosts[0]",
"for port in range(port_list[0], port_list[1]): if self.events['send'].isSet(): transport.dstp = port",
"socket.AF_INET proto = socket.IPPROTO_RAW eth = '' else: family =",
"tcp, udp ETH_P_IP = 0x0800 # IP protocol ETH_P_ALL =",
"self.stype) except StopIteration: break for port_list in self.ports: for port",
"check if thread is alive ''' alive = False for",
"size self.inc = size/4 if self.inc<1: self.inc = 1 self.base",
"self.events['send'].isSet(): transport.dstp = port packet = eth + iph.pack() +",
"packed = transport.pack(src, dst) return packed + transport.payload def __CookieCheck(self,",
"proto = socket.IPPROTO_RAW eth = '' else: family = socket.AF_PACKET",
"self.banner = options.banner self.count = options.count self.cooldown = options.cooldown self.queue",
"# self.ifname npacket+=1 if not npacket%self.cooldown[0]: time.sleep(self.cooldown[1]) else: break logging.info('[SEND]",
"i+=1 return self.threads, self.events, self.queue, generators def run(self): self.events['send'].set() self.events['recv'].set()",
"srcp not in self.sport: self.sport.append(srcp) break return srcp def Extract(packet):",
"t.start() self.queues[script] = q def Feed(self, host, port): for scr",
"Load(self): for script in self.imports: q = Queue.Queue() s =",
"self.base def next_index(self): self.index+=1 if self.index>=self.inc: raise StopIteration def suspend(self):",
"time.sleep(self.cooldown[1]) else: break logging.info('[SEND] Sent: {} packets'.format(npacket)) sock.close() def recv(self):",
"socket import struct import logging import threading from convert import",
"break except socket.timeout: continue sock.close() logging.info('[RECV] Received: {} packets'.format(counter)) def",
"in self.imports[scr]: if port in xrange(r[0], r[1]): self.queues[scr].put((host, port)) break",
"not npacket%self.cooldown[0]: time.sleep(self.cooldown[1]) else: break logging.info('[SEND] Sent: {} packets'.format(npacket)) sock.close()",
"self.base self.index = 0 def __iter__(self): return self def next(self):",
"{} self.thread = [] def Load(self): for script in self.imports:",
"struct.unpack('B', data[33])[0] & 0b010010 # SYN-ACK if dstp==self.srcp and ackn==0xDEADC0DF",
"= tcp.TCP(src, dst) transport.seqn = 0xDEADC0DE else: transport = udp.UDP(src,",
"return src, srcp def Alive(thread_list): ''' check if thread is",
"= index class ScriptEngine(object): def __init__(self, imports): self.imports = imports",
"g = Generator(h[1]-h[0]) generators.append(g) t = threading.Thread(target=self.send, args=(h, self.srcp, g))",
"s = __import__('{}.{}'.format(NSCRIPT_PATH, script), fromlist=[NSCRIPT_PATH]) t = threading.Thread(target=s.run, args=(q, self.event))",
"socket.timeout: continue sock.close() logging.info('[RECV] Received: {} packets'.format(counter)) def split(self, hosts,",
"+ self.inc return self.num def next_base(self): self.base = 0 self.base-=",
"self.dmac = options.dmac self.ifname = options.ifname self.siface = options.siface self.diface",
"= { 'send': threading.Event(), 'recv': threading.Event()} self.threads = { 'send':",
"ScriptEngine(object): def __init__(self, imports): self.imports = imports self.event = threading.Event()",
"self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src, iph.dst) sock.sendto(packet, (dec2dot(target), 0)) # self.ifname",
"self.events['send'].clear() break except socket.timeout: continue sock.close() logging.info('[RECV] Received: {} packets'.format(counter))",
"= self.__Transport(srcp, 0) npacket = 0 self.events['send'].wait() target = hosts[0]",
"and flags==18: check = True return check def init(self): generators",
"hosts[0] while True: if len(host_parts)<n-1: end = start + nparts",
"else: transport = udp.UDP(src, dst) return transport def __Pack(self, transport,",
"for r in self.imports[scr]: if port in xrange(r[0], r[1]): self.queues[scr].put((host,",
"} class Generator(object): def __init__(self, size): self.size = size self.inc",
"self.queues = {} self.thread = [] def Load(self): for script",
"= threading.Thread(target=s.run, args=(q, self.event)) self.thread.append(t) t.setDaemon(True) t.start() self.queues[script] = q",
"struct.unpack('!L', data[28:32])[0] flags = struct.unpack('B', data[33])[0] & 0b010010 # SYN-ACK",
"self.imports[scr]: if port in xrange(r[0], r[1]): self.queues[scr].put((host, port)) break def",
"0 def __iter__(self): return self def next(self): if (self.num+self.inc)>=self.size: self.next_index()",
"eth = '' else: family = socket.AF_PACKET proto = ETH_P_IP",
"random.randint(1, 65535)#self.PickPort() # source port self.smac = options.smac self.dmac =",
"#tcph.pack(iph.src, iph.dst) sock.sendto(packet, (dec2dot(target), 0)) # self.ifname npacket+=1 if not",
"self.num = self.base def next_index(self): self.index+=1 if self.index>=self.inc: raise StopIteration",
"self.stype==socket.IPPROTO_UDP: if dstp==self.srcp: check = True else: ackn = struct.unpack('!L',",
"import socket import struct import logging import threading from convert",
"[] for h in self.hosts: g = Generator(h[1]-h[0]) generators.append(g) t",
"= eth + iph.pack() + self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src, iph.dst)",
"1 self.base = -self.inc self.num = self.base self.index = 0",
"transport.seqn = 0xDEADC0DE else: transport = udp.UDP(src, dst) return transport",
"fromlist=[NSCRIPT_PATH]) t = threading.Thread(target=s.run, args=(q, self.event)) self.thread.append(t) t.setDaemon(True) t.start() self.queues[script]",
"= [] def Load(self): for script in self.imports: q =",
"convert import * from protocol import ethernet, ip, tcp, udp",
"= options.diface self.banner = options.banner self.count = options.count self.cooldown =",
"port_list in self.ports: for port in range(port_list[0], port_list[1]): if self.events['send'].isSet():",
"self.cooldown = options.cooldown self.queue = Queue.Queue() if options.stype.upper()=='U': self.stype =",
"= hosts[0] while True: if len(host_parts)<n-1: end = start +",
"tcp.TCP(src, dst) transport.seqn = 0xDEADC0DE else: transport = udp.UDP(src, dst)",
"split(self, hosts, n): ''' Split host range into n parts",
"def suspend(self): return self.size, self.inc, self.base, self.num, self.index def resume(self,",
"0x0003 # Every packet NSCRIPT_PATH = 'nscript' # NSCRIPT PATH",
"dstp==self.srcp: check = True else: ackn = struct.unpack('!L', data[28:32])[0] flags",
"bandwidth) 1900:('M-SEARCH * HTTP/1.1\\r\\nHOST: 192.168.127.12:1900\\r\\n' 'MAN: \"ssdp:discover\"\\r\\nMX: 2\\r\\nST: ssdp:all\\r\\n\\r\\n') }",
"options.dmac self.ifname = options.ifname self.siface = options.siface self.diface = options.diface",
"family = socket.AF_INET proto = socket.IPPROTO_RAW eth = '' else:",
"in self.threads['send']: t.start() self.threads['recv'].start() def send(self, hosts, srcp, gen): if",
"= __import__('{}.{}'.format(NSCRIPT_PATH, script), fromlist=[NSCRIPT_PATH]) t = threading.Thread(target=s.run, args=(q, self.event)) self.thread.append(t)",
"= size/4 if self.inc<1: self.inc = 1 self.base = -self.inc",
"= PAYLOAD.get(transport.dstp, '\\x00\\r\\n\\r\\n') packed = transport.pack(src, dst) return packed +",
"= options.banner self.count = options.count self.cooldown = options.cooldown self.queue =",
"0) npacket = 0 self.events['send'].wait() target = hosts[0] while self.events['send'].isSet():",
"- hosts[0] # number of hosts nparts = nhosts/n +",
"= self.base self.index = 0 def __iter__(self): return self def",
"self.threads['send'].append(t) t = threading.Thread(target=self.recv) t.setDaemon(True) self.threads['recv'] = t if 'resume'",
"import random import socket import struct import logging import threading",
"self.split(options.hosts, options.threads) self.ports = options.ports self.srcp = random.randint(1, 65535)#self.PickPort() #",
"Received: {} packets'.format(counter)) def split(self, hosts, n): ''' Split host",
"counter = 0 while self.events['recv'].isSet(): try: data, sa_ll = sock.recvfrom(65535)",
"generators = [] for h in self.hosts: g = Generator(h[1]-h[0])",
"(multithreaded) ''' nhosts = hosts[1] - hosts[0] # number of",
"threading.Event() self.queues = {} self.thread = [] def Load(self): for",
"t in thread_list: if t.isAlive(): alive = True break return",
"for t in thread_list: if t.isAlive(): alive = True break",
"self.events['recv'].wait() counter = 0 while self.events['recv'].isSet(): try: data, sa_ll =",
"args=(h, self.srcp, g)) t.setDaemon(True) self.threads['send'].append(t) t = threading.Thread(target=self.recv) t.setDaemon(True) self.threads['recv']",
"self.base-= self.index self.num = self.base def next_index(self): self.index+=1 if self.index>=self.inc:",
"self.ports = options.ports self.srcp = random.randint(1, 65535)#self.PickPort() # source port",
"check def init(self): generators = [] for h in self.hosts:",
"= socket.IPPROTO_UDP else: self.stype = socket.IPPROTO_TCP self.events = { 'send':",
"dst) return transport def __Pack(self, transport, src, dst): if self.stype==socket.IPPROTO_TCP:",
"next_index(self): self.index+=1 if self.index>=self.inc: raise StopIteration def suspend(self): return self.size,",
"import * from protocol import ethernet, ip, tcp, udp ETH_P_IP",
"return check def init(self): generators = [] for h in",
"self.index = 0 def __iter__(self): return self def next(self): if",
"source port self.smac = options.smac self.dmac = options.dmac self.ifname =",
"dst) return packed + transport.payload def __CookieCheck(self, data): check =",
"__Pack(self, transport, src, dst): if self.stype==socket.IPPROTO_TCP: transport.payload = '' else:",
"HTTP/1.1\\r\\nHOST: 192.168.127.12:1900\\r\\n' 'MAN: \"ssdp:discover\"\\r\\nMX: 2\\r\\nST: ssdp:all\\r\\n\\r\\n') } class Generator(object): def",
"__init__(self, size): self.size = size self.inc = size/4 if self.inc<1:",
"self.events['recv'].isSet(): try: data, sa_ll = sock.recvfrom(65535) if self.__CookieCheck(data): self.queue.put(Extract(data)) counter",
"version|1.3.6.1.2.1 123:('\\x17\\x00\\x02\\x05'), # NTP systats commands lacks 38 null bytes",
"options.ifname self.siface = options.siface self.diface = options.diface self.banner = options.banner",
"random import socket import struct import logging import threading from",
"packet NSCRIPT_PATH = 'nscript' # NSCRIPT PATH PAYLOAD = {",
"= threading.Event() self.queues = {} self.thread = [] def Load(self):",
"transport.payload def __CookieCheck(self, data): check = False dstp = struct.unpack('!H',",
"+ 1 host_parts = [] start = hosts[0] while True:",
"'recv': threading.Event()} self.threads = { 'send': [], 'recv': None} def",
"src = socket.inet_ntoa(packet[12:16]) srcp = struct.unpack('!H', packet[20:22])[0] return src, srcp",
"len(host_parts)<n-1: end = start + nparts host_parts.append((start, end)) start =",
"port): for scr in self.imports: for r in self.imports[scr]: if",
"= socket.socket(family, socket.SOCK_RAW, proto) transport = self.__Transport(srcp, 0) npacket =",
"# number of hosts nparts = nhosts/n + 1 host_parts",
"= socket.socket(socket.AF_INET, socket.SOCK_RAW, self.stype) sock.bind(('', self.srcp)) sock.settimeout(5) self.events['recv'].wait() counter =",
"self.threads = { 'send': [], 'recv': None} def __Transport(self, src,",
"bytes (just to save bandwidth) 1900:('M-SEARCH * HTTP/1.1\\r\\nHOST: 192.168.127.12:1900\\r\\n' 'MAN:",
"self.size, self.inc, self.base, self.num, self.index def resume(self, size, inc, base,",
"= sock.recvfrom(65535) if self.__CookieCheck(data): self.queue.put(Extract(data)) counter += 1 if counter==self.count:",
"transport = tcp.TCP(src, dst) transport.seqn = 0xDEADC0DE else: transport =",
"= port packet = eth + iph.pack() + self.__Pack(transport, iph.src,",
"import Queue import random import socket import struct import logging",
"host_parts def PickPort(self): while True: srcp = random.randrange(10000, 65535) if",
"udp.UDP(src, dst) return transport def __Pack(self, transport, src, dst): if",
"# NSCRIPT PATH PAYLOAD = { 53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06' 'google\\x03com\\x00\\x00\\x01\\x00\\x01'), # 'google.com'",
"''' nhosts = hosts[1] - hosts[0] # number of hosts",
"ip.IP(self.diface, dec2dot(target), self.stype) except StopIteration: break for port_list in self.ports:",
"sock.close() def recv(self): sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.stype) sock.bind(('', self.srcp))",
"sock = socket.socket(family, socket.SOCK_RAW, proto) transport = self.__Transport(srcp, 0) npacket",
"= options.smac self.dmac = options.dmac self.ifname = options.ifname self.siface =",
"options.siface self.diface = options.diface self.banner = options.banner self.count = options.count",
"start = hosts[0] while True: if len(host_parts)<n-1: end = start",
"hosts nparts = nhosts/n + 1 host_parts = [] start",
"self.srcp)) sock.settimeout(5) self.events['recv'].wait() counter = 0 while self.events['recv'].isSet(): try: data,",
"if self.stype==socket.IPPROTO_TCP: transport = tcp.TCP(src, dst) transport.seqn = 0xDEADC0DE else:",
"host_parts.append((start, hosts[1])) break return host_parts def PickPort(self): while True: srcp",
"t.setDaemon(True) self.threads['recv'] = t if 'resume' in dir(self.options): i =",
"def __CookieCheck(self, data): check = False dstp = struct.unpack('!H', data[22:24])[0]",
"StopIteration def suspend(self): return self.size, self.inc, self.base, self.num, self.index def",
"imports): self.imports = imports self.event = threading.Event() self.queues = {}",
"t.start() self.threads['recv'].start() def send(self, hosts, srcp, gen): if 'ppp' in",
"dec2dot(target), self.stype) except StopIteration: break for port_list in self.ports: for",
"iph = ip.IP(self.diface, dec2dot(target), self.stype) except StopIteration: break for port_list",
"inc self.base = base self.num = num self.index = index",
"StopIteration: break for port_list in self.ports: for port in range(port_list[0],",
"break logging.info('[SEND] Sent: {} packets'.format(npacket)) sock.close() def recv(self): sock =",
"self.num = self.base self.index = 0 def __iter__(self): return self",
"port)) break def Cleanup(self): while Alive(self.thread): time.sleep(10) class nscan(object): def",
"inc, base, num, index): self.size = size self.inc = inc",
"= options.ports self.srcp = random.randint(1, 65535)#self.PickPort() # source port self.smac",
"options.ports self.srcp = random.randint(1, 65535)#self.PickPort() # source port self.smac =",
"Queue import random import socket import struct import logging import",
"sock.close() logging.info('[RECV] Received: {} packets'.format(counter)) def split(self, hosts, n): '''",
"systats commands lacks 38 null bytes (just to save bandwidth)",
"= [] for h in self.hosts: g = Generator(h[1]-h[0]) generators.append(g)",
"script in self.imports: q = Queue.Queue() s = __import__('{}.{}'.format(NSCRIPT_PATH, script),",
"for scr in self.imports: for r in self.imports[scr]: if port",
"self.smac = options.smac self.dmac = options.dmac self.ifname = options.ifname self.siface",
"dstp==self.srcp and ackn==0xDEADC0DF and flags==18: check = True return check",
"self.event = threading.Event() self.queues = {} self.thread = [] def",
"if self.stype==socket.IPPROTO_UDP: if dstp==self.srcp: check = True else: ackn =",
"Queue.Queue() if options.stype.upper()=='U': self.stype = socket.IPPROTO_UDP else: self.stype = socket.IPPROTO_TCP",
"= hosts[1] - hosts[0] # number of hosts nparts =",
"'nscript' # NSCRIPT PATH PAYLOAD = { 53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06' 'google\\x03com\\x00\\x00\\x01\\x00\\x01'), #",
"Queue.Queue() s = __import__('{}.{}'.format(NSCRIPT_PATH, script), fromlist=[NSCRIPT_PATH]) t = threading.Thread(target=s.run, args=(q,",
"if self.events['send'].isSet(): transport.dstp = port packet = eth + iph.pack()",
"srcp def Extract(packet): src = socket.inet_ntoa(packet[12:16]) srcp = struct.unpack('!H', packet[20:22])[0]",
"IP protocol ETH_P_ALL = 0x0003 # Every packet NSCRIPT_PATH =",
"self.threads['recv'] = t if 'resume' in dir(self.options): i = 0",
"'send': threading.Event(), 'recv': threading.Event()} self.threads = { 'send': [], 'recv':",
"data): check = False dstp = struct.unpack('!H', data[22:24])[0] if self.stype==socket.IPPROTO_UDP:",
"Lookup 161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02' '\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06' '\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'), # SNMP GetNextRequest|public|2c version|1.3.6.1.2.1 123:('\\x17\\x00\\x02\\x05'), #",
"self.index>=self.inc: raise StopIteration def suspend(self): return self.size, self.inc, self.base, self.num,",
"alive ''' alive = False for t in thread_list: if",
"for g in generators: g.resume(*self.options.indexes[i]) i+=1 return self.threads, self.events, self.queue,",
"= { 'send': [], 'recv': None} def __Transport(self, src, dst=0):",
"in xrange(r[0], r[1]): self.queues[scr].put((host, port)) break def Cleanup(self): while Alive(self.thread):",
"hosts[0] # number of hosts nparts = nhosts/n + 1",
"nhosts/n + 1 host_parts = [] start = hosts[0] while",
"def __Pack(self, transport, src, dst): if self.stype==socket.IPPROTO_TCP: transport.payload = ''",
"= self.num + self.inc return self.num def next_base(self): self.base =",
"= threading.Thread(target=self.recv) t.setDaemon(True) self.threads['recv'] = t if 'resume' in dir(self.options):",
"self.__CookieCheck(data): self.queue.put(Extract(data)) counter += 1 if counter==self.count: self.events['send'].clear() break except",
"thread is alive ''' alive = False for t in",
"= num self.index = index class ScriptEngine(object): def __init__(self, imports):",
"0 while self.events['recv'].isSet(): try: data, sa_ll = sock.recvfrom(65535) if self.__CookieCheck(data):",
"self.queue = Queue.Queue() if options.stype.upper()=='U': self.stype = socket.IPPROTO_UDP else: self.stype",
"import time import Queue import random import socket import struct",
"return self.size, self.inc, self.base, self.num, self.index def resume(self, size, inc,",
"'google.com' DNS Lookup 161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02' '\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06' '\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'), # SNMP GetNextRequest|public|2c version|1.3.6.1.2.1",
"= socket.AF_INET proto = socket.IPPROTO_RAW eth = '' else: family",
"'resume' in dir(self.options): i = 0 for g in generators:",
"iph.src, iph.dst) #tcph.pack(iph.src, iph.dst) sock.sendto(packet, (dec2dot(target), 0)) # self.ifname npacket+=1",
"= self.base def next_index(self): self.index+=1 if self.index>=self.inc: raise StopIteration def",
"end else: host_parts.append((start, hosts[1])) break return host_parts def PickPort(self): while",
"start = end else: host_parts.append((start, hosts[1])) break return host_parts def",
"struct import logging import threading from convert import * from",
"return host_parts def PickPort(self): while True: srcp = random.randrange(10000, 65535)",
"data[28:32])[0] flags = struct.unpack('B', data[33])[0] & 0b010010 # SYN-ACK if",
"transport.dstp = port packet = eth + iph.pack() + self.__Pack(transport,",
"ackn==0xDEADC0DF and flags==18: check = True return check def init(self):",
"if self.stype==socket.IPPROTO_TCP: transport.payload = '' else: transport.payload = PAYLOAD.get(transport.dstp, '\\x00\\r\\n\\r\\n')",
"scr in self.imports: for r in self.imports[scr]: if port in",
"options.banner self.count = options.count self.cooldown = options.cooldown self.queue = Queue.Queue()",
"PickPort(self): while True: srcp = random.randrange(10000, 65535) if srcp not",
"= {} self.thread = [] def Load(self): for script in",
"next(self): if (self.num+self.inc)>=self.size: self.next_index() self.next_base() self.num = self.num + self.inc",
"1 if counter==self.count: self.events['send'].clear() break except socket.timeout: continue sock.close() logging.info('[RECV]",
"= [] start = hosts[0] while True: if len(host_parts)<n-1: end",
"Every packet NSCRIPT_PATH = 'nscript' # NSCRIPT PATH PAYLOAD =",
"= self.split(options.hosts, options.threads) self.ports = options.ports self.srcp = random.randint(1, 65535)#self.PickPort()",
"__init__(self, imports): self.imports = imports self.event = threading.Event() self.queues =",
"[], 'recv': None} def __Transport(self, src, dst=0): if self.stype==socket.IPPROTO_TCP: transport",
"Split host range into n parts (multithreaded) ''' nhosts =",
"{} packets'.format(counter)) def split(self, hosts, n): ''' Split host range",
"= 0 for g in generators: g.resume(*self.options.indexes[i]) i+=1 return self.threads,",
"def resume(self, size, inc, base, num, index): self.size = size",
"def recv(self): sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.stype) sock.bind(('', self.srcp)) sock.settimeout(5)",
"transport def __Pack(self, transport, src, dst): if self.stype==socket.IPPROTO_TCP: transport.payload =",
"g)) t.setDaemon(True) self.threads['send'].append(t) t = threading.Thread(target=self.recv) t.setDaemon(True) self.threads['recv'] = t",
"= 0 self.base-= self.index self.num = self.base def next_index(self): self.index+=1",
"transport.pack(src, dst) return packed + transport.payload def __CookieCheck(self, data): check",
"= 0 def __iter__(self): return self def next(self): if (self.num+self.inc)>=self.size:",
"= hosts[0] + gen.next() iph = ip.IP(self.diface, dec2dot(target), self.stype) except",
"socket.socket(family, socket.SOCK_RAW, proto) transport = self.__Transport(srcp, 0) npacket = 0",
"in self.ports: for port in range(port_list[0], port_list[1]): if self.events['send'].isSet(): transport.dstp",
"xrange(r[0], r[1]): self.queues[scr].put((host, port)) break def Cleanup(self): while Alive(self.thread): time.sleep(10)",
"sock.recvfrom(65535) if self.__CookieCheck(data): self.queue.put(Extract(data)) counter += 1 if counter==self.count: self.events['send'].clear()",
"src, dst=0): if self.stype==socket.IPPROTO_TCP: transport = tcp.TCP(src, dst) transport.seqn =",
"'google\\x03com\\x00\\x00\\x01\\x00\\x01'), # 'google.com' DNS Lookup 161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02' '\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06' '\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'), # SNMP",
"protocol import ethernet, ip, tcp, udp ETH_P_IP = 0x0800 #",
"0x0800 # IP protocol ETH_P_ALL = 0x0003 # Every packet",
"self.imports = imports self.event = threading.Event() self.queues = {} self.thread",
"self.stype==socket.IPPROTO_TCP: transport = tcp.TCP(src, dst) transport.seqn = 0xDEADC0DE else: transport",
"gen.next() iph = ip.IP(self.diface, dec2dot(target), self.stype) except StopIteration: break for",
"in self.sport: self.sport.append(srcp) break return srcp def Extract(packet): src =",
"for script in self.imports: q = Queue.Queue() s = __import__('{}.{}'.format(NSCRIPT_PATH,",
"= options.ifname self.siface = options.siface self.diface = options.diface self.banner =",
"else: self.stype = socket.IPPROTO_TCP self.events = { 'send': threading.Event(), 'recv':",
"iph.dst) sock.sendto(packet, (dec2dot(target), 0)) # self.ifname npacket+=1 if not npacket%self.cooldown[0]:",
"srcp = struct.unpack('!H', packet[20:22])[0] return src, srcp def Alive(thread_list): '''",
"if (self.num+self.inc)>=self.size: self.next_index() self.next_base() self.num = self.num + self.inc return",
"import ethernet, ip, tcp, udp ETH_P_IP = 0x0800 # IP",
"self.next_base() self.num = self.num + self.inc return self.num def next_base(self):",
"(dec2dot(target), 0)) # self.ifname npacket+=1 if not npacket%self.cooldown[0]: time.sleep(self.cooldown[1]) else:",
"{} packets'.format(npacket)) sock.close() def recv(self): sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.stype)",
"while True: if len(host_parts)<n-1: end = start + nparts host_parts.append((start,",
"def __init__(self, imports): self.imports = imports self.event = threading.Event() self.queues",
"hosts[1] - hosts[0] # number of hosts nparts = nhosts/n",
"self.stype = socket.IPPROTO_TCP self.events = { 'send': threading.Event(), 'recv': threading.Event()}",
"= random.randrange(10000, 65535) if srcp not in self.sport: self.sport.append(srcp) break",
"{ 53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06' 'google\\x03com\\x00\\x00\\x01\\x00\\x01'), # 'google.com' DNS Lookup 161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02' '\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06' '\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'),",
"self.base = 0 self.base-= self.index self.num = self.base def next_index(self):",
"ip, tcp, udp ETH_P_IP = 0x0800 # IP protocol ETH_P_ALL",
"ETH_P_IP eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack() sock = socket.socket(family, socket.SOCK_RAW,",
"self.stype) sock.bind(('', self.srcp)) sock.settimeout(5) self.events['recv'].wait() counter = 0 while self.events['recv'].isSet():",
"raise StopIteration def suspend(self): return self.size, self.inc, self.base, self.num, self.index",
"transport.payload = '' else: transport.payload = PAYLOAD.get(transport.dstp, '\\x00\\r\\n\\r\\n') packed =",
"if 'resume' in dir(self.options): i = 0 for g in",
"try: target = hosts[0] + gen.next() iph = ip.IP(self.diface, dec2dot(target),",
"size self.inc = inc self.base = base self.num = num",
"= size self.inc = inc self.base = base self.num =",
"in self.hosts: g = Generator(h[1]-h[0]) generators.append(g) t = threading.Thread(target=self.send, args=(h,",
"eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack() sock = socket.socket(family, socket.SOCK_RAW, proto)",
"continue sock.close() logging.info('[RECV] Received: {} packets'.format(counter)) def split(self, hosts, n):",
"host_parts.append((start, end)) start = end else: host_parts.append((start, hosts[1])) break return",
"self.events['send'].wait() target = hosts[0] while self.events['send'].isSet(): try: target = hosts[0]",
"+ gen.next() iph = ip.IP(self.diface, dec2dot(target), self.stype) except StopIteration: break",
"struct.unpack('!H', packet[20:22])[0] return src, srcp def Alive(thread_list): ''' check if",
"= imports self.event = threading.Event() self.queues = {} self.thread =",
"threading from convert import * from protocol import ethernet, ip,",
"script), fromlist=[NSCRIPT_PATH]) t = threading.Thread(target=s.run, args=(q, self.event)) self.thread.append(t) t.setDaemon(True) t.start()",
"= options.cooldown self.queue = Queue.Queue() if options.stype.upper()=='U': self.stype = socket.IPPROTO_UDP",
"{ 'send': threading.Event(), 'recv': threading.Event()} self.threads = { 'send': [],",
"161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02' '\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06' '\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'), # SNMP GetNextRequest|public|2c version|1.3.6.1.2.1 123:('\\x17\\x00\\x02\\x05'), # NTP",
"sock.settimeout(5) self.events['recv'].wait() counter = 0 while self.events['recv'].isSet(): try: data, sa_ll",
"generators: g.resume(*self.options.indexes[i]) i+=1 return self.threads, self.events, self.queue, generators def run(self):",
"self.next_index() self.next_base() self.num = self.num + self.inc return self.num def",
"self.inc = 1 self.base = -self.inc self.num = self.base self.index",
"if self.__CookieCheck(data): self.queue.put(Extract(data)) counter += 1 if counter==self.count: self.events['send'].clear() break",
"port in xrange(r[0], r[1]): self.queues[scr].put((host, port)) break def Cleanup(self): while",
"= ip.IP(self.diface, dec2dot(target), self.stype) except StopIteration: break for port_list in",
"proto) transport = self.__Transport(srcp, 0) npacket = 0 self.events['send'].wait() target",
"= size self.inc = size/4 if self.inc<1: self.inc = 1",
"while self.events['send'].isSet(): try: target = hosts[0] + gen.next() iph =",
"else: ackn = struct.unpack('!L', data[28:32])[0] flags = struct.unpack('B', data[33])[0] &",
"hosts[1])) break return host_parts def PickPort(self): while True: srcp =",
"self.threads['recv'].start() def send(self, hosts, srcp, gen): if 'ppp' in self.ifname:",
"= options.dmac self.ifname = options.ifname self.siface = options.siface self.diface =",
"threading.Thread(target=self.recv) t.setDaemon(True) self.threads['recv'] = t if 'resume' in dir(self.options): i",
"def Extract(packet): src = socket.inet_ntoa(packet[12:16]) srcp = struct.unpack('!H', packet[20:22])[0] return",
"udp ETH_P_IP = 0x0800 # IP protocol ETH_P_ALL = 0x0003",
"self.base = -self.inc self.num = self.base self.index = 0 def",
"def next_index(self): self.index+=1 if self.index>=self.inc: raise StopIteration def suspend(self): return",
"+ iph.pack() + self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src, iph.dst) sock.sendto(packet, (dec2dot(target),",
"def Alive(thread_list): ''' check if thread is alive ''' alive",
"dstp = struct.unpack('!H', data[22:24])[0] if self.stype==socket.IPPROTO_UDP: if dstp==self.srcp: check =",
"t if 'resume' in dir(self.options): i = 0 for g",
"hosts[0] while self.events['send'].isSet(): try: target = hosts[0] + gen.next() iph",
"65535) if srcp not in self.sport: self.sport.append(srcp) break return srcp",
"+= 1 if counter==self.count: self.events['send'].clear() break except socket.timeout: continue sock.close()",
"self.sport.append(srcp) break return srcp def Extract(packet): src = socket.inet_ntoa(packet[12:16]) srcp",
"else: host_parts.append((start, hosts[1])) break return host_parts def PickPort(self): while True:",
"struct.unpack('!H', data[22:24])[0] if self.stype==socket.IPPROTO_UDP: if dstp==self.srcp: check = True else:",
"True else: ackn = struct.unpack('!L', data[28:32])[0] flags = struct.unpack('B', data[33])[0]",
"dst) transport.seqn = 0xDEADC0DE else: transport = udp.UDP(src, dst) return",
"self.index+=1 if self.index>=self.inc: raise StopIteration def suspend(self): return self.size, self.inc,",
"= ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack() sock = socket.socket(family, socket.SOCK_RAW, proto) transport",
"self.inc = inc self.base = base self.num = num self.index",
"''' alive = False for t in thread_list: if t.isAlive():",
"import logging import threading from convert import * from protocol",
"threading.Event(), 'recv': threading.Event()} self.threads = { 'send': [], 'recv': None}",
"family = socket.AF_PACKET proto = ETH_P_IP eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac),",
"npacket%self.cooldown[0]: time.sleep(self.cooldown[1]) else: break logging.info('[SEND] Sent: {} packets'.format(npacket)) sock.close() def",
"t in self.threads['send']: t.start() self.threads['recv'].start() def send(self, hosts, srcp, gen):",
"import struct import logging import threading from convert import *",
"self.queues[scr].put((host, port)) break def Cleanup(self): while Alive(self.thread): time.sleep(10) class nscan(object):",
"q def Feed(self, host, port): for scr in self.imports: for",
"return packed + transport.payload def __CookieCheck(self, data): check = False",
"''' check if thread is alive ''' alive = False",
"'\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'), # SNMP GetNextRequest|public|2c version|1.3.6.1.2.1 123:('\\x17\\x00\\x02\\x05'), # NTP systats commands",
"& 0b010010 # SYN-ACK if dstp==self.srcp and ackn==0xDEADC0DF and flags==18:",
"options.cooldown self.queue = Queue.Queue() if options.stype.upper()=='U': self.stype = socket.IPPROTO_UDP else:",
"end)) start = end else: host_parts.append((start, hosts[1])) break return host_parts",
"self.num, self.index def resume(self, size, inc, base, num, index): self.size",
"''' Split host range into n parts (multithreaded) ''' nhosts",
"def __Transport(self, src, dst=0): if self.stype==socket.IPPROTO_TCP: transport = tcp.TCP(src, dst)",
"if thread is alive ''' alive = False for t",
"= options.siface self.diface = options.diface self.banner = options.banner self.count =",
"'\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06' '\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'), # SNMP GetNextRequest|public|2c version|1.3.6.1.2.1 123:('\\x17\\x00\\x02\\x05'), # NTP systats",
"options): self.options = options self.hosts = self.split(options.hosts, options.threads) self.ports =",
"= Queue.Queue() if options.stype.upper()=='U': self.stype = socket.IPPROTO_UDP else: self.stype =",
"self.base = base self.num = num self.index = index class",
"in self.imports: q = Queue.Queue() s = __import__('{}.{}'.format(NSCRIPT_PATH, script), fromlist=[NSCRIPT_PATH])",
"[] def Load(self): for script in self.imports: q = Queue.Queue()",
"in dir(self.options): i = 0 for g in generators: g.resume(*self.options.indexes[i])",
"True: srcp = random.randrange(10000, 65535) if srcp not in self.sport:",
"if srcp not in self.sport: self.sport.append(srcp) break return srcp def",
"srcp, gen): if 'ppp' in self.ifname: family = socket.AF_INET proto",
"transport = self.__Transport(srcp, 0) npacket = 0 self.events['send'].wait() target =",
"* HTTP/1.1\\r\\nHOST: 192.168.127.12:1900\\r\\n' 'MAN: \"ssdp:discover\"\\r\\nMX: 2\\r\\nST: ssdp:all\\r\\n\\r\\n') } class Generator(object):",
"self.thread = [] def Load(self): for script in self.imports: q",
"host, port): for scr in self.imports: for r in self.imports[scr]:",
"= Generator(h[1]-h[0]) generators.append(g) t = threading.Thread(target=self.send, args=(h, self.srcp, g)) t.setDaemon(True)",
"class ScriptEngine(object): def __init__(self, imports): self.imports = imports self.event =",
"self.hosts = self.split(options.hosts, options.threads) self.ports = options.ports self.srcp = random.randint(1,",
"port_list[1]): if self.events['send'].isSet(): transport.dstp = port packet = eth +",
"packet[20:22])[0] return src, srcp def Alive(thread_list): ''' check if thread",
"= start + nparts host_parts.append((start, end)) start = end else:",
"\"ssdp:discover\"\\r\\nMX: 2\\r\\nST: ssdp:all\\r\\n\\r\\n') } class Generator(object): def __init__(self, size): self.size",
"if counter==self.count: self.events['send'].clear() break except socket.timeout: continue sock.close() logging.info('[RECV] Received:",
"# source port self.smac = options.smac self.dmac = options.dmac self.ifname",
"SNMP GetNextRequest|public|2c version|1.3.6.1.2.1 123:('\\x17\\x00\\x02\\x05'), # NTP systats commands lacks 38",
"counter += 1 if counter==self.count: self.events['send'].clear() break except socket.timeout: continue",
"1900:('M-SEARCH * HTTP/1.1\\r\\nHOST: 192.168.127.12:1900\\r\\n' 'MAN: \"ssdp:discover\"\\r\\nMX: 2\\r\\nST: ssdp:all\\r\\n\\r\\n') } class",
"= ETH_P_IP eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack() sock = socket.socket(family,",
"= t if 'resume' in dir(self.options): i = 0 for",
"for t in self.threads['send']: t.start() self.threads['recv'].start() def send(self, hosts, srcp,",
"self.imports: q = Queue.Queue() s = __import__('{}.{}'.format(NSCRIPT_PATH, script), fromlist=[NSCRIPT_PATH]) t",
"alive = False for t in thread_list: if t.isAlive(): alive",
"def next_base(self): self.base = 0 self.base-= self.index self.num = self.base",
"resume(self, size, inc, base, num, index): self.size = size self.inc",
"+ nparts host_parts.append((start, end)) start = end else: host_parts.append((start, hosts[1]))",
"return self def next(self): if (self.num+self.inc)>=self.size: self.next_index() self.next_base() self.num =",
"# 'google.com' DNS Lookup 161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02' '\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06' '\\x05\\x2b\\x06\\x01\\x02\\x01\\x05\\x00'), # SNMP GetNextRequest|public|2c",
"base, num, index): self.size = size self.inc = inc self.base",
"= socket.IPPROTO_RAW eth = '' else: family = socket.AF_PACKET proto",
"r in self.imports[scr]: if port in xrange(r[0], r[1]): self.queues[scr].put((host, port))",
"generators def run(self): self.events['send'].set() self.events['recv'].set() for t in self.threads['send']: t.start()",
"options.threads) self.ports = options.ports self.srcp = random.randint(1, 65535)#self.PickPort() # source",
"flags = struct.unpack('B', data[33])[0] & 0b010010 # SYN-ACK if dstp==self.srcp",
"'ppp' in self.ifname: family = socket.AF_INET proto = socket.IPPROTO_RAW eth",
"self.queues[script] = q def Feed(self, host, port): for scr in",
"if self.index>=self.inc: raise StopIteration def suspend(self): return self.size, self.inc, self.base,",
"self.queue.put(Extract(data)) counter += 1 if counter==self.count: self.events['send'].clear() break except socket.timeout:",
"65535)#self.PickPort() # source port self.smac = options.smac self.dmac = options.dmac",
"'send': [], 'recv': None} def __Transport(self, src, dst=0): if self.stype==socket.IPPROTO_TCP:",
"n parts (multithreaded) ''' nhosts = hosts[1] - hosts[0] #",
"Alive(thread_list): ''' check if thread is alive ''' alive =",
"src, srcp def Alive(thread_list): ''' check if thread is alive",
"else: transport.payload = PAYLOAD.get(transport.dstp, '\\x00\\r\\n\\r\\n') packed = transport.pack(src, dst) return",
"g in generators: g.resume(*self.options.indexes[i]) i+=1 return self.threads, self.events, self.queue, generators",
"data[33])[0] & 0b010010 # SYN-ACK if dstp==self.srcp and ackn==0xDEADC0DF and",
"null bytes (just to save bandwidth) 1900:('M-SEARCH * HTTP/1.1\\r\\nHOST: 192.168.127.12:1900\\r\\n'",
"def run(self): self.events['send'].set() self.events['recv'].set() for t in self.threads['send']: t.start() self.threads['recv'].start()",
"protocol ETH_P_ALL = 0x0003 # Every packet NSCRIPT_PATH = 'nscript'",
"import threading from convert import * from protocol import ethernet,",
"size): self.size = size self.inc = size/4 if self.inc<1: self.inc",
"in range(port_list[0], port_list[1]): if self.events['send'].isSet(): transport.dstp = port packet =",
"into n parts (multithreaded) ''' nhosts = hosts[1] - hosts[0]",
"packed + transport.payload def __CookieCheck(self, data): check = False dstp",
"self.__Transport(srcp, 0) npacket = 0 self.events['send'].wait() target = hosts[0] while",
"if dstp==self.srcp and ackn==0xDEADC0DF and flags==18: check = True return",
"logging import threading from convert import * from protocol import",
"number of hosts nparts = nhosts/n + 1 host_parts =",
"and ackn==0xDEADC0DF and flags==18: check = True return check def",
"= threading.Thread(target=self.send, args=(h, self.srcp, g)) t.setDaemon(True) self.threads['send'].append(t) t = threading.Thread(target=self.recv)",
"if len(host_parts)<n-1: end = start + nparts host_parts.append((start, end)) start",
"if dstp==self.srcp: check = True else: ackn = struct.unpack('!L', data[28:32])[0]",
"def __iter__(self): return self def next(self): if (self.num+self.inc)>=self.size: self.next_index() self.next_base()",
"dir(self.options): i = 0 for g in generators: g.resume(*self.options.indexes[i]) i+=1",
"= -self.inc self.num = self.base self.index = 0 def __iter__(self):",
"while self.events['recv'].isSet(): try: data, sa_ll = sock.recvfrom(65535) if self.__CookieCheck(data): self.queue.put(Extract(data))",
"self.srcp = random.randint(1, 65535)#self.PickPort() # source port self.smac = options.smac",
"base self.num = num self.index = index class ScriptEngine(object): def",
"flags==18: check = True return check def init(self): generators =",
"size/4 if self.inc<1: self.inc = 1 self.base = -self.inc self.num",
"size, inc, base, num, index): self.size = size self.inc =",
"threading.Thread(target=self.send, args=(h, self.srcp, g)) t.setDaemon(True) self.threads['send'].append(t) t = threading.Thread(target=self.recv) t.setDaemon(True)",
"self.size = size self.inc = inc self.base = base self.num",
"def __init__(self, options): self.options = options self.hosts = self.split(options.hosts, options.threads)",
"options.count self.cooldown = options.cooldown self.queue = Queue.Queue() if options.stype.upper()=='U': self.stype",
"threading.Event()} self.threads = { 'send': [], 'recv': None} def __Transport(self,",
"# SYN-ACK if dstp==self.srcp and ackn==0xDEADC0DF and flags==18: check =",
"socket.AF_PACKET proto = ETH_P_IP eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack() sock",
"eth + iph.pack() + self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src, iph.dst) sock.sendto(packet,",
"packet = eth + iph.pack() + self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src,",
"def init(self): generators = [] for h in self.hosts: g",
"self.num + self.inc return self.num def next_base(self): self.base = 0",
"def PickPort(self): while True: srcp = random.randrange(10000, 65535) if srcp",
"dst): if self.stype==socket.IPPROTO_TCP: transport.payload = '' else: transport.payload = PAYLOAD.get(transport.dstp,",
"self.num = self.num + self.inc return self.num def next_base(self): self.base",
"self.ifname = options.ifname self.siface = options.siface self.diface = options.diface self.banner",
"'recv': None} def __Transport(self, src, dst=0): if self.stype==socket.IPPROTO_TCP: transport =",
"ethernet, ip, tcp, udp ETH_P_IP = 0x0800 # IP protocol",
"def Feed(self, host, port): for scr in self.imports: for r",
"False dstp = struct.unpack('!H', data[22:24])[0] if self.stype==socket.IPPROTO_UDP: if dstp==self.srcp: check",
"if self.inc<1: self.inc = 1 self.base = -self.inc self.num =",
"iph.pack() + self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src, iph.dst) sock.sendto(packet, (dec2dot(target), 0))",
"self.ifname npacket+=1 if not npacket%self.cooldown[0]: time.sleep(self.cooldown[1]) else: break logging.info('[SEND] Sent:",
"srcp = random.randrange(10000, 65535) if srcp not in self.sport: self.sport.append(srcp)",
"nscan(object): def __init__(self, options): self.options = options self.hosts = self.split(options.hosts,",
"data, sa_ll = sock.recvfrom(65535) if self.__CookieCheck(data): self.queue.put(Extract(data)) counter += 1",
"= base self.num = num self.index = index class ScriptEngine(object):",
"self.size = size self.inc = size/4 if self.inc<1: self.inc =",
"= '' else: family = socket.AF_PACKET proto = ETH_P_IP eth",
"logging.info('[SEND] Sent: {} packets'.format(npacket)) sock.close() def recv(self): sock = socket.socket(socket.AF_INET,",
"socket.IPPROTO_RAW eth = '' else: family = socket.AF_PACKET proto =",
"lacks 38 null bytes (just to save bandwidth) 1900:('M-SEARCH *",
"PATH PAYLOAD = { 53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06' 'google\\x03com\\x00\\x00\\x01\\x00\\x01'), # 'google.com' DNS Lookup",
"[] start = hosts[0] while True: if len(host_parts)<n-1: end =",
"dst=0): if self.stype==socket.IPPROTO_TCP: transport = tcp.TCP(src, dst) transport.seqn = 0xDEADC0DE",
"index class ScriptEngine(object): def __init__(self, imports): self.imports = imports self.event",
"* from protocol import ethernet, ip, tcp, udp ETH_P_IP =",
"= options self.hosts = self.split(options.hosts, options.threads) self.ports = options.ports self.srcp",
"try: data, sa_ll = sock.recvfrom(65535) if self.__CookieCheck(data): self.queue.put(Extract(data)) counter +=",
"host range into n parts (multithreaded) ''' nhosts = hosts[1]",
"'MAN: \"ssdp:discover\"\\r\\nMX: 2\\r\\nST: ssdp:all\\r\\n\\r\\n') } class Generator(object): def __init__(self, size):",
"t.setDaemon(True) self.threads['send'].append(t) t = threading.Thread(target=self.recv) t.setDaemon(True) self.threads['recv'] = t if",
"i = 0 for g in generators: g.resume(*self.options.indexes[i]) i+=1 return",
"= '' else: transport.payload = PAYLOAD.get(transport.dstp, '\\x00\\r\\n\\r\\n') packed = transport.pack(src,",
"args=(q, self.event)) self.thread.append(t) t.setDaemon(True) t.start() self.queues[script] = q def Feed(self,",
"index): self.size = size self.inc = inc self.base = base",
"'\\x00\\r\\n\\r\\n') packed = transport.pack(src, dst) return packed + transport.payload def",
"h in self.hosts: g = Generator(h[1]-h[0]) generators.append(g) t = threading.Thread(target=self.send,",
"self.srcp, g)) t.setDaemon(True) self.threads['send'].append(t) t = threading.Thread(target=self.recv) t.setDaemon(True) self.threads['recv'] =",
"t.setDaemon(True) t.start() self.queues[script] = q def Feed(self, host, port): for",
"recv(self): sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.stype) sock.bind(('', self.srcp)) sock.settimeout(5) self.events['recv'].wait()",
"end = start + nparts host_parts.append((start, end)) start = end",
"def split(self, hosts, n): ''' Split host range into n",
"ETH_P_IP = 0x0800 # IP protocol ETH_P_ALL = 0x0003 #",
"= 0xDEADC0DE else: transport = udp.UDP(src, dst) return transport def",
"self.hosts: g = Generator(h[1]-h[0]) generators.append(g) t = threading.Thread(target=self.send, args=(h, self.srcp,",
"self.threads['send']: t.start() self.threads['recv'].start() def send(self, hosts, srcp, gen): if 'ppp'",
"# NTP systats commands lacks 38 null bytes (just to",
"= 1 self.base = -self.inc self.num = self.base self.index =",
"NSCRIPT_PATH = 'nscript' # NSCRIPT PATH PAYLOAD = { 53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06'",
"commands lacks 38 null bytes (just to save bandwidth) 1900:('M-SEARCH",
"self.events['recv'].set() for t in self.threads['send']: t.start() self.threads['recv'].start() def send(self, hosts,",
"= 0 self.events['send'].wait() target = hosts[0] while self.events['send'].isSet(): try: target",
"npacket = 0 self.events['send'].wait() target = hosts[0] while self.events['send'].isSet(): try:",
"port packet = eth + iph.pack() + self.__Pack(transport, iph.src, iph.dst)",
"break for port_list in self.ports: for port in range(port_list[0], port_list[1]):",
"= struct.unpack('!H', packet[20:22])[0] return src, srcp def Alive(thread_list): ''' check",
"packets'.format(counter)) def split(self, hosts, n): ''' Split host range into",
"= q def Feed(self, host, port): for scr in self.imports:",
"= transport.pack(src, dst) return packed + transport.payload def __CookieCheck(self, data):",
"SYN-ACK if dstp==self.srcp and ackn==0xDEADC0DF and flags==18: check = True",
"counter==self.count: self.events['send'].clear() break except socket.timeout: continue sock.close() logging.info('[RECV] Received: {}",
"except socket.timeout: continue sock.close() logging.info('[RECV] Received: {} packets'.format(counter)) def split(self,",
"r[1]): self.queues[scr].put((host, port)) break def Cleanup(self): while Alive(self.thread): time.sleep(10) class",
"True return check def init(self): generators = [] for h",
"(just to save bandwidth) 1900:('M-SEARCH * HTTP/1.1\\r\\nHOST: 192.168.127.12:1900\\r\\n' 'MAN: \"ssdp:discover\"\\r\\nMX:",
"range into n parts (multithreaded) ''' nhosts = hosts[1] -",
"Generator(h[1]-h[0]) generators.append(g) t = threading.Thread(target=self.send, args=(h, self.srcp, g)) t.setDaemon(True) self.threads['send'].append(t)",
"self.events = { 'send': threading.Event(), 'recv': threading.Event()} self.threads = {",
"check = False dstp = struct.unpack('!H', data[22:24])[0] if self.stype==socket.IPPROTO_UDP: if",
"# IP protocol ETH_P_ALL = 0x0003 # Every packet NSCRIPT_PATH",
"from convert import * from protocol import ethernet, ip, tcp,",
"ETH_P_ALL = 0x0003 # Every packet NSCRIPT_PATH = 'nscript' #",
"__init__(self, options): self.options = options self.hosts = self.split(options.hosts, options.threads) self.ports",
"check = True return check def init(self): generators = []",
"self.base, self.num, self.index def resume(self, size, inc, base, num, index):",
"srcp def Alive(thread_list): ''' check if thread is alive '''",
"self.siface = options.siface self.diface = options.diface self.banner = options.banner self.count",
"= True return check def init(self): generators = [] for",
"run(self): self.events['send'].set() self.events['recv'].set() for t in self.threads['send']: t.start() self.threads['recv'].start() def",
"packets'.format(npacket)) sock.close() def recv(self): sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.stype) sock.bind(('',",
"__import__('{}.{}'.format(NSCRIPT_PATH, script), fromlist=[NSCRIPT_PATH]) t = threading.Thread(target=s.run, args=(q, self.event)) self.thread.append(t) t.setDaemon(True)",
"= inc self.base = base self.num = num self.index =",
"192.168.127.12:1900\\r\\n' 'MAN: \"ssdp:discover\"\\r\\nMX: 2\\r\\nST: ssdp:all\\r\\n\\r\\n') } class Generator(object): def __init__(self,",
"self.index = index class ScriptEngine(object): def __init__(self, imports): self.imports =",
"time.sleep(10) class nscan(object): def __init__(self, options): self.options = options self.hosts",
"= { 53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06' 'google\\x03com\\x00\\x00\\x01\\x00\\x01'), # 'google.com' DNS Lookup 161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02' '\\x04\\x56\\x9f\\x5a\\xdd\\x02\\x01\\x00\\x02\\x01\\x00\\x30\\x0b\\x30\\x09\\x06'",
"return self.threads, self.events, self.queue, generators def run(self): self.events['send'].set() self.events['recv'].set() for",
"send(self, hosts, srcp, gen): if 'ppp' in self.ifname: family =",
"start + nparts host_parts.append((start, end)) start = end else: host_parts.append((start,",
"NTP systats commands lacks 38 null bytes (just to save",
"num self.index = index class ScriptEngine(object): def __init__(self, imports): self.imports",
"self.stype = socket.IPPROTO_UDP else: self.stype = socket.IPPROTO_TCP self.events = {",
"Sent: {} packets'.format(npacket)) sock.close() def recv(self): sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,",
"random.randrange(10000, 65535) if srcp not in self.sport: self.sport.append(srcp) break return",
"socket.inet_ntoa(packet[12:16]) srcp = struct.unpack('!H', packet[20:22])[0] return src, srcp def Alive(thread_list):",
"self.events['send'].isSet(): try: target = hosts[0] + gen.next() iph = ip.IP(self.diface,",
"self.inc, self.base, self.num, self.index def resume(self, size, inc, base, num,",
"{ 'send': [], 'recv': None} def __Transport(self, src, dst=0): if",
"break def Cleanup(self): while Alive(self.thread): time.sleep(10) class nscan(object): def __init__(self,",
"ackn = struct.unpack('!L', data[28:32])[0] flags = struct.unpack('B', data[33])[0] & 0b010010",
"self.inc<1: self.inc = 1 self.base = -self.inc self.num = self.base",
"self.imports: for r in self.imports[scr]: if port in xrange(r[0], r[1]):",
"= socket.inet_ntoa(packet[12:16]) srcp = struct.unpack('!H', packet[20:22])[0] return src, srcp def",
"while True: srcp = random.randrange(10000, 65535) if srcp not in",
"PAYLOAD = { 53:('\\x5d\\x0d\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x06' 'google\\x03com\\x00\\x00\\x01\\x00\\x01'), # 'google.com' DNS Lookup 161:('\\x30\\x26\\x02\\x01\\x01\\x04\\x06public\\xa1\\x19\\x02'",
"__iter__(self): return self def next(self): if (self.num+self.inc)>=self.size: self.next_index() self.next_base() self.num",
"for port_list in self.ports: for port in range(port_list[0], port_list[1]): if",
"= struct.unpack('!L', data[28:32])[0] flags = struct.unpack('B', data[33])[0] & 0b010010 #",
"socket.SOCK_RAW, self.stype) sock.bind(('', self.srcp)) sock.settimeout(5) self.events['recv'].wait() counter = 0 while",
"self.options = options self.hosts = self.split(options.hosts, options.threads) self.ports = options.ports",
"return transport def __Pack(self, transport, src, dst): if self.stype==socket.IPPROTO_TCP: transport.payload",
"__CookieCheck(self, data): check = False dstp = struct.unpack('!H', data[22:24])[0] if",
"def Load(self): for script in self.imports: q = Queue.Queue() s",
"mac2byte(self.dmac), ETH_P_IP).pack() sock = socket.socket(family, socket.SOCK_RAW, proto) transport = self.__Transport(srcp,",
"0 self.base-= self.index self.num = self.base def next_index(self): self.index+=1 if",
"is alive ''' alive = False for t in thread_list:",
"in generators: g.resume(*self.options.indexes[i]) i+=1 return self.threads, self.events, self.queue, generators def",
"= random.randint(1, 65535)#self.PickPort() # source port self.smac = options.smac self.dmac",
"port self.smac = options.smac self.dmac = options.dmac self.ifname = options.ifname"
] |
[
"db from flaskApp.assignment.utils import * from flaskApp.error.error_handlers import * import",
"return jsonify({}), 204 except (NotFound, BadRequest) as e: return jsonify(e.body),",
"BadRequest) as e: return jsonify(e.body), e.status_code @assignment.route('/addAssignment/<calID>/<courseID>', methods=['POST']) def add_assignment(calID,",
"assignment) return jsonify(res), 200 except (NotFound) as e: return jsonify(e.body),",
"e: return jsonify(e.body), e.status_code @assignment.route('/deleteAssignment/<calID>/<courseID>', methods=['DELETE']) def delete_assignment(calID, courseID): try:",
"except (NotFound, BadRequest) as e: return jsonify(e.body), e.status_code @assignment.route('/addAssignment/<calID>/<courseID>', methods=['POST'])",
"e: return jsonify(e.body), e.status_code @assignment.route('/getAssignment/<calID>/<courseID>/<assignment>', methods=['GET']) def get_assignment_details(calID, courseID, assignment):",
"the data pipeline will drop stuff into''' @assignment.route('/getAssignmentTest/<courseID>', methods=['GET']) def",
"request_body) return jsonify({}), 204 except (NotFound, BadRequest) as e: return",
"* import json from flaskApp.helpers import getAssignmentData assignment = Blueprint('assignment',",
"jsonify(e.body), e.status_code @assignment.route('/getAssignment/<calID>/<courseID>/<assignment>', methods=['GET']) def get_assignment_details(calID, courseID, assignment): try: res",
"__name__) @assignment.route('/restoreAssignment/<calID>/<courseID>', methods=['POST']) def restore_assignment(calID, courseID): try: DbAssignmentUtils.restore_all_original_assignment(calID, courseID) return",
"interact with just the MySQL database that the data pipeline",
"e.status_code '''Test method, keep just in case. Will prob be",
"return jsonify(e.body), e.status_code @assignment.route('/deleteAssignment/<calID>/<courseID>', methods=['DELETE']) def delete_assignment(calID, courseID): try: request_body",
"import db from flaskApp.assignment.utils import * from flaskApp.error.error_handlers import *",
"seperate API designed to interact with just the MySQL database",
"methods=['DELETE']) def delete_assignment(calID, courseID): try: request_body = json.loads(request.get_data()) DbAssignmentUtils.delete_assignment_slot(calID, courseID,",
"* from flaskApp.error.error_handlers import * import json from flaskApp.helpers import",
"try: DbAssignmentUtils.restore_all_original_assignment(calID, courseID) return jsonify({\"restore\" : \"success\"}), 201 except (NotFound)",
"from flaskApp.helpers import getAssignmentData assignment = Blueprint('assignment', __name__) @assignment.route('/restoreAssignment/<calID>/<courseID>', methods=['POST'])",
"delete_assignment(calID, courseID): try: request_body = json.loads(request.get_data()) DbAssignmentUtils.delete_assignment_slot(calID, courseID, request_body) return",
"return jsonify(res), 201 except (NotFound, BadRequest, ValidationFailed) as e: return",
"@assignment.route('/getAssignment/<calID>/<courseID>/<assignment>', methods=['GET']) def get_assignment_details(calID, courseID, assignment): try: res = DbAssignmentUtils.get_assignment_slot_details(calID,",
"flaskApp import db from flaskApp.assignment.utils import * from flaskApp.error.error_handlers import",
"= json.loads(request.get_data()) DbAssignmentUtils.delete_assignment_slot(calID, courseID, request_body) return jsonify({}), 204 except (NotFound,",
"database that the data pipeline will drop stuff into''' @assignment.route('/getAssignmentTest/<courseID>',",
"as e: return jsonify(e.body), e.status_code @assignment.route('/getAssignment/<calID>/<courseID>/<assignment>', methods=['GET']) def get_assignment_details(calID, courseID,",
"will drop stuff into''' @assignment.route('/getAssignmentTest/<courseID>', methods=['GET']) def get_session_assignment(courseID): try: result",
"(NotFound, BadRequest, ValidationFailed) as e: return jsonify(e.body), e.status_code '''Test method,",
"just the MySQL database that the data pipeline will drop",
"def restore_assignment(calID, courseID): try: DbAssignmentUtils.restore_all_original_assignment(calID, courseID) return jsonify({\"restore\" : \"success\"}),",
"be moved to seperate API designed to interact with just",
"jsonify(res), 200 except (NotFound) as e: return jsonify(e.body), e.status_code @assignment.route('/deleteAssignment/<calID>/<courseID>',",
"json.loads(request.get_data()) DbAssignmentUtils.delete_assignment_slot(calID, courseID, request_body) return jsonify({}), 204 except (NotFound, BadRequest)",
"getAssignmentData assignment = Blueprint('assignment', __name__) @assignment.route('/restoreAssignment/<calID>/<courseID>', methods=['POST']) def restore_assignment(calID, courseID):",
"@assignment.route('/getAssignmentTest/<courseID>', methods=['GET']) def get_session_assignment(courseID): try: result = getAssignmentData(courseID) return jsonify(result)",
"ValidationFailed) as e: return jsonify(e.body), e.status_code '''Test method, keep just",
"prob be moved to seperate API designed to interact with",
"e.status_code @assignment.route('/addAssignment/<calID>/<courseID>', methods=['POST']) def add_assignment(calID, courseID): try: request_body = json.loads(request.get_data())",
"except (NotFound) as e: return jsonify(e.body), e.status_code @assignment.route('/deleteAssignment/<calID>/<courseID>', methods=['DELETE']) def",
"'''Test method, keep just in case. Will prob be moved",
"jsonify({}), 204 except (NotFound, BadRequest) as e: return jsonify(e.body), e.status_code",
"e: return jsonify(e.body), e.status_code @assignment.route('/addAssignment/<calID>/<courseID>', methods=['POST']) def add_assignment(calID, courseID): try:",
"(NotFound, BadRequest) as e: return jsonify(e.body), e.status_code @assignment.route('/addAssignment/<calID>/<courseID>', methods=['POST']) def",
"jsonify(e.body), e.status_code @assignment.route('/addAssignment/<calID>/<courseID>', methods=['POST']) def add_assignment(calID, courseID): try: request_body =",
"res = DbAssignmentUtils.get_assignment_slot_details(calID, courseID, assignment) return jsonify(res), 200 except (NotFound)",
"API designed to interact with just the MySQL database that",
"@assignment.route('/restoreAssignment/<calID>/<courseID>', methods=['POST']) def restore_assignment(calID, courseID): try: DbAssignmentUtils.restore_all_original_assignment(calID, courseID) return jsonify({\"restore\"",
"e.status_code @assignment.route('/deleteAssignment/<calID>/<courseID>', methods=['DELETE']) def delete_assignment(calID, courseID): try: request_body = json.loads(request.get_data())",
"request_body = json.loads(request.get_data()) res = DbAssignmentUtils.add_Assignment_slot(calID, courseID, request_body) return jsonify(res),",
"(NotFound) as e: return jsonify(e.body), e.status_code @assignment.route('/deleteAssignment/<calID>/<courseID>', methods=['DELETE']) def delete_assignment(calID,",
"e.status_code @assignment.route('/getAssignment/<calID>/<courseID>/<assignment>', methods=['GET']) def get_assignment_details(calID, courseID, assignment): try: res =",
"200 except (NotFound) as e: return jsonify(e.body), e.status_code @assignment.route('/deleteAssignment/<calID>/<courseID>', methods=['DELETE'])",
"e: return jsonify(e.body), e.status_code '''Test method, keep just in case.",
"return jsonify(e.body), e.status_code @assignment.route('/addAssignment/<calID>/<courseID>', methods=['POST']) def add_assignment(calID, courseID): try: request_body",
"get_session_assignment(courseID): try: result = getAssignmentData(courseID) return jsonify(result) except (NotFound) as",
"201 except (NotFound) as e: return jsonify(e.body), e.status_code @assignment.route('/getAssignment/<calID>/<courseID>/<assignment>', methods=['GET'])",
"assignment = Blueprint('assignment', __name__) @assignment.route('/restoreAssignment/<calID>/<courseID>', methods=['POST']) def restore_assignment(calID, courseID): try:",
"= DbAssignmentUtils.get_assignment_slot_details(calID, courseID, assignment) return jsonify(res), 200 except (NotFound) as",
"res = DbAssignmentUtils.add_Assignment_slot(calID, courseID, request_body) return jsonify(res), 201 except (NotFound,",
"DbAssignmentUtils.delete_assignment_slot(calID, courseID, request_body) return jsonify({}), 204 except (NotFound, BadRequest) as",
"def delete_assignment(calID, courseID): try: request_body = json.loads(request.get_data()) DbAssignmentUtils.delete_assignment_slot(calID, courseID, request_body)",
"try: request_body = json.loads(request.get_data()) res = DbAssignmentUtils.add_Assignment_slot(calID, courseID, request_body) return",
"204 except (NotFound, BadRequest) as e: return jsonify(e.body), e.status_code @assignment.route('/addAssignment/<calID>/<courseID>',",
"201 except (NotFound, BadRequest, ValidationFailed) as e: return jsonify(e.body), e.status_code",
"def get_session_assignment(courseID): try: result = getAssignmentData(courseID) return jsonify(result) except (NotFound)",
"courseID): try: request_body = json.loads(request.get_data()) DbAssignmentUtils.delete_assignment_slot(calID, courseID, request_body) return jsonify({}),",
"jsonify({\"restore\" : \"success\"}), 201 except (NotFound) as e: return jsonify(e.body),",
"methods=['POST']) def restore_assignment(calID, courseID): try: DbAssignmentUtils.restore_all_original_assignment(calID, courseID) return jsonify({\"restore\" :",
"DbAssignmentUtils.get_assignment_slot_details(calID, courseID, assignment) return jsonify(res), 200 except (NotFound) as e:",
"DbAssignmentUtils.restore_all_original_assignment(calID, courseID) return jsonify({\"restore\" : \"success\"}), 201 except (NotFound) as",
"as e: return jsonify(e.body), e.status_code '''Test method, keep just in",
"sys from flask import Blueprint, request, jsonify from flaskApp import",
"import * import json from flaskApp.helpers import getAssignmentData assignment =",
"request_body = json.loads(request.get_data()) DbAssignmentUtils.delete_assignment_slot(calID, courseID, request_body) return jsonify({}), 204 except",
"courseID) return jsonify({\"restore\" : \"success\"}), 201 except (NotFound) as e:",
"\"success\"}), 201 except (NotFound) as e: return jsonify(e.body), e.status_code @assignment.route('/getAssignment/<calID>/<courseID>/<assignment>',",
"BadRequest, ValidationFailed) as e: return jsonify(e.body), e.status_code '''Test method, keep",
"flask import Blueprint, request, jsonify from flaskApp import db from",
"except (NotFound, BadRequest, ValidationFailed) as e: return jsonify(e.body), e.status_code '''Test",
"request_body) return jsonify(res), 201 except (NotFound, BadRequest, ValidationFailed) as e:",
"in case. Will prob be moved to seperate API designed",
"def add_assignment(calID, courseID): try: request_body = json.loads(request.get_data()) res = DbAssignmentUtils.add_Assignment_slot(calID,",
"jsonify from flaskApp import db from flaskApp.assignment.utils import * from",
"from flask import Blueprint, request, jsonify from flaskApp import db",
"return jsonify(res), 200 except (NotFound) as e: return jsonify(e.body), e.status_code",
"as e: return jsonify(e.body), e.status_code @assignment.route('/deleteAssignment/<calID>/<courseID>', methods=['DELETE']) def delete_assignment(calID, courseID):",
"@assignment.route('/deleteAssignment/<calID>/<courseID>', methods=['DELETE']) def delete_assignment(calID, courseID): try: request_body = json.loads(request.get_data()) DbAssignmentUtils.delete_assignment_slot(calID,",
"method, keep just in case. Will prob be moved to",
"flaskApp.assignment.utils import * from flaskApp.error.error_handlers import * import json from",
"json from flaskApp.helpers import getAssignmentData assignment = Blueprint('assignment', __name__) @assignment.route('/restoreAssignment/<calID>/<courseID>',",
"try: request_body = json.loads(request.get_data()) DbAssignmentUtils.delete_assignment_slot(calID, courseID, request_body) return jsonify({}), 204",
"return jsonify(e.body), e.status_code '''Test method, keep just in case. Will",
"import sys from flask import Blueprint, request, jsonify from flaskApp",
": \"success\"}), 201 except (NotFound) as e: return jsonify(e.body), e.status_code",
"MySQL database that the data pipeline will drop stuff into'''",
"case. Will prob be moved to seperate API designed to",
"pipeline will drop stuff into''' @assignment.route('/getAssignmentTest/<courseID>', methods=['GET']) def get_session_assignment(courseID): try:",
"from flaskApp.error.error_handlers import * import json from flaskApp.helpers import getAssignmentData",
"drop stuff into''' @assignment.route('/getAssignmentTest/<courseID>', methods=['GET']) def get_session_assignment(courseID): try: result =",
"flaskApp.error.error_handlers import * import json from flaskApp.helpers import getAssignmentData assignment",
"jsonify(e.body), e.status_code @assignment.route('/deleteAssignment/<calID>/<courseID>', methods=['DELETE']) def delete_assignment(calID, courseID): try: request_body =",
"restore_assignment(calID, courseID): try: DbAssignmentUtils.restore_all_original_assignment(calID, courseID) return jsonify({\"restore\" : \"success\"}), 201",
"import json from flaskApp.helpers import getAssignmentData assignment = Blueprint('assignment', __name__)",
"into''' @assignment.route('/getAssignmentTest/<courseID>', methods=['GET']) def get_session_assignment(courseID): try: result = getAssignmentData(courseID) return",
"from flaskApp.assignment.utils import * from flaskApp.error.error_handlers import * import json",
"return jsonify(e.body), e.status_code @assignment.route('/getAssignment/<calID>/<courseID>/<assignment>', methods=['GET']) def get_assignment_details(calID, courseID, assignment): try:",
"= getAssignmentData(courseID) return jsonify(result) except (NotFound) as e: return jsonify(e.body),",
"Blueprint('assignment', __name__) @assignment.route('/restoreAssignment/<calID>/<courseID>', methods=['POST']) def restore_assignment(calID, courseID): try: DbAssignmentUtils.restore_all_original_assignment(calID, courseID)",
"stuff into''' @assignment.route('/getAssignmentTest/<courseID>', methods=['GET']) def get_session_assignment(courseID): try: result = getAssignmentData(courseID)",
"to seperate API designed to interact with just the MySQL",
"assignment): try: res = DbAssignmentUtils.get_assignment_slot_details(calID, courseID, assignment) return jsonify(res), 200",
"add_assignment(calID, courseID): try: request_body = json.loads(request.get_data()) res = DbAssignmentUtils.add_Assignment_slot(calID, courseID,",
"just in case. Will prob be moved to seperate API",
"data pipeline will drop stuff into''' @assignment.route('/getAssignmentTest/<courseID>', methods=['GET']) def get_session_assignment(courseID):",
"except (NotFound) as e: return jsonify(e.body), e.status_code @assignment.route('/getAssignment/<calID>/<courseID>/<assignment>', methods=['GET']) def",
"return jsonify({\"restore\" : \"success\"}), 201 except (NotFound) as e: return",
"get_assignment_details(calID, courseID, assignment): try: res = DbAssignmentUtils.get_assignment_slot_details(calID, courseID, assignment) return",
"try: result = getAssignmentData(courseID) return jsonify(result) except (NotFound) as e:",
"import * from flaskApp.error.error_handlers import * import json from flaskApp.helpers",
"= DbAssignmentUtils.add_Assignment_slot(calID, courseID, request_body) return jsonify(res), 201 except (NotFound, BadRequest,",
"methods=['GET']) def get_session_assignment(courseID): try: result = getAssignmentData(courseID) return jsonify(result) except",
"the MySQL database that the data pipeline will drop stuff",
"courseID): try: request_body = json.loads(request.get_data()) res = DbAssignmentUtils.add_Assignment_slot(calID, courseID, request_body)",
"from flaskApp import db from flaskApp.assignment.utils import * from flaskApp.error.error_handlers",
"json.loads(request.get_data()) res = DbAssignmentUtils.add_Assignment_slot(calID, courseID, request_body) return jsonify(res), 201 except",
"= Blueprint('assignment', __name__) @assignment.route('/restoreAssignment/<calID>/<courseID>', methods=['POST']) def restore_assignment(calID, courseID): try: DbAssignmentUtils.restore_all_original_assignment(calID,",
"with just the MySQL database that the data pipeline will",
"Will prob be moved to seperate API designed to interact",
"= json.loads(request.get_data()) res = DbAssignmentUtils.add_Assignment_slot(calID, courseID, request_body) return jsonify(res), 201",
"as e: return jsonify(e.body), e.status_code @assignment.route('/addAssignment/<calID>/<courseID>', methods=['POST']) def add_assignment(calID, courseID):",
"Blueprint, request, jsonify from flaskApp import db from flaskApp.assignment.utils import",
"getAssignmentData(courseID) return jsonify(result) except (NotFound) as e: return jsonify(e.body), e.status_code",
"import Blueprint, request, jsonify from flaskApp import db from flaskApp.assignment.utils",
"that the data pipeline will drop stuff into''' @assignment.route('/getAssignmentTest/<courseID>', methods=['GET'])",
"jsonify(res), 201 except (NotFound, BadRequest, ValidationFailed) as e: return jsonify(e.body),",
"methods=['POST']) def add_assignment(calID, courseID): try: request_body = json.loads(request.get_data()) res =",
"@assignment.route('/addAssignment/<calID>/<courseID>', methods=['POST']) def add_assignment(calID, courseID): try: request_body = json.loads(request.get_data()) res",
"courseID, assignment) return jsonify(res), 200 except (NotFound) as e: return",
"courseID): try: DbAssignmentUtils.restore_all_original_assignment(calID, courseID) return jsonify({\"restore\" : \"success\"}), 201 except",
"designed to interact with just the MySQL database that the",
"to interact with just the MySQL database that the data",
"(NotFound) as e: return jsonify(e.body), e.status_code @assignment.route('/getAssignment/<calID>/<courseID>/<assignment>', methods=['GET']) def get_assignment_details(calID,",
"courseID, assignment): try: res = DbAssignmentUtils.get_assignment_slot_details(calID, courseID, assignment) return jsonify(res),",
"result = getAssignmentData(courseID) return jsonify(result) except (NotFound) as e: return",
"moved to seperate API designed to interact with just the",
"import getAssignmentData assignment = Blueprint('assignment', __name__) @assignment.route('/restoreAssignment/<calID>/<courseID>', methods=['POST']) def restore_assignment(calID,",
"try: res = DbAssignmentUtils.get_assignment_slot_details(calID, courseID, assignment) return jsonify(res), 200 except",
"keep just in case. Will prob be moved to seperate",
"jsonify(e.body), e.status_code '''Test method, keep just in case. Will prob",
"methods=['GET']) def get_assignment_details(calID, courseID, assignment): try: res = DbAssignmentUtils.get_assignment_slot_details(calID, courseID,",
"def get_assignment_details(calID, courseID, assignment): try: res = DbAssignmentUtils.get_assignment_slot_details(calID, courseID, assignment)",
"courseID, request_body) return jsonify(res), 201 except (NotFound, BadRequest, ValidationFailed) as",
"request, jsonify from flaskApp import db from flaskApp.assignment.utils import *",
"DbAssignmentUtils.add_Assignment_slot(calID, courseID, request_body) return jsonify(res), 201 except (NotFound, BadRequest, ValidationFailed)",
"flaskApp.helpers import getAssignmentData assignment = Blueprint('assignment', __name__) @assignment.route('/restoreAssignment/<calID>/<courseID>', methods=['POST']) def",
"courseID, request_body) return jsonify({}), 204 except (NotFound, BadRequest) as e:"
] |
[
"is_present[char_ord] = i max_window = max(max_window, i - window_start +",
"longest substring without any repeating characters is \"abc\". # #",
"# Output: 2 # Explanation: The longest substring without any",
"# Output: 3 # Explanation: The longest substring without any",
"a string, find the length of the longest substring which",
"of the longest substring which has no repeating characters. #",
"substrings without any repeating characters are \"abc\" & \"cde\". #######################################################################################################################",
"characters is \"ab\". # # Input: String=\"abccde\" # Output: 3",
"max(max_window, i - window_start + 1) return max_window print(longest_substring_no_repeating_char('aabccbb')) print(longest_substring_no_repeating_char('abbbb'))",
"= max(window_start, is_present[char_ord] + 1) is_present[char_ord] = i max_window =",
"longest substring which has no repeating characters. # # Input:",
"+ 1) is_present[char_ord] = i max_window = max(max_window, i -",
"characters. # # Input: String=\"aabccbb\" # Output: 3 # Explanation:",
"substring without any repeating characters is \"ab\". # # Input:",
"Output: 3 # Explanation: Longest substrings without any repeating characters",
"0 for i in range(len(input_str)): char_ord = ord(input_str[i]) - 97",
"\"abc\" & \"cde\". ####################################################################################################################### def longest_substring_no_repeating_char(input_str: str) -> int: window_start",
"max(window_start, is_present[char_ord] + 1) is_present[char_ord] = i max_window = max(max_window,",
"= max(max_window, i - window_start + 1) return max_window print(longest_substring_no_repeating_char('aabccbb'))",
"string, find the length of the longest substring which has",
"any repeating characters are \"abc\" & \"cde\". ####################################################################################################################### def longest_substring_no_repeating_char(input_str:",
"max_window = 0 for i in range(len(input_str)): char_ord = ord(input_str[i])",
"= ord(input_str[i]) - 97 if is_present[char_ord] is not None: window_start",
"repeating characters is \"ab\". # # Input: String=\"abccde\" # Output:",
"\"ab\". # # Input: String=\"abccde\" # Output: 3 # Explanation:",
"range(26)] max_window = 0 for i in range(len(input_str)): char_ord =",
"= 0 is_present = [None for i in range(26)] max_window",
"+ 1) return max_window print(longest_substring_no_repeating_char('aabccbb')) print(longest_substring_no_repeating_char('abbbb')) print(longest_substring_no_repeating_char('abccde')) print(longest_substring_no_repeating_char('abcabcbb')) print(longest_substring_no_repeating_char('bbbbb')) print(longest_substring_no_repeating_char('pwwkew'))",
"no repeating characters. # # Input: String=\"aabccbb\" # Output: 3",
"Longest substrings without any repeating characters are \"abc\" & \"cde\".",
"String=\"abbbb\" # Output: 2 # Explanation: The longest substring without",
"String=\"abccde\" # Output: 3 # Explanation: Longest substrings without any",
"repeating characters. # # Input: String=\"aabccbb\" # Output: 3 #",
"is not None: window_start = max(window_start, is_present[char_ord] + 1) is_present[char_ord]",
"i max_window = max(max_window, i - window_start + 1) return",
"is \"abc\". # # Input: String=\"abbbb\" # Output: 2 #",
"The longest substring without any repeating characters is \"abc\". #",
"[None for i in range(26)] max_window = 0 for i",
"is_present[char_ord] is not None: window_start = max(window_start, is_present[char_ord] + 1)",
"max_window = max(max_window, i - window_start + 1) return max_window",
"-> int: window_start = 0 is_present = [None for i",
"ord(input_str[i]) - 97 if is_present[char_ord] is not None: window_start =",
"- window_start + 1) return max_window print(longest_substring_no_repeating_char('aabccbb')) print(longest_substring_no_repeating_char('abbbb')) print(longest_substring_no_repeating_char('abccde')) print(longest_substring_no_repeating_char('abcabcbb'))",
"repeating characters is \"abc\". # # Input: String=\"abbbb\" # Output:",
"Input: String=\"abbbb\" # Output: 2 # Explanation: The longest substring",
"# Input: String=\"abbbb\" # Output: 2 # Explanation: The longest",
"None: window_start = max(window_start, is_present[char_ord] + 1) is_present[char_ord] = i",
"# # Input: String=\"abbbb\" # Output: 2 # Explanation: The",
"the length of the longest substring which has no repeating",
"range(len(input_str)): char_ord = ord(input_str[i]) - 97 if is_present[char_ord] is not",
"Input: String=\"aabccbb\" # Output: 3 # Explanation: The longest substring",
"# Output: 3 # Explanation: Longest substrings without any repeating",
"any repeating characters is \"ab\". # # Input: String=\"abccde\" #",
"longest_substring_no_repeating_char(input_str: str) -> int: window_start = 0 is_present = [None",
"longest substring without any repeating characters is \"ab\". # #",
"- 97 if is_present[char_ord] is not None: window_start = max(window_start,",
"any repeating characters is \"abc\". # # Input: String=\"abbbb\" #",
"is_present = [None for i in range(26)] max_window = 0",
"\"cde\". ####################################################################################################################### def longest_substring_no_repeating_char(input_str: str) -> int: window_start = 0",
"####################################################################################################################### # Given a string, find the length of the",
"= [None for i in range(26)] max_window = 0 for",
"is_present[char_ord] + 1) is_present[char_ord] = i max_window = max(max_window, i",
"window_start = 0 is_present = [None for i in range(26)]",
"length of the longest substring which has no repeating characters.",
"i in range(26)] max_window = 0 for i in range(len(input_str)):",
"i - window_start + 1) return max_window print(longest_substring_no_repeating_char('aabccbb')) print(longest_substring_no_repeating_char('abbbb')) print(longest_substring_no_repeating_char('abccde'))",
"# Input: String=\"aabccbb\" # Output: 3 # Explanation: The longest",
"2 # Explanation: The longest substring without any repeating characters",
"# Explanation: Longest substrings without any repeating characters are \"abc\"",
"String=\"aabccbb\" # Output: 3 # Explanation: The longest substring without",
"# Input: String=\"abccde\" # Output: 3 # Explanation: Longest substrings",
"substring which has no repeating characters. # # Input: String=\"aabccbb\"",
"str) -> int: window_start = 0 is_present = [None for",
"Explanation: Longest substrings without any repeating characters are \"abc\" &",
"\"abc\". # # Input: String=\"abbbb\" # Output: 2 # Explanation:",
"window_start = max(window_start, is_present[char_ord] + 1) is_present[char_ord] = i max_window",
"for i in range(26)] max_window = 0 for i in",
"are \"abc\" & \"cde\". ####################################################################################################################### def longest_substring_no_repeating_char(input_str: str) -> int:",
"0 is_present = [None for i in range(26)] max_window =",
"i in range(len(input_str)): char_ord = ord(input_str[i]) - 97 if is_present[char_ord]",
"the longest substring which has no repeating characters. # #",
"in range(len(input_str)): char_ord = ord(input_str[i]) - 97 if is_present[char_ord] is",
"if is_present[char_ord] is not None: window_start = max(window_start, is_present[char_ord] +",
"3 # Explanation: The longest substring without any repeating characters",
"not None: window_start = max(window_start, is_present[char_ord] + 1) is_present[char_ord] =",
"& \"cde\". ####################################################################################################################### def longest_substring_no_repeating_char(input_str: str) -> int: window_start =",
"Input: String=\"abccde\" # Output: 3 # Explanation: Longest substrings without",
"Given a string, find the length of the longest substring",
"= i max_window = max(max_window, i - window_start + 1)",
"Explanation: The longest substring without any repeating characters is \"ab\".",
"Explanation: The longest substring without any repeating characters is \"abc\".",
"char_ord = ord(input_str[i]) - 97 if is_present[char_ord] is not None:",
"3 # Explanation: Longest substrings without any repeating characters are",
"# Explanation: The longest substring without any repeating characters is",
"find the length of the longest substring which has no",
"# # Input: String=\"abccde\" # Output: 3 # Explanation: Longest",
"is \"ab\". # # Input: String=\"abccde\" # Output: 3 #",
"repeating characters are \"abc\" & \"cde\". ####################################################################################################################### def longest_substring_no_repeating_char(input_str: str)",
"####################################################################################################################### def longest_substring_no_repeating_char(input_str: str) -> int: window_start = 0 is_present",
"97 if is_present[char_ord] is not None: window_start = max(window_start, is_present[char_ord]",
"has no repeating characters. # # Input: String=\"aabccbb\" # Output:",
"1) is_present[char_ord] = i max_window = max(max_window, i - window_start",
"Output: 3 # Explanation: The longest substring without any repeating",
"without any repeating characters is \"ab\". # # Input: String=\"abccde\"",
"in range(26)] max_window = 0 for i in range(len(input_str)): char_ord",
"Output: 2 # Explanation: The longest substring without any repeating",
"def longest_substring_no_repeating_char(input_str: str) -> int: window_start = 0 is_present =",
"substring without any repeating characters is \"abc\". # # Input:",
"# Given a string, find the length of the longest",
"characters are \"abc\" & \"cde\". ####################################################################################################################### def longest_substring_no_repeating_char(input_str: str) ->",
"int: window_start = 0 is_present = [None for i in",
"characters is \"abc\". # # Input: String=\"abbbb\" # Output: 2",
"The longest substring without any repeating characters is \"ab\". #",
"without any repeating characters are \"abc\" & \"cde\". ####################################################################################################################### def",
"without any repeating characters is \"abc\". # # Input: String=\"abbbb\"",
"= 0 for i in range(len(input_str)): char_ord = ord(input_str[i]) -",
"window_start + 1) return max_window print(longest_substring_no_repeating_char('aabccbb')) print(longest_substring_no_repeating_char('abbbb')) print(longest_substring_no_repeating_char('abccde')) print(longest_substring_no_repeating_char('abcabcbb')) print(longest_substring_no_repeating_char('bbbbb'))",
"which has no repeating characters. # # Input: String=\"aabccbb\" #",
"for i in range(len(input_str)): char_ord = ord(input_str[i]) - 97 if",
"# # Input: String=\"aabccbb\" # Output: 3 # Explanation: The"
] |
[
"Latitude, Longitude, Altitude, Timezone, DST, Timezone in Olson format Sample",
"Then remove all the airports which are located in United",
"= airportPairRDD.filter( lambda keyValue: keyValue[1] != \"\\\"United States\\\"\") airportsNotInUSA.saveAsTextFile( \"outputs/airports_not_in_usa_pair_rdd.text\")",
"the airports which are located in United States and output",
"with Python - Big Data with PySpark and Spark/6-PairRDD/filter/AirportsNotInUsa.py import",
"New Guinea\") ... ''' conf = SparkConf().setAppName(\"airports\").setMaster(\"local[*]\") sc = SparkContext(conf=conf)",
"and country name being the value. Then remove all the",
"Timezone in Olson format Sample output: (\"Kamloops\", \"Canada\") (\"Wewak Intl\",",
"Main city served by airport, Country where airport is located,",
"Big Data with PySpark and Spark/6-PairRDD/filter/AirportsNotInUsa.py import sys sys.path.insert(0, '.')",
"United States and output the pair RDD to out/airports_not_in_usa_pair_rdd.text Each",
"the following columns: Airport ID, Name of airport, Main city",
"conf = SparkConf().setAppName(\"airports\").setMaster(\"local[*]\") sc = SparkContext(conf=conf) airportsRDD = sc.textFile(\"inputs/airports.text\") airportPairRDD",
"= airportsRDD.map(lambda line: (Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA = airportPairRDD.filter( lambda keyValue:",
"columns: Airport ID, Name of airport, Main city served by",
"read the airport data from in/airports.text; generate a pair RDD",
"served by airport, Country where airport is located, IATA/FAA code,",
"airport, Country where airport is located, IATA/FAA code, ICAO Code,",
"of airport, Main city served by airport, Country where airport",
"in United States and output the pair RDD to out/airports_not_in_usa_pair_rdd.text",
"Country where airport is located, IATA/FAA code, ICAO Code, Latitude,",
"SparkConf().setAppName(\"airports\").setMaster(\"local[*]\") sc = SparkContext(conf=conf) airportsRDD = sc.textFile(\"inputs/airports.text\") airportPairRDD = airportsRDD.map(lambda",
"the input file contains the following columns: Airport ID, Name",
"RDD to out/airports_not_in_usa_pair_rdd.text Each row of the input file contains",
"airportsRDD = sc.textFile(\"inputs/airports.text\") airportPairRDD = airportsRDD.map(lambda line: (Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA",
"import SparkContext, SparkConf from commons.Utils import Utils if __name__ ==",
"SparkContext(conf=conf) airportsRDD = sc.textFile(\"inputs/airports.text\") airportPairRDD = airportsRDD.map(lambda line: (Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3]))",
"pyspark import SparkContext, SparkConf from commons.Utils import Utils if __name__",
"sys.path.insert(0, '.') from pyspark import SparkContext, SparkConf from commons.Utils import",
"out/airports_not_in_usa_pair_rdd.text Each row of the input file contains the following",
"name being the key and country name being the value.",
"commons.Utils import Utils if __name__ == \"__main__\": ''' Create a",
"airport, Main city served by airport, Country where airport is",
"Each row of the input file contains the following columns:",
"Python - Big Data with PySpark and Spark/6-PairRDD/filter/AirportsNotInUsa.py import sys",
"= SparkContext(conf=conf) airportsRDD = sc.textFile(\"inputs/airports.text\") airportPairRDD = airportsRDD.map(lambda line: (Utils.COMMA_DELIMITER.split(line)[1],",
"output: (\"Kamloops\", \"Canada\") (\"Wewak Intl\", \"Papua New Guinea\") ... '''",
"(\"Kamloops\", \"Canada\") (\"Wewak Intl\", \"Papua New Guinea\") ... ''' conf",
"name being the value. Then remove all the airports which",
"Create a Spark program to read the airport data from",
"a pair RDD with airport name being the key and",
"'.') from pyspark import SparkContext, SparkConf from commons.Utils import Utils",
"where airport is located, IATA/FAA code, ICAO Code, Latitude, Longitude,",
"in Olson format Sample output: (\"Kamloops\", \"Canada\") (\"Wewak Intl\", \"Papua",
"airportsRDD.map(lambda line: (Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA = airportPairRDD.filter( lambda keyValue: keyValue[1]",
"code, ICAO Code, Latitude, Longitude, Altitude, Timezone, DST, Timezone in",
"of the input file contains the following columns: Airport ID,",
"located, IATA/FAA code, ICAO Code, Latitude, Longitude, Altitude, Timezone, DST,",
"the airport data from in/airports.text; generate a pair RDD with",
"DST, Timezone in Olson format Sample output: (\"Kamloops\", \"Canada\") (\"Wewak",
"to out/airports_not_in_usa_pair_rdd.text Each row of the input file contains the",
"Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA = airportPairRDD.filter( lambda keyValue: keyValue[1] != \"\\\"United States\\\"\")",
"Name of airport, Main city served by airport, Country where",
"remove all the airports which are located in United States",
"with airport name being the key and country name being",
"\"Papua New Guinea\") ... ''' conf = SparkConf().setAppName(\"airports\").setMaster(\"local[*]\") sc =",
"Spark with Python - Big Data with PySpark and Spark/6-PairRDD/filter/AirportsNotInUsa.py",
"value. Then remove all the airports which are located in",
"import sys sys.path.insert(0, '.') from pyspark import SparkContext, SparkConf from",
"airportPairRDD = airportsRDD.map(lambda line: (Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA = airportPairRDD.filter( lambda",
"airport data from in/airports.text; generate a pair RDD with airport",
"Spark/6-PairRDD/filter/AirportsNotInUsa.py import sys sys.path.insert(0, '.') from pyspark import SparkContext, SparkConf",
"are located in United States and output the pair RDD",
"\"__main__\": ''' Create a Spark program to read the airport",
"<filename>Apache Spark with Python - Big Data with PySpark and",
"all the airports which are located in United States and",
"a Spark program to read the airport data from in/airports.text;",
"''' conf = SparkConf().setAppName(\"airports\").setMaster(\"local[*]\") sc = SparkContext(conf=conf) airportsRDD = sc.textFile(\"inputs/airports.text\")",
"output the pair RDD to out/airports_not_in_usa_pair_rdd.text Each row of the",
"pair RDD to out/airports_not_in_usa_pair_rdd.text Each row of the input file",
"generate a pair RDD with airport name being the key",
"PySpark and Spark/6-PairRDD/filter/AirportsNotInUsa.py import sys sys.path.insert(0, '.') from pyspark import",
"sys sys.path.insert(0, '.') from pyspark import SparkContext, SparkConf from commons.Utils",
"import Utils if __name__ == \"__main__\": ''' Create a Spark",
"by airport, Country where airport is located, IATA/FAA code, ICAO",
"Timezone, DST, Timezone in Olson format Sample output: (\"Kamloops\", \"Canada\")",
"\"Canada\") (\"Wewak Intl\", \"Papua New Guinea\") ... ''' conf =",
"(\"Wewak Intl\", \"Papua New Guinea\") ... ''' conf = SparkConf().setAppName(\"airports\").setMaster(\"local[*]\")",
"airportsNotInUSA = airportPairRDD.filter( lambda keyValue: keyValue[1] != \"\\\"United States\\\"\") airportsNotInUSA.saveAsTextFile(",
"Olson format Sample output: (\"Kamloops\", \"Canada\") (\"Wewak Intl\", \"Papua New",
"airports which are located in United States and output the",
"which are located in United States and output the pair",
"key and country name being the value. Then remove all",
"= sc.textFile(\"inputs/airports.text\") airportPairRDD = airportsRDD.map(lambda line: (Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA =",
"Data with PySpark and Spark/6-PairRDD/filter/AirportsNotInUsa.py import sys sys.path.insert(0, '.') from",
"with PySpark and Spark/6-PairRDD/filter/AirportsNotInUsa.py import sys sys.path.insert(0, '.') from pyspark",
"''' Create a Spark program to read the airport data",
"if __name__ == \"__main__\": ''' Create a Spark program to",
"to read the airport data from in/airports.text; generate a pair",
"== \"__main__\": ''' Create a Spark program to read the",
"input file contains the following columns: Airport ID, Name of",
"following columns: Airport ID, Name of airport, Main city served",
"Guinea\") ... ''' conf = SparkConf().setAppName(\"airports\").setMaster(\"local[*]\") sc = SparkContext(conf=conf) airportsRDD",
"Code, Latitude, Longitude, Altitude, Timezone, DST, Timezone in Olson format",
"and Spark/6-PairRDD/filter/AirportsNotInUsa.py import sys sys.path.insert(0, '.') from pyspark import SparkContext,",
"being the key and country name being the value. Then",
"sc = SparkContext(conf=conf) airportsRDD = sc.textFile(\"inputs/airports.text\") airportPairRDD = airportsRDD.map(lambda line:",
"= SparkConf().setAppName(\"airports\").setMaster(\"local[*]\") sc = SparkContext(conf=conf) airportsRDD = sc.textFile(\"inputs/airports.text\") airportPairRDD =",
"Airport ID, Name of airport, Main city served by airport,",
"RDD with airport name being the key and country name",
"the value. Then remove all the airports which are located",
"airport name being the key and country name being the",
"the key and country name being the value. Then remove",
"... ''' conf = SparkConf().setAppName(\"airports\").setMaster(\"local[*]\") sc = SparkContext(conf=conf) airportsRDD =",
"(Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA = airportPairRDD.filter( lambda keyValue: keyValue[1] != \"\\\"United",
"__name__ == \"__main__\": ''' Create a Spark program to read",
"from in/airports.text; generate a pair RDD with airport name being",
"the pair RDD to out/airports_not_in_usa_pair_rdd.text Each row of the input",
"located in United States and output the pair RDD to",
"ID, Name of airport, Main city served by airport, Country",
"from pyspark import SparkContext, SparkConf from commons.Utils import Utils if",
"format Sample output: (\"Kamloops\", \"Canada\") (\"Wewak Intl\", \"Papua New Guinea\")",
"program to read the airport data from in/airports.text; generate a",
"Sample output: (\"Kamloops\", \"Canada\") (\"Wewak Intl\", \"Papua New Guinea\") ...",
"in/airports.text; generate a pair RDD with airport name being the",
"Spark program to read the airport data from in/airports.text; generate",
"and output the pair RDD to out/airports_not_in_usa_pair_rdd.text Each row of",
"SparkConf from commons.Utils import Utils if __name__ == \"__main__\": '''",
"ICAO Code, Latitude, Longitude, Altitude, Timezone, DST, Timezone in Olson",
"Intl\", \"Papua New Guinea\") ... ''' conf = SparkConf().setAppName(\"airports\").setMaster(\"local[*]\") sc",
"Utils if __name__ == \"__main__\": ''' Create a Spark program",
"from commons.Utils import Utils if __name__ == \"__main__\": ''' Create",
"file contains the following columns: Airport ID, Name of airport,",
"- Big Data with PySpark and Spark/6-PairRDD/filter/AirportsNotInUsa.py import sys sys.path.insert(0,",
"is located, IATA/FAA code, ICAO Code, Latitude, Longitude, Altitude, Timezone,",
"Altitude, Timezone, DST, Timezone in Olson format Sample output: (\"Kamloops\",",
"being the value. Then remove all the airports which are",
"pair RDD with airport name being the key and country",
"contains the following columns: Airport ID, Name of airport, Main",
"country name being the value. Then remove all the airports",
"city served by airport, Country where airport is located, IATA/FAA",
"data from in/airports.text; generate a pair RDD with airport name",
"States and output the pair RDD to out/airports_not_in_usa_pair_rdd.text Each row",
"line: (Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA = airportPairRDD.filter( lambda keyValue: keyValue[1] !=",
"sc.textFile(\"inputs/airports.text\") airportPairRDD = airportsRDD.map(lambda line: (Utils.COMMA_DELIMITER.split(line)[1], Utils.COMMA_DELIMITER.split(line)[3])) airportsNotInUSA = airportPairRDD.filter(",
"Longitude, Altitude, Timezone, DST, Timezone in Olson format Sample output:",
"row of the input file contains the following columns: Airport",
"IATA/FAA code, ICAO Code, Latitude, Longitude, Altitude, Timezone, DST, Timezone",
"airport is located, IATA/FAA code, ICAO Code, Latitude, Longitude, Altitude,",
"SparkContext, SparkConf from commons.Utils import Utils if __name__ == \"__main__\":"
] |
[
"+ kmp['packageID'] + \"/share\" if not path.isfile(path_qr): qr = qrcode.QRCode(",
"lbl_share_kbd self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) self.get_content_area().pack_start(grid, True, True, 12) self.resize(800, 450) self.show_all()",
"show the icon somewhere lbl_kbd_file = Gtk.Label() lbl_kbd_file.set_text(_(\"Keyboard filename: \"))",
"1) lbl_share_kbd = Gtk.Label() lbl_share_kbd.set_markup(_(\"Scan this code to load this",
"label = Gtk.Label() label.set_text(path.join(packageDir, kbd['id'] + \".kmx\")) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"supported languages, fonts # from kmx?: keyboard version, encoding, layout",
"grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) # label7 = Gtk.Label() #",
"1, 1) lbl_pkg_vrs = Gtk.Label() lbl_pkg_vrs.set_text(_(\"Package version: \")) lbl_pkg_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_vrs,",
"lbl_pkg_auth label = Gtk.Label() if secure_lookup(info, 'author', 'description'): label.set_text(secure_lookup(info, 'author',",
"= Gtk.Label() # label.set_line_wrap(True) # label.set_text( # \"This keyboard is",
"= qr.make_image() img.save(path_qr) # Display QR Code, spanning 2 columns",
"1, 1) prevlabel = lbl_kbd_file label = Gtk.Label() label.set_text(path.join(packageDir, kbd['id']",
"\"kmp.json\") info, system, options, keyboards, files = parsemetadata(kmp_json) if info",
"label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_kbd_desc, Gtk.PositionType.RIGHT, 1, 1) #",
"'packageID'): lbl_kbd_name = Gtk.Label() lbl_kbd_name.set_text(_(\"Keyboard name: \")) lbl_kbd_name.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_name, prevlabel,",
"1) prevlabel = lbl_kbd_lic label = Gtk.Label() if secure_lookup(kbdata, 'license'):",
"Keyboard details window import logging import json from os import",
"installed\")) # # label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # # grid.attach_next_to(label,",
"lbl_share_kbd.set_line_wrap(True) grid.attach_next_to(lbl_share_kbd, image, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_share_kbd self.add_button(_(\"_Close\"),",
"= Gtk.Label() lbl_invalid_metadata.set_text(_(\"ERROR: Keyboard metadata is damaged.\\nPlease \\\"Uninstall\\\" and then",
"1, 1) prevlabel = lbl_kbd_lic label = Gtk.Label() if secure_lookup(kbdata,",
"1) prevlabel = lbl_kbd_auth label = Gtk.Label() if secure_lookup(kbdata, 'authorName'):",
"# else: # # label.set_text(_(\"Not installed\")) # # label.set_halign(Gtk.Align.START) #",
"kmp[\"id\"] + \".json\") # Package info lbl_pkg_name = Gtk.Label() lbl_pkg_name.set_text(_(\"Package",
"path.join(packageDir, kbd['id'] + \".json\") if path.isfile(jsonfile): try: with open(jsonfile, \"r\")",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label9 # label",
"(MIT) as described somewhere\") # #label.set_text(kmp[\"description\"]) # label.set_halign(Gtk.Align.START) # label.set_selectable(True)",
"1, 1) if kbdata and secure_lookup(kbdata, 'id') != secure_lookup(kmp, 'packageID'):",
"if not path.isfile(path_qr): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=4, border=4)",
"# label.set_halign(Gtk.Align.START) # label.set_selectable(True) # grid.attach_next_to(label, label9, Gtk.PositionType.RIGHT, 1, 1)",
"json.load(read_file) except Exception as e: logging.warning('Exception %s reading %s %s',",
"is distributed under the MIT license (MIT) as described somewhere\")",
"label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_auth, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"copyright\"): lbl_pkg_cpy",
"description # other things: filename (of kmx), , # OSK",
"= Gtk.Label() lbl_kbd_file.set_text(_(\"Keyboard filename: \")) lbl_kbd_file.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_file, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"= lbl_kbd_name label = Gtk.Label() if secure_lookup(kbdata, 'name'): label.set_text(kbdata['name']) label.set_halign(Gtk.Align.START)",
"qr.make(fit=True) img = qr.make_image() img.save(path_qr) # Display QR Code, spanning",
"'version', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_vrs, Gtk.PositionType.RIGHT, 1, 1) if",
"lbl_pkg_auth.set_text(_(\"Package author: \")) lbl_pkg_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"Gtk.Label() lbl_kbd_desc.set_text(_(\"Keyboard description: \")) lbl_kbd_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"Gtk.Label() label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_pkg_desc, Gtk.PositionType.RIGHT, 1, 1)",
"'license'): label.set_text(kbdata['license']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_lic, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_desc",
"# label.set_selectable(True) # grid.attach_next_to(label, label9, Gtk.PositionType.RIGHT, 1, 1) # Add",
"in kmp.inf/kmp.json # there is possibly data in kbid.json (downloaded",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_pkg_desc, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info,",
"kmp[\"id\"], kmp[\"id\"] + \".json\") # Package info lbl_pkg_name = Gtk.Label()",
"label.set_text(kbdata['authorName']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_auth, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_lic =",
"# Add an entire row of padding lbl_pad = Gtk.Label()",
"label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"): lbl_kbd_auth",
"= Gtk.Label() if secure_lookup(kbdata, 'license'): label.set_text(kbdata['license']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_lic,",
"grid.attach_next_to(lbl_share_kbd, image, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_share_kbd self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE)",
"1, 1) prevlabel = lbl_pkg_vrs label = Gtk.Label() if secure_lookup(info,",
"secure_lookup(info, \"author\"): lbl_pkg_auth = Gtk.Label() lbl_pkg_auth.set_text(_(\"Package author: \")) lbl_pkg_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_auth,",
"\")) lbl_kbd_file.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_file, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_file",
"if secure_lookup(kbdata, 'license'): label.set_text(kbdata['license']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_lic, Gtk.PositionType.RIGHT, 1,",
"Gtk.Label() if secure_lookup(info, 'name', 'description'): label.set_text(secure_lookup(info, 'name', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"license: \")) lbl_kbd_lic.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_lic, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel =",
"\"welcome.htm\") # # if path.isfile(welcome_file): # # label.set_text(_(\"Installed\")) # #",
"lbl_pkg_cpy = Gtk.Label() lbl_pkg_cpy.set_text(_(\"Package copyright: \")) lbl_pkg_cpy.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_cpy, prevlabel, Gtk.PositionType.BOTTOM,",
"lbl_kbd_id, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_vrs = Gtk.Label() lbl_kbd_vrs.set_text(_(\"Keyboard version: \"))",
"import init_accel from keyman_config.kmpmetadata import parsemetadata gi.require_version('Gtk', '3.0') # basics:",
"version, description # other things: filename (of kmx), , #",
"kmp['packageID'] + \".json\") if path.isfile(jsonfile): try: with open(jsonfile, \"r\") as",
"if secure_lookup(info, 'name', 'description'): label.set_text(secure_lookup(info, 'name', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_cpy label = Gtk.Label() if",
"with padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM,",
"= Gtk.Label() lbl_kbd_vrs.set_text(_(\"Keyboard version: \")) lbl_kbd_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"secure_lookup(kbdata, 'license'): label.set_text(kbdata['license']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_lic, Gtk.PositionType.RIGHT, 1, 1)",
"# kbdatapath = path.join(\"/usr/local/share/keyman\", kmp[\"id\"], kmp[\"id\"] + \".json\") # Package",
"1) # prevlabel = label9 # label = Gtk.Label() #",
"somewhere\") # #label.set_text(kmp[\"description\"]) # label.set_halign(Gtk.Align.START) # label.set_selectable(True) # grid.attach_next_to(label, label9,",
"\"/go/keyboard/\" + kmp['packageID'] + \"/share\" if not path.isfile(path_qr): qr =",
"# grid.attach_next_to(label9, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label9",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_lic label = Gtk.Label()",
"grid = Gtk.Grid() self.get_content_area().pack_start(grid, True, True, 12) lbl_invalid_metadata = Gtk.Label()",
"secure_lookup(kmp, 'packageID'): label.set_text(kmp['packageID']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_id, Gtk.PositionType.RIGHT, 1, 1)",
"= Gtk.Label() if secure_lookup(kbdata, 'name'): label.set_text(kbdata['name']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_name,",
"damaged.\\nPlease \\\"Uninstall\\\" and then \\\"Install\\\" the keyboard.\")) lbl_invalid_metadata.set_halign(Gtk.Align.END) grid.add(lbl_invalid_metadata) self.resize(700,",
"# \"This keyboard is distributed under the MIT license (MIT)",
"lbl_pkg_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_vrs label",
"# # label.set_selectable(True) # # grid.attach_next_to(label, label8, Gtk.PositionType.RIGHT, 1, 1)",
"lbl_pkg_cpy.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_cpy, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_cpy label",
"Gtk.Label() lbl_pkg_vrs.set_text(_(\"Package version: \")) lbl_pkg_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"this code to load this keyboard\\non another device or <a",
"lbl_kbd_desc label = Gtk.Label() if secure_lookup(kbdata, 'description'): label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"that is available # especially what is displayed for Keyman",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_id label = Gtk.Label() if",
"label.set_text(_(\"Not installed\")) # # label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # #",
"grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad # show",
"1) prevlabel = lbl_pkg_id label = Gtk.Label() if secure_lookup(kmp, 'packageID'):",
"# Dialog when invalid metadata self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) grid = Gtk.Grid()",
"lbl_kbd_vrs.set_text(_(\"Keyboard version: \")) lbl_kbd_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"# # label = Gtk.Label() # # label.set_text(secure_lookup(info, 'version', 'description'))",
"import tempfile import gi from gi.repository import Gtk from keyman_config",
"lbl_kbd_auth label = Gtk.Label() if secure_lookup(kbdata, 'authorName'): label.set_text(kbdata['authorName']) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"Gtk.Label() lbl_pkg_auth.set_text(_(\"Package author: \")) lbl_pkg_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"self.set_border_width(6) packageDir = path.join(kmp['areapath'], kmp['packageID']) kmp_json = path.join(packageDir, \"kmp.json\") info,",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_name label = Gtk.Label()",
"lbl_share_kbd.set_markup(_(\"Scan this code to load this keyboard\\non another device or",
"import json from os import path import qrcode import tempfile",
"label.set_text(kbdata['id']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_id, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_vrs =",
"# # welcome_file = path.join(\"/usr/local/share/doc/keyman\", kmp[\"id\"], \"welcome.htm\") # # if",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_id label = Gtk.Label()",
"Gtk.Label() # label.set_line_wrap(True) # label.set_text( # \"This keyboard is distributed",
"Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"): lbl_kbd_auth = Gtk.Label() lbl_kbd_auth.set_text(_(\"Keyboard",
"img.save(path_qr) # Display QR Code, spanning 2 columns so it",
"1, 1) lbl_kbd_id = Gtk.Label() lbl_kbd_id.set_text(_(\"Keyboard id: \")) lbl_kbd_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_id,",
"= lbl_pkg_vrs label = Gtk.Label() if secure_lookup(info, 'version', 'description'): label.set_text(secure_lookup(info,",
"parent, kmp): # kmp has name, version, packageID, area if",
"data in kbid.json (downloaded from api) class KeyboardDetailsView(Gtk.Dialog): # TODO",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_vrs label = Gtk.Label()",
"Gtk.Label() if secure_lookup(kbdata, 'version'): label.set_text(kbdata['version']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_vrs, Gtk.PositionType.RIGHT,",
"prevlabel = lbl_pkg_cpy label = Gtk.Label() if secure_lookup(info, 'copyright', 'description'):",
"True, 12) lbl_invalid_metadata = Gtk.Label() lbl_invalid_metadata.set_text(_(\"ERROR: Keyboard metadata is damaged.\\nPlease",
"import logging import json from os import path import qrcode",
"availability, package copyright # also: supported languages, fonts # from",
"None: # Dialog when invalid metadata self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) grid =",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_cpy label = Gtk.Label()",
"# TODO Display all the information that is available #",
"Gtk.PositionType.RIGHT, 1, 1) # label9 = Gtk.Label() # # stored",
"from os import path import qrcode import tempfile import gi",
"the MIT license (MIT) as described somewhere\") # #label.set_text(kmp[\"description\"]) #",
"online</a>\").format(uri=url)) lbl_share_kbd.set_halign(Gtk.Align.CENTER) lbl_share_kbd.set_line_wrap(True) grid.attach_next_to(lbl_share_kbd, image, Gtk.PositionType.BOTTOM, 2, 1) prevlabel =",
"1) prevlabel = lbl_pad # show the icon somewhere lbl_kbd_file",
"= qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=4, border=4) qr.add_data(url) qr.make(fit=True) img =",
"= label7 # # label = Gtk.Label() # # label.set_text(secure_lookup(info,",
"'description'): label.set_text(secure_lookup(info, 'name', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_name, Gtk.PositionType.RIGHT, 1,",
"lbl_kbd_lic.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_lic, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_lic label",
"label.set_text(kbdata['version']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info,",
"\")) lbl_pkg_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_auth",
"%s', type(e), jsonfile, e.args) grid = Gtk.Grid() # grid.set_column_homogeneous(True) #",
"Gtk.Label() lbl_invalid_metadata.set_text(_(\"ERROR: Keyboard metadata is damaged.\\nPlease \\\"Uninstall\\\" and then \\\"Install\\\"",
"KeyboardDetailsView(Gtk.Dialog): # TODO Display all the information that is available",
"lbl_pkg_vrs label = Gtk.Label() if secure_lookup(info, 'version', 'description'): label.set_text(secure_lookup(info, 'version',",
"grid.attach_next_to(label, lbl_pkg_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(kbdata, 'description'): lbl_pkg_desc =",
"need to know which area keyboard is installed in to",
"'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(kbdata,",
"box_size=4, border=4) qr.add_data(url) qr.make(fit=True) img = qr.make_image() img.save(path_qr) # Display",
"kmp has name, version, packageID, area if \"keyboard\" in kmp[\"name\"].lower():",
"when invalid metadata self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) grid = Gtk.Grid() self.get_content_area().pack_start(grid, True,",
"= label8 # #TODO need to know which area keyboard",
"Display QR Code, spanning 2 columns so it will be",
"Gtk.PositionType.BOTTOM, 2, 1) lbl_share_kbd = Gtk.Label() lbl_share_kbd.set_markup(_(\"Scan this code to",
"# Keyboard info for each keyboard if keyboards: for kbd",
"if keyboards: for kbd in keyboards: kbdata = None jsonfile",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label7 # #",
"\")) # label8.set_halign(Gtk.Align.END) # grid.attach_next_to(label8, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) #",
"'id') != secure_lookup(kmp, 'packageID'): lbl_kbd_name = Gtk.Label() lbl_kbd_name.set_text(_(\"Keyboard name: \"))",
"wintitle = _(\"{name} keyboard\").format(name=kmp[\"name\"]) Gtk.Dialog.__init__(self, wintitle, parent) init_accel(self) self.set_border_width(6) packageDir",
"lbl_pkg_auth = Gtk.Label() lbl_pkg_auth.set_text(_(\"Package author: \")) lbl_pkg_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_auth, prevlabel, Gtk.PositionType.BOTTOM,",
"lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad",
"1) lbl_kbd_vrs = Gtk.Label() lbl_kbd_vrs.set_text(_(\"Keyboard version: \")) lbl_kbd_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_vrs, prevlabel,",
"version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=4, border=4) qr.add_data(url) qr.make(fit=True) img = qr.make_image() img.save(path_qr)",
"kmp[\"name\"].lower(): wintitle = kmp[\"name\"] else: wintitle = _(\"{name} keyboard\").format(name=kmp[\"name\"]) Gtk.Dialog.__init__(self,",
"Gtk.Label() # # welcome_file = path.join(\"/usr/local/share/doc/keyman\", kmp[\"id\"], \"welcome.htm\") # #",
"metadata self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) grid = Gtk.Grid() self.get_content_area().pack_start(grid, True, True, 12)",
"Gtk.PositionType.RIGHT, 1, 1) # Padding and full width horizontal divider",
"# label9 = Gtk.Label() # # stored in kmx #",
"Keyboard info for each keyboard if keyboards: for kbd in",
"keyboard name, package version, description # other things: filename (of",
"stored in kmx # label9.set_text(_(\"Message: \")) # label9.set_halign(Gtk.Align.END) # grid.attach_next_to(label9,",
"lbl_pkg_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_id label",
"parent) init_accel(self) self.set_border_width(6) packageDir = path.join(kmp['areapath'], kmp['packageID']) kmp_json = path.join(packageDir,",
"version, encoding, layout type # there is data in kmp.inf/kmp.json",
"author: \")) lbl_pkg_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"path.join(packageDir, kmp['packageID'] + \".json\") if path.isfile(jsonfile): try: with open(jsonfile, \"r\")",
"+ '_qrcode.png') url = KeymanComUrl + \"/go/keyboard/\" + kmp['packageID'] +",
"import path import qrcode import tempfile import gi from gi.repository",
"lbl_pkg_vrs.set_text(_(\"Package version: \")) lbl_pkg_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"availability, documentation availability, package copyright # also: supported languages, fonts",
"\")) lbl_kbd_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_auth",
"+ \"/share\" if not path.isfile(path_qr): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H,",
"Gtk.Label() if secure_lookup(info, 'copyright', 'description'): label.set_text(secure_lookup(info, 'copyright', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) grid = Gtk.Grid() self.get_content_area().pack_start(grid, True, True, 12) lbl_invalid_metadata",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_desc label = Gtk.Label()",
"2, 1) prevlabel = lbl_pad # show the icon somewhere",
"2, 1) lbl_share_kbd = Gtk.Label() lbl_share_kbd.set_markup(_(\"Scan this code to load",
"the keyboard.\")) lbl_invalid_metadata.set_halign(Gtk.Align.END) grid.add(lbl_invalid_metadata) self.resize(700, 200) self.show_all() return kbdata =",
"secure_lookup(kbdata, 'id') != secure_lookup(kmp, 'packageID'): lbl_kbd_name = Gtk.Label() lbl_kbd_name.set_text(_(\"Keyboard name:",
"secure_lookup(kmp, 'packageID'): lbl_kbd_name = Gtk.Label() lbl_kbd_name.set_text(_(\"Keyboard name: \")) lbl_kbd_name.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_name,",
"# prevlabel = label7 # # label = Gtk.Label() #",
"'description'): label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_kbd_desc, Gtk.PositionType.RIGHT, 1, 1)",
"Gtk.Label() if secure_lookup(kmp, 'packageID'): label.set_text(kmp['packageID']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_id, Gtk.PositionType.RIGHT,",
"all the information that is available # especially what is",
"= Gtk.Label() # # label.set_text(secure_lookup(info, 'version', 'description')) # # label.set_halign(Gtk.Align.START)",
"will be centered image = Gtk.Image() image.set_from_file(path_qr) grid.attach_next_to(image, prevlabel, Gtk.PositionType.BOTTOM,",
"know which area keyboard is installed in to show this",
"= Gtk.Label() lbl_pkg_cpy.set_text(_(\"Package copyright: \")) lbl_pkg_cpy.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_cpy, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"# grid.attach_next_to(label, label9, Gtk.PositionType.RIGHT, 1, 1) # Add an entire",
"secure_lookup(info, 'copyright', 'description'): label.set_text(secure_lookup(info, 'copyright', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_cpy,",
"qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=4, border=4) qr.add_data(url) qr.make(fit=True) img = qr.make_image()",
"lbl_share_kbd.set_halign(Gtk.Align.CENTER) lbl_share_kbd.set_line_wrap(True) grid.attach_next_to(lbl_share_kbd, image, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_share_kbd",
"import parsemetadata gi.require_version('Gtk', '3.0') # basics: keyboard name, package version,",
"# label8 = Gtk.Label() # label8.set_text(_(\"Documentation: \")) # label8.set_halign(Gtk.Align.END) #",
"distributed under the MIT license (MIT) as described somewhere\") #",
"grid.attach_next_to(label, label8, Gtk.PositionType.RIGHT, 1, 1) # label9 = Gtk.Label() #",
"return kbdata = None jsonfile = path.join(packageDir, kmp['packageID'] + \".json\")",
"# OSK availability, documentation availability, package copyright # also: supported",
"lbl_kbd_auth.set_text(_(\"Keyboard author: \")) lbl_kbd_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"\")) # label9.set_halign(Gtk.Align.END) # grid.attach_next_to(label9, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) #",
"lbl_invalid_metadata = Gtk.Label() lbl_invalid_metadata.set_text(_(\"ERROR: Keyboard metadata is damaged.\\nPlease \\\"Uninstall\\\" and",
"1) # Add an entire row of padding lbl_pad =",
"packageID, area if \"keyboard\" in kmp[\"name\"].lower(): wintitle = kmp[\"name\"] else:",
"type(e), jsonfile, e.args) grid = Gtk.Grid() # grid.set_column_homogeneous(True) # kbdatapath",
"path.join(kmp['areapath'], kmp['packageID']) kmp_json = path.join(packageDir, \"kmp.json\") info, system, options, keyboards,",
"label = Gtk.Label() if secure_lookup(info, 'name', 'description'): label.set_text(secure_lookup(info, 'name', 'description'))",
"Display all the information that is available # especially what",
"= Gtk.Label() lbl_pkg_auth.set_text(_(\"Package author: \")) lbl_pkg_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_auth, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = divider_pkg # Keyboard info",
"kbd in keyboards: kbdata = None jsonfile = path.join(packageDir, kbd['id']",
"= path.join(packageDir, kbd['id'] + \".json\") if path.isfile(jsonfile): try: with open(jsonfile,",
"= lbl_kbd_file label = Gtk.Label() label.set_text(path.join(packageDir, kbd['id'] + \".kmx\")) label.set_halign(Gtk.Align.START)",
"Gtk.Dialog.__init__(self, wintitle, parent) init_accel(self) self.set_border_width(6) packageDir = path.join(kmp['areapath'], kmp['packageID']) kmp_json",
"1, 1) lbl_kbd_vrs = Gtk.Label() lbl_kbd_vrs.set_text(_(\"Keyboard version: \")) lbl_kbd_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_vrs,",
"keyboard\").format(name=kmp[\"name\"]) Gtk.Dialog.__init__(self, wintitle, parent) init_accel(self) self.set_border_width(6) packageDir = path.join(kmp['areapath'], kmp['packageID'])",
"on Windows # TODO clean up file once have what",
"import Gtk from keyman_config import KeymanComUrl, _, secure_lookup from keyman_config.accelerators",
"label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(kbdata, 'description'): lbl_pkg_desc",
"1) if secure_lookup(info, \"copyright\"): lbl_pkg_cpy = Gtk.Label() lbl_pkg_cpy.set_text(_(\"Package copyright: \"))",
"lbl_kbd_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_desc label",
"secure_lookup(info, \"author\"): lbl_kbd_auth = Gtk.Label() lbl_kbd_auth.set_text(_(\"Keyboard author: \")) lbl_kbd_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_auth,",
"lbl_kbd_lic label = Gtk.Label() if secure_lookup(kbdata, 'license'): label.set_text(kbdata['license']) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"lbl_pad # show the icon somewhere lbl_kbd_file = Gtk.Label() lbl_kbd_file.set_text(_(\"Keyboard",
"'author', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_auth, Gtk.PositionType.RIGHT, 1, 1) if",
"grid.attach_next_to(label, lbl_kbd_name, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_id = Gtk.Label() lbl_kbd_id.set_text(_(\"Keyboard id:",
"%s', type(e), jsonfile, e.args) # start with padding lbl_pad =",
"qrcode import tempfile import gi from gi.repository import Gtk from",
"'copyright', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_cpy, Gtk.PositionType.RIGHT, 1, 1) #",
"lbl_kbd_vrs = Gtk.Label() lbl_kbd_vrs.set_text(_(\"Keyboard version: \")) lbl_kbd_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_vrs, prevlabel, Gtk.PositionType.BOTTOM,",
"lbl_kbd_name = Gtk.Label() lbl_kbd_name.set_text(_(\"Keyboard name: \")) lbl_kbd_name.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_name, prevlabel, Gtk.PositionType.BOTTOM,",
"grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = divider_pkg # Keyboard",
"grid.attach_next_to(label, lbl_kbd_file, Gtk.PositionType.RIGHT, 1, 1) if kbdata and secure_lookup(kbdata, 'id')",
"from api) class KeyboardDetailsView(Gtk.Dialog): # TODO Display all the information",
"lbl_pkg_name label = Gtk.Label() if secure_lookup(info, 'name', 'description'): label.set_text(secure_lookup(info, 'name',",
"\".json\") # Package info lbl_pkg_name = Gtk.Label() lbl_pkg_name.set_text(_(\"Package name: \"))",
"Dialog when invalid metadata self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) grid = Gtk.Grid() self.get_content_area().pack_start(grid,",
"name: \")) lbl_kbd_name.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_name, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"is available # especially what is displayed for Keyman on",
"Keyboard: \")) # label7.set_halign(Gtk.Align.END) # grid.attach_next_to(label7, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"%s %s', type(e), jsonfile, e.args) grid = Gtk.Grid() # grid.set_column_homogeneous(True)",
"lbl_pkg_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(kbdata, 'description'): lbl_pkg_desc = Gtk.Label()",
"= Gtk.Label() if secure_lookup(info, 'copyright', 'description'): label.set_text(secure_lookup(info, 'copyright', 'description')) label.set_halign(Gtk.Align.START)",
"'description'): label.set_text(secure_lookup(info, 'copyright', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_cpy, Gtk.PositionType.RIGHT, 1,",
"2, 1) prevlabel = divider_pkg # Keyboard info for each",
"info for each keyboard if keyboards: for kbd in keyboards:",
"= parsemetadata(kmp_json) if info is None: # Dialog when invalid",
"# # grid.attach_next_to(label, label7, Gtk.PositionType.RIGHT, 1, 1) # label8 =",
"kmp['packageID'] + '_qrcode.png') url = KeymanComUrl + \"/go/keyboard/\" + kmp['packageID']",
"1) # label8 = Gtk.Label() # label8.set_text(_(\"Documentation: \")) # label8.set_halign(Gtk.Align.END)",
"prevlabel = lbl_share_kbd self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) self.get_content_area().pack_start(grid, True, True, 12) self.resize(800,",
"lbl_pkg_desc.set_text(_(\"Package description: \")) lbl_pkg_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"grid.attach_next_to(lbl_kbd_lic, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_lic label =",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_vrs label = Gtk.Label() if",
"Gtk.Grid() self.get_content_area().pack_start(grid, True, True, 12) lbl_invalid_metadata = Gtk.Label() lbl_invalid_metadata.set_text(_(\"ERROR: Keyboard",
"label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_file, Gtk.PositionType.RIGHT, 1, 1) if kbdata and secure_lookup(kbdata,",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_name, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_id = Gtk.Label()",
"= Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) # label7 =",
"label7.set_text(_(\"On Screen Keyboard: \")) # label7.set_halign(Gtk.Align.END) # grid.attach_next_to(label7, prevlabel, Gtk.PositionType.BOTTOM,",
"1) lbl_kbd_desc = Gtk.Label() lbl_kbd_desc.set_text(_(\"Keyboard description: \")) lbl_kbd_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_desc, prevlabel,",
"documentation availability, package copyright # also: supported languages, fonts #",
"label7, Gtk.PositionType.RIGHT, 1, 1) # label8 = Gtk.Label() # label8.set_text(_(\"Documentation:",
"prevlabel = lbl_pkg_id label = Gtk.Label() if secure_lookup(kmp, 'packageID'): label.set_text(kmp['packageID'])",
"Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_id = Gtk.Label() lbl_kbd_id.set_text(_(\"Keyboard id: \")) lbl_kbd_id.set_halign(Gtk.Align.END)",
"Keyboard metadata is damaged.\\nPlease \\\"Uninstall\\\" and then \\\"Install\\\" the keyboard.\"))",
"grid.attach_next_to(lbl_pkg_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_desc label =",
"lbl_pkg_id label = Gtk.Label() if secure_lookup(kmp, 'packageID'): label.set_text(kmp['packageID']) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"Gtk.Label() label.set_text(path.join(packageDir, kbd['id'] + \".kmx\")) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_file, Gtk.PositionType.RIGHT,",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_name, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_id = Gtk.Label()",
"= Gtk.Label() label.set_text(path.join(packageDir, kbd['id'] + \".kmx\")) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_file,",
"prevlabel = lbl_kbd_desc label = Gtk.Label() if secure_lookup(kbdata, 'description'): label.set_text(kbdata['description'])",
"is data in kmp.inf/kmp.json # there is possibly data in",
"Gtk.Label() lbl_pkg_cpy.set_text(_(\"Package copyright: \")) lbl_pkg_cpy.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_cpy, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"keyman_config.accelerators import init_accel from keyman_config.kmpmetadata import parsemetadata gi.require_version('Gtk', '3.0') #",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_auth label = Gtk.Label()",
"Gtk.Label() lbl_pkg_desc.set_text(_(\"Package description: \")) lbl_pkg_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"label.set_text(_(\"Installed\")) # # else: # # label.set_text(_(\"Not installed\")) # #",
"secure_lookup(kbdata, 'version'): label.set_text(kbdata['version']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_vrs, Gtk.PositionType.RIGHT, 1, 1)",
"# show the icon somewhere lbl_kbd_file = Gtk.Label() lbl_kbd_file.set_text(_(\"Keyboard filename:",
"Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label8 # #TODO need",
"window import logging import json from os import path import",
"prevlabel = lbl_pkg_desc label = Gtk.Label() label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80)",
"Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = divider_pkg #",
"from gi.repository import Gtk from keyman_config import KeymanComUrl, _, secure_lookup",
"1, 1) if secure_lookup(info, \"author\"): lbl_pkg_auth = Gtk.Label() lbl_pkg_auth.set_text(_(\"Package author:",
"logging import json from os import path import qrcode import",
"keyboard is distributed under the MIT license (MIT) as described",
"1, 1) # prevlabel = label7 # # label =",
"\".kmx\")) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_file, Gtk.PositionType.RIGHT, 1, 1) if kbdata",
"# grid.attach_next_to(label8, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label8",
"# # grid.attach_next_to(label, label8, Gtk.PositionType.RIGHT, 1, 1) # label9 =",
"secure_lookup from keyman_config.accelerators import init_accel from keyman_config.kmpmetadata import parsemetadata gi.require_version('Gtk',",
"tempfile import gi from gi.repository import Gtk from keyman_config import",
"1) lbl_pkg_id = Gtk.Label() lbl_pkg_id.set_text(_(\"Package id: \")) lbl_pkg_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_id, prevlabel,",
"reading %s %s', type(e), jsonfile, e.args) grid = Gtk.Grid() #",
"# label = Gtk.Label() # label.set_line_wrap(True) # label.set_text( # \"This",
"type(e), jsonfile, e.args) # start with padding lbl_pad = Gtk.Label()",
"if secure_lookup(kbdata, 'version'): label.set_text(kbdata['version']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_vrs, Gtk.PositionType.RIGHT, 1,",
"import qrcode import tempfile import gi from gi.repository import Gtk",
"'version'): label.set_text(kbdata['version']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_vrs, Gtk.PositionType.RIGHT, 1, 1) if",
"description: \")) lbl_kbd_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"things: filename (of kmx), , # OSK availability, documentation availability,",
"secure_lookup(info, 'author', 'description'): label.set_text(secure_lookup(info, 'author', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_auth,",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_desc label = Gtk.Label() if",
"Add an entire row of padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\")",
"lbl_pad # If it doesn't exist, generate QR code to",
"options, keyboards, files = parsemetadata(kmp_json) if info is None: #",
"\\\"Install\\\" the keyboard.\")) lbl_invalid_metadata.set_halign(Gtk.Align.END) grid.add(lbl_invalid_metadata) self.resize(700, 200) self.show_all() return kbdata",
"\"copyright\"): lbl_pkg_cpy = Gtk.Label() lbl_pkg_cpy.set_text(_(\"Package copyright: \")) lbl_pkg_cpy.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_cpy, prevlabel,",
"lbl_kbd_id = Gtk.Label() lbl_kbd_id.set_text(_(\"Keyboard id: \")) lbl_kbd_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_id, prevlabel, Gtk.PositionType.BOTTOM,",
"centered image = Gtk.Image() image.set_from_file(path_qr) grid.attach_next_to(image, prevlabel, Gtk.PositionType.BOTTOM, 2, 1)",
"label = Gtk.Label() # label.set_line_wrap(True) # label.set_text( # \"This keyboard",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_auth, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"copyright\"):",
"also: supported languages, fonts # from kmx?: keyboard version, encoding,",
"label.set_text(secure_lookup(info, 'copyright', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_cpy, Gtk.PositionType.RIGHT, 1, 1)",
"Gtk.Label() lbl_pkg_name.set_text(_(\"Package name: \")) lbl_pkg_name.set_halign(Gtk.Align.END) grid.add(lbl_pkg_name) prevlabel = lbl_pkg_name label",
"1, 1) if secure_lookup(info, \"author\"): lbl_kbd_auth = Gtk.Label() lbl_kbd_auth.set_text(_(\"Keyboard author:",
"device or <a href='{uri}'>share online</a>\").format(uri=url)) lbl_share_kbd.set_halign(Gtk.Align.CENTER) lbl_share_kbd.set_line_wrap(True) grid.attach_next_to(lbl_share_kbd, image, Gtk.PositionType.BOTTOM,",
"label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_pkg_desc, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"):",
"divider lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2,",
"grid.attach_next_to(label, label7, Gtk.PositionType.RIGHT, 1, 1) # label8 = Gtk.Label() #",
"if secure_lookup(kbdata, 'description'): lbl_pkg_desc = Gtk.Label() lbl_pkg_desc.set_text(_(\"Package description: \")) lbl_pkg_desc.set_halign(Gtk.Align.END)",
"# Padding and full width horizontal divider lbl_pad = Gtk.Label()",
"this keyboard\\non another device or <a href='{uri}'>share online</a>\").format(uri=url)) lbl_share_kbd.set_halign(Gtk.Align.CENTER) lbl_share_kbd.set_line_wrap(True)",
"gi.repository import Gtk from keyman_config import KeymanComUrl, _, secure_lookup from",
"lbl_pkg_vrs = Gtk.Label() lbl_pkg_vrs.set_text(_(\"Package version: \")) lbl_pkg_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_vrs, prevlabel, Gtk.PositionType.BOTTOM,",
"name, version, packageID, area if \"keyboard\" in kmp[\"name\"].lower(): wintitle =",
"# grid.set_column_homogeneous(True) # kbdatapath = path.join(\"/usr/local/share/keyman\", kmp[\"id\"], kmp[\"id\"] + \".json\")",
"1) if secure_lookup(kbdata, 'description'): lbl_pkg_desc = Gtk.Label() lbl_pkg_desc.set_text(_(\"Package description: \"))",
"full width horizontal divider lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad,",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_lic, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_desc = Gtk.Label()",
"1, 1) # label8 = Gtk.Label() # label8.set_text(_(\"Documentation: \")) #",
"it will be centered image = Gtk.Image() image.set_from_file(path_qr) grid.attach_next_to(image, prevlabel,",
"= path.join(packageDir, \"kmp.json\") info, system, options, keyboards, files = parsemetadata(kmp_json)",
"version: \")) lbl_kbd_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"logging.warning('Exception %s reading %s %s', type(e), jsonfile, e.args) # start",
"init_accel(self) self.set_border_width(6) packageDir = path.join(kmp['areapath'], kmp['packageID']) kmp_json = path.join(packageDir, \"kmp.json\")",
"metadata is damaged.\\nPlease \\\"Uninstall\\\" and then \\\"Install\\\" the keyboard.\")) lbl_invalid_metadata.set_halign(Gtk.Align.END)",
"kmp): # kmp has name, version, packageID, area if \"keyboard\"",
"secure_lookup(kbdata, 'authorName'): label.set_text(kbdata['authorName']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_auth, Gtk.PositionType.RIGHT, 1, 1)",
"in to show this # # label = Gtk.Label() #",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_auth label = Gtk.Label() if",
"keyboard if keyboards: for kbd in keyboards: kbdata = None",
"lbl_kbd_file = Gtk.Label() lbl_kbd_file.set_text(_(\"Keyboard filename: \")) lbl_kbd_file.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_file, prevlabel, Gtk.PositionType.BOTTOM,",
"1) prevlabel = lbl_pkg_vrs label = Gtk.Label() if secure_lookup(info, 'version',",
"up file once have what we want def __init__(self, parent,",
"copyright # also: supported languages, fonts # from kmx?: keyboard",
"1) prevlabel = divider_pkg # Keyboard info for each keyboard",
"Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label9 # label =",
"padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2,",
"!= secure_lookup(kmp, 'packageID'): lbl_kbd_name = Gtk.Label() lbl_kbd_name.set_text(_(\"Keyboard name: \")) lbl_kbd_name.set_halign(Gtk.Align.END)",
"#!/usr/bin/python3 # Keyboard details window import logging import json from",
"_, secure_lookup from keyman_config.accelerators import init_accel from keyman_config.kmpmetadata import parsemetadata",
"area if \"keyboard\" in kmp[\"name\"].lower(): wintitle = kmp[\"name\"] else: wintitle",
"in kmp[\"name\"].lower(): wintitle = kmp[\"name\"] else: wintitle = _(\"{name} keyboard\").format(name=kmp[\"name\"])",
"lbl_pkg_auth, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"copyright\"): lbl_pkg_cpy = Gtk.Label()",
"%s %s', type(e), jsonfile, e.args) # start with padding lbl_pad",
"kmx # label9.set_text(_(\"Message: \")) # label9.set_halign(Gtk.Align.END) # grid.attach_next_to(label9, prevlabel, Gtk.PositionType.BOTTOM,",
"fonts # from kmx?: keyboard version, encoding, layout type #",
"package path_qr = path.join(tempfile.gettempdir(), kmp['packageID'] + '_qrcode.png') url = KeymanComUrl",
"from kmx?: keyboard version, encoding, layout type # there is",
"id: \")) lbl_pkg_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"= Gtk.Label() if secure_lookup(kbdata, 'description'): label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label,",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_auth, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_lic = Gtk.Label()",
"each keyboard if keyboards: for kbd in keyboards: kbdata =",
"as e: logging.warning('Exception %s reading %s %s', type(e), jsonfile, e.args)",
"= lbl_pkg_name label = Gtk.Label() if secure_lookup(info, 'name', 'description'): label.set_text(secure_lookup(info,",
"self.resize(700, 200) self.show_all() return kbdata = None jsonfile = path.join(packageDir,",
"(of kmx), , # OSK availability, documentation availability, package copyright",
"Package info lbl_pkg_name = Gtk.Label() lbl_pkg_name.set_text(_(\"Package name: \")) lbl_pkg_name.set_halign(Gtk.Align.END) grid.add(lbl_pkg_name)",
"package copyright # also: supported languages, fonts # from kmx?:",
"'packageID'): label.set_text(kmp['packageID']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_id, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_vrs",
"prevlabel = lbl_kbd_vrs label = Gtk.Label() if secure_lookup(kbdata, 'version'): label.set_text(kbdata['version'])",
"lbl_kbd_auth = Gtk.Label() lbl_kbd_auth.set_text(_(\"Keyboard author: \")) lbl_kbd_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_auth, prevlabel, Gtk.PositionType.BOTTOM,",
"qr.add_data(url) qr.make(fit=True) img = qr.make_image() img.save(path_qr) # Display QR Code,",
"prevlabel = lbl_kbd_name label = Gtk.Label() if secure_lookup(kbdata, 'name'): label.set_text(kbdata['name'])",
"1) prevlabel = lbl_pkg_cpy label = Gtk.Label() if secure_lookup(info, 'copyright',",
"1) lbl_kbd_lic = Gtk.Label() lbl_kbd_lic.set_text(_(\"Keyboard license: \")) lbl_kbd_lic.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_lic, prevlabel,",
"# label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # # grid.attach_next_to(label, label8, Gtk.PositionType.RIGHT,",
"KeymanComUrl, _, secure_lookup from keyman_config.accelerators import init_accel from keyman_config.kmpmetadata import",
"if secure_lookup(kbdata, 'name'): label.set_text(kbdata['name']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_name, Gtk.PositionType.RIGHT, 1,",
"we want def __init__(self, parent, kmp): # kmp has name,",
"as described somewhere\") # #label.set_text(kmp[\"description\"]) # label.set_halign(Gtk.Align.START) # label.set_selectable(True) #",
"1, 1) # Add an entire row of padding lbl_pad",
"wintitle, parent) init_accel(self) self.set_border_width(6) packageDir = path.join(kmp['areapath'], kmp['packageID']) kmp_json =",
"described somewhere\") # #label.set_text(kmp[\"description\"]) # label.set_halign(Gtk.Align.START) # label.set_selectable(True) # grid.attach_next_to(label,",
"= path.join(kmp['areapath'], kmp['packageID']) kmp_json = path.join(packageDir, \"kmp.json\") info, system, options,",
"QR Code, spanning 2 columns so it will be centered",
"other things: filename (of kmx), , # OSK availability, documentation",
"= label9 # label = Gtk.Label() # label.set_line_wrap(True) # label.set_text(",
"an entire row of padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END)",
"KeymanComUrl + \"/go/keyboard/\" + kmp['packageID'] + \"/share\" if not path.isfile(path_qr):",
"= json.load(read_file) except Exception as e: logging.warning('Exception %s reading %s",
"Code, spanning 2 columns so it will be centered image",
"# there is possibly data in kbid.json (downloaded from api)",
"wintitle = kmp[\"name\"] else: wintitle = _(\"{name} keyboard\").format(name=kmp[\"name\"]) Gtk.Dialog.__init__(self, wintitle,",
"= Gtk.Label() if secure_lookup(info, 'version', 'description'): label.set_text(secure_lookup(info, 'version', 'description')) label.set_halign(Gtk.Align.START)",
"# label8.set_halign(Gtk.Align.END) # grid.attach_next_to(label8, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel",
"'_qrcode.png') url = KeymanComUrl + \"/go/keyboard/\" + kmp['packageID'] + \"/share\"",
"Gtk.Label() lbl_pkg_id.set_text(_(\"Package id: \")) lbl_pkg_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"e: logging.warning('Exception %s reading %s %s', type(e), jsonfile, e.args) #",
"= Gtk.Label() lbl_kbd_desc.set_text(_(\"Keyboard description: \")) lbl_kbd_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_desc, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"label.set_halign(Gtk.Align.START) # label.set_selectable(True) # grid.attach_next_to(label, label9, Gtk.PositionType.RIGHT, 1, 1) #",
"from keyman_config.kmpmetadata import parsemetadata gi.require_version('Gtk', '3.0') # basics: keyboard name,",
"keyboard version, encoding, layout type # there is data in",
"= divider_pkg # Keyboard info for each keyboard if keyboards:",
"prevlabel = lbl_pad # show the icon somewhere lbl_kbd_file =",
"# # label = Gtk.Label() # # welcome_file = path.join(\"/usr/local/share/doc/keyman\",",
"kmp['packageID']) kmp_json = path.join(packageDir, \"kmp.json\") info, system, options, keyboards, files",
"kbd['id'] + \".kmx\")) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_file, Gtk.PositionType.RIGHT, 1, 1)",
"'version', 'description')) # # label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # #",
"1, 1) # prevlabel = label9 # label = Gtk.Label()",
"license (MIT) as described somewhere\") # #label.set_text(kmp[\"description\"]) # label.set_halign(Gtk.Align.START) #",
"to load this keyboard\\non another device or <a href='{uri}'>share online</a>\").format(uri=url))",
"keyboard.\")) lbl_invalid_metadata.set_halign(Gtk.Align.END) grid.add(lbl_invalid_metadata) self.resize(700, 200) self.show_all() return kbdata = None",
"Gtk.Label() if secure_lookup(kbdata, 'license'): label.set_text(kbdata['license']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_lic, Gtk.PositionType.RIGHT,",
"grid = Gtk.Grid() # grid.set_column_homogeneous(True) # kbdatapath = path.join(\"/usr/local/share/keyman\", kmp[\"id\"],",
"1) prevlabel = lbl_pkg_auth label = Gtk.Label() if secure_lookup(info, 'author',",
"= Gtk.Label() if secure_lookup(kbdata, 'authorName'): label.set_text(kbdata['authorName']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_auth,",
"\")) lbl_kbd_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_vrs",
"area keyboard is installed in to show this # #",
"1) prevlabel = lbl_kbd_desc label = Gtk.Label() if secure_lookup(kbdata, 'description'):",
"to share keyboard package path_qr = path.join(tempfile.gettempdir(), kmp['packageID'] + '_qrcode.png')",
"try: with open(jsonfile, \"r\") as read_file: kbdata = json.load(read_file) except",
"kbdatapath = path.join(\"/usr/local/share/keyman\", kmp[\"id\"], kmp[\"id\"] + \".json\") # Package info",
"1, 1) prevlabel = lbl_pkg_cpy label = Gtk.Label() if secure_lookup(info,",
"prevlabel, Gtk.PositionType.BOTTOM, 2, 1) # label7 = Gtk.Label() # label7.set_text(_(\"On",
"'author', 'description'): label.set_text(secure_lookup(info, 'author', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_auth, Gtk.PositionType.RIGHT,",
"1) prevlabel = lbl_pad divider_pkg = Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM,",
"= path.join(\"/usr/local/share/keyman\", kmp[\"id\"], kmp[\"id\"] + \".json\") # Package info lbl_pkg_name",
"\")) lbl_pkg_name.set_halign(Gtk.Align.END) grid.add(lbl_pkg_name) prevlabel = lbl_pkg_name label = Gtk.Label() if",
"load this keyboard\\non another device or <a href='{uri}'>share online</a>\").format(uri=url)) lbl_share_kbd.set_halign(Gtk.Align.CENTER)",
"label.set_line_wrap(True) # label.set_text( # \"This keyboard is distributed under the",
"lbl_pad divider_pkg = Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) #",
"# from kmx?: keyboard version, encoding, layout type # there",
"%s reading %s %s', type(e), jsonfile, e.args) grid = Gtk.Grid()",
"if secure_lookup(kmp, 'packageID'): label.set_text(kmp['packageID']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_id, Gtk.PositionType.RIGHT, 1,",
"label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # # grid.attach_next_to(label, label8, Gtk.PositionType.RIGHT, 1,",
"spanning 2 columns so it will be centered image =",
"lbl_kbd_file label = Gtk.Label() label.set_text(path.join(packageDir, kbd['id'] + \".kmx\")) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"label = Gtk.Label() # # welcome_file = path.join(\"/usr/local/share/doc/keyman\", kmp[\"id\"], \"welcome.htm\")",
"# prevlabel = label8 # #TODO need to know which",
"+ \".kmx\")) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_file, Gtk.PositionType.RIGHT, 1, 1) if",
"'name', 'description'): label.set_text(secure_lookup(info, 'name', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_name, Gtk.PositionType.RIGHT,",
"label.set_text(secure_lookup(info, 'name', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_name, Gtk.PositionType.RIGHT, 1, 1)",
"version: \")) lbl_pkg_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"for each keyboard if keyboards: for kbd in keyboards: kbdata",
"prevlabel = lbl_kbd_id label = Gtk.Label() if secure_lookup(kbdata, 'id'): label.set_text(kbdata['id'])",
"author: \")) lbl_kbd_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"url = KeymanComUrl + \"/go/keyboard/\" + kmp['packageID'] + \"/share\" if",
"is installed in to show this # # label =",
"img = qr.make_image() img.save(path_qr) # Display QR Code, spanning 2",
"(downloaded from api) class KeyboardDetailsView(Gtk.Dialog): # TODO Display all the",
"= lbl_pkg_auth label = Gtk.Label() if secure_lookup(info, 'author', 'description'): label.set_text(secure_lookup(info,",
"jsonfile = path.join(packageDir, kbd['id'] + \".json\") if path.isfile(jsonfile): try: with",
"icon somewhere lbl_kbd_file = Gtk.Label() lbl_kbd_file.set_text(_(\"Keyboard filename: \")) lbl_kbd_file.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_file,",
"# Package info lbl_pkg_name = Gtk.Label() lbl_pkg_name.set_text(_(\"Package name: \")) lbl_pkg_name.set_halign(Gtk.Align.END)",
"this # # label = Gtk.Label() # # welcome_file =",
", # OSK availability, documentation availability, package copyright # also:",
"doesn't exist, generate QR code to share keyboard package path_qr",
"kbdata and secure_lookup(kbdata, 'id') != secure_lookup(kmp, 'packageID'): lbl_kbd_name = Gtk.Label()",
"# # label.set_text(_(\"Installed\")) # # else: # # label.set_text(_(\"Not installed\"))",
"want def __init__(self, parent, kmp): # kmp has name, version,",
"# grid.attach_next_to(label, label7, Gtk.PositionType.RIGHT, 1, 1) # label8 = Gtk.Label()",
"row of padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel,",
"details window import logging import json from os import path",
"# label.set_selectable(True) # # grid.attach_next_to(label, label7, Gtk.PositionType.RIGHT, 1, 1) #",
"path.join(\"/usr/local/share/doc/keyman\", kmp[\"id\"], \"welcome.htm\") # # if path.isfile(welcome_file): # # label.set_text(_(\"Installed\"))",
"\"keyboard\" in kmp[\"name\"].lower(): wintitle = kmp[\"name\"] else: wintitle = _(\"{name}",
"_(\"{name} keyboard\").format(name=kmp[\"name\"]) Gtk.Dialog.__init__(self, wintitle, parent) init_accel(self) self.set_border_width(6) packageDir = path.join(kmp['areapath'],",
"# welcome_file = path.join(\"/usr/local/share/doc/keyman\", kmp[\"id\"], \"welcome.htm\") # # if path.isfile(welcome_file):",
"\"author\"): lbl_kbd_auth = Gtk.Label() lbl_kbd_auth.set_text(_(\"Keyboard author: \")) lbl_kbd_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_auth, prevlabel,",
"if \"keyboard\" in kmp[\"name\"].lower(): wintitle = kmp[\"name\"] else: wintitle =",
"1, 1) prevlabel = lbl_kbd_vrs label = Gtk.Label() if secure_lookup(kbdata,",
"if secure_lookup(info, \"copyright\"): lbl_pkg_cpy = Gtk.Label() lbl_pkg_cpy.set_text(_(\"Package copyright: \")) lbl_pkg_cpy.set_halign(Gtk.Align.END)",
"else: # # label.set_text(_(\"Not installed\")) # # label.set_halign(Gtk.Align.START) # #",
"for kbd in keyboards: kbdata = None jsonfile = path.join(packageDir,",
"qr.make_image() img.save(path_qr) # Display QR Code, spanning 2 columns so",
"= Gtk.Label() lbl_pkg_id.set_text(_(\"Package id: \")) lbl_pkg_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_id, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"lbl_pkg_desc, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"): lbl_pkg_auth = Gtk.Label()",
"%s reading %s %s', type(e), jsonfile, e.args) # start with",
"lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad divider_pkg",
"kbid.json (downloaded from api) class KeyboardDetailsView(Gtk.Dialog): # TODO Display all",
"secure_lookup(kbdata, 'id'): label.set_text(kbdata['id']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_id, Gtk.PositionType.RIGHT, 1, 1)",
"grid.attach_next_to(label, label9, Gtk.PositionType.RIGHT, 1, 1) # Add an entire row",
"data in kmp.inf/kmp.json # there is possibly data in kbid.json",
"is possibly data in kbid.json (downloaded from api) class KeyboardDetailsView(Gtk.Dialog):",
"= None jsonfile = path.join(packageDir, kbd['id'] + \".json\") if path.isfile(jsonfile):",
"# label = Gtk.Label() # # welcome_file = path.join(\"/usr/local/share/doc/keyman\", kmp[\"id\"],",
"type # there is data in kmp.inf/kmp.json # there is",
"# if path.isfile(welcome_file): # # label.set_text(_(\"Installed\")) # # else: #",
"1) # prevlabel = label7 # # label = Gtk.Label()",
"label7.set_halign(Gtk.Align.END) # grid.attach_next_to(label7, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel =",
"if secure_lookup(kbdata, 'id'): label.set_text(kbdata['id']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_id, Gtk.PositionType.RIGHT, 1,",
"if secure_lookup(info, \"author\"): lbl_kbd_auth = Gtk.Label() lbl_kbd_auth.set_text(_(\"Keyboard author: \")) lbl_kbd_auth.set_halign(Gtk.Align.END)",
"lbl_kbd_id.set_text(_(\"Keyboard id: \")) lbl_kbd_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"Gtk.Label() lbl_kbd_vrs.set_text(_(\"Keyboard version: \")) lbl_kbd_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"1, 1) lbl_kbd_desc = Gtk.Label() lbl_kbd_desc.set_text(_(\"Keyboard description: \")) lbl_kbd_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_desc,",
"= Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel",
"to show this # # label = Gtk.Label() # #",
"# label9.set_text(_(\"Message: \")) # label9.set_halign(Gtk.Align.END) # grid.attach_next_to(label9, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"label9 = Gtk.Label() # # stored in kmx # label9.set_text(_(\"Message:",
"kmp.inf/kmp.json # there is possibly data in kbid.json (downloaded from",
"once have what we want def __init__(self, parent, kmp): #",
"+ \".json\") if path.isfile(jsonfile): try: with open(jsonfile, \"r\") as read_file:",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_id, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_vrs = Gtk.Label()",
"= Gtk.Image() image.set_from_file(path_qr) grid.attach_next_to(image, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) lbl_share_kbd =",
"secure_lookup(kbdata, 'name'): label.set_text(kbdata['name']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_name, Gtk.PositionType.RIGHT, 1, 1)",
"= Gtk.Label() lbl_kbd_lic.set_text(_(\"Keyboard license: \")) lbl_kbd_lic.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_lic, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"grid.attach_next_to(lbl_kbd_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_auth label =",
"2, 1) prevlabel = lbl_pad divider_pkg = Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel,",
"path_qr = path.join(tempfile.gettempdir(), kmp['packageID'] + '_qrcode.png') url = KeymanComUrl +",
"if secure_lookup(info, 'copyright', 'description'): label.set_text(secure_lookup(info, 'copyright', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"e.args) # start with padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END)",
"= Gtk.Label() lbl_pkg_name.set_text(_(\"Package name: \")) lbl_pkg_name.set_halign(Gtk.Align.END) grid.add(lbl_pkg_name) prevlabel = lbl_pkg_name",
"if secure_lookup(kbdata, 'authorName'): label.set_text(kbdata['authorName']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_auth, Gtk.PositionType.RIGHT, 1,",
"label7 = Gtk.Label() # label7.set_text(_(\"On Screen Keyboard: \")) # label7.set_halign(Gtk.Align.END)",
"\")) lbl_pkg_cpy.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_cpy, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_cpy",
"#label.set_text(kmp[\"description\"]) # label.set_halign(Gtk.Align.START) # label.set_selectable(True) # grid.attach_next_to(label, label9, Gtk.PositionType.RIGHT, 1,",
"# If it doesn't exist, generate QR code to share",
"Gtk.PositionType.BOTTOM, 2, 1) prevlabel = divider_pkg # Keyboard info for",
"there is possibly data in kbid.json (downloaded from api) class",
"under the MIT license (MIT) as described somewhere\") # #label.set_text(kmp[\"description\"])",
"'description'): label.set_text(secure_lookup(info, 'author', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_auth, Gtk.PositionType.RIGHT, 1,",
"image, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_share_kbd self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) self.get_content_area().pack_start(grid,",
"parsemetadata(kmp_json) if info is None: # Dialog when invalid metadata",
"label.set_line_wrap(80) grid.attach_next_to(label, lbl_kbd_desc, Gtk.PositionType.RIGHT, 1, 1) # Padding and full",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_kbd_desc, Gtk.PositionType.RIGHT, 1, 1) # Padding",
"label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_id, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_vrs = Gtk.Label() lbl_kbd_vrs.set_text(_(\"Keyboard",
"grid.attach_next_to(label, lbl_kbd_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"): lbl_kbd_auth =",
"label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_name, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_id = Gtk.Label() lbl_pkg_id.set_text(_(\"Package",
"lbl_kbd_auth, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_lic = Gtk.Label() lbl_kbd_lic.set_text(_(\"Keyboard license: \"))",
"= Gtk.Label() lbl_kbd_auth.set_text(_(\"Keyboard author: \")) lbl_kbd_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_auth, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"secure_lookup(info, 'version', 'description'): label.set_text(secure_lookup(info, 'version', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_vrs,",
"'id'): label.set_text(kbdata['id']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_id, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_vrs",
"displayed for Keyman on Windows # TODO clean up file",
"# kmp has name, version, packageID, area if \"keyboard\" in",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_auth label = Gtk.Label()",
"clean up file once have what we want def __init__(self,",
"secure_lookup(info, \"copyright\"): lbl_pkg_cpy = Gtk.Label() lbl_pkg_cpy.set_text(_(\"Package copyright: \")) lbl_pkg_cpy.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_cpy,",
"reading %s %s', type(e), jsonfile, e.args) # start with padding",
"if secure_lookup(kbdata, 'description'): label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_kbd_desc, Gtk.PositionType.RIGHT,",
"Gtk.PositionType.RIGHT, 1, 1) # label8 = Gtk.Label() # label8.set_text(_(\"Documentation: \"))",
"self.get_content_area().pack_start(grid, True, True, 12) lbl_invalid_metadata = Gtk.Label() lbl_invalid_metadata.set_text(_(\"ERROR: Keyboard metadata",
"Padding and full width horizontal divider lbl_pad = Gtk.Label() lbl_pad.set_text(\"\")",
"is displayed for Keyman on Windows # TODO clean up",
"1, 1) prevlabel = lbl_kbd_name label = Gtk.Label() if secure_lookup(kbdata,",
"not path.isfile(path_qr): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=4, border=4) qr.add_data(url)",
"files = parsemetadata(kmp_json) if info is None: # Dialog when",
"lbl_pkg_desc label = Gtk.Label() label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_pkg_desc,",
"Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_desc = Gtk.Label() lbl_kbd_desc.set_text(_(\"Keyboard description: \")) lbl_kbd_desc.set_halign(Gtk.Align.END)",
"# # label.set_text(secure_lookup(info, 'version', 'description')) # # label.set_halign(Gtk.Align.START) # #",
"# stored in kmx # label9.set_text(_(\"Message: \")) # label9.set_halign(Gtk.Align.END) #",
"class KeyboardDetailsView(Gtk.Dialog): # TODO Display all the information that is",
"if kbdata and secure_lookup(kbdata, 'id') != secure_lookup(kmp, 'packageID'): lbl_kbd_name =",
"# # label.set_text(_(\"Not installed\")) # # label.set_halign(Gtk.Align.START) # # label.set_selectable(True)",
"\")) lbl_pkg_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_id",
"grid.attach_next_to(label, lbl_kbd_lic, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_desc = Gtk.Label() lbl_kbd_desc.set_text(_(\"Keyboard description:",
"= lbl_kbd_id label = Gtk.Label() if secure_lookup(kbdata, 'id'): label.set_text(kbdata['id']) label.set_halign(Gtk.Align.START)",
"\"r\") as read_file: kbdata = json.load(read_file) except Exception as e:",
"\")) lbl_pkg_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_desc",
"another device or <a href='{uri}'>share online</a>\").format(uri=url)) lbl_share_kbd.set_halign(Gtk.Align.CENTER) lbl_share_kbd.set_line_wrap(True) grid.attach_next_to(lbl_share_kbd, image,",
"show this # # label = Gtk.Label() # # welcome_file",
"for Keyman on Windows # TODO clean up file once",
"else: wintitle = _(\"{name} keyboard\").format(name=kmp[\"name\"]) Gtk.Dialog.__init__(self, wintitle, parent) init_accel(self) self.set_border_width(6)",
"so it will be centered image = Gtk.Image() image.set_from_file(path_qr) grid.attach_next_to(image,",
"label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_name, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_id = Gtk.Label() lbl_kbd_id.set_text(_(\"Keyboard",
"Gtk.Label() # label8.set_text(_(\"Documentation: \")) # label8.set_halign(Gtk.Align.END) # grid.attach_next_to(label8, prevlabel, Gtk.PositionType.BOTTOM,",
"exist, generate QR code to share keyboard package path_qr =",
"= Gtk.Grid() self.get_content_area().pack_start(grid, True, True, 12) lbl_invalid_metadata = Gtk.Label() lbl_invalid_metadata.set_text(_(\"ERROR:",
"grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad # If",
"1, 1) # prevlabel = label8 # #TODO need to",
"and full width horizontal divider lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END)",
"2, 1) # label7 = Gtk.Label() # label7.set_text(_(\"On Screen Keyboard:",
"1) lbl_pkg_vrs = Gtk.Label() lbl_pkg_vrs.set_text(_(\"Package version: \")) lbl_pkg_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_vrs, prevlabel,",
"1) prevlabel = lbl_pad # If it doesn't exist, generate",
"= _(\"{name} keyboard\").format(name=kmp[\"name\"]) Gtk.Dialog.__init__(self, wintitle, parent) init_accel(self) self.set_border_width(6) packageDir =",
"12) lbl_invalid_metadata = Gtk.Label() lbl_invalid_metadata.set_text(_(\"ERROR: Keyboard metadata is damaged.\\nPlease \\\"Uninstall\\\"",
"logging.warning('Exception %s reading %s %s', type(e), jsonfile, e.args) grid =",
"gi from gi.repository import Gtk from keyman_config import KeymanComUrl, _,",
"1, 1) if secure_lookup(kbdata, 'description'): lbl_pkg_desc = Gtk.Label() lbl_pkg_desc.set_text(_(\"Package description:",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_name label = Gtk.Label() if",
"= path.join(tempfile.gettempdir(), kmp['packageID'] + '_qrcode.png') url = KeymanComUrl + \"/go/keyboard/\"",
"kbd['id'] + \".json\") if path.isfile(jsonfile): try: with open(jsonfile, \"r\") as",
"Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) # label7 = Gtk.Label()",
"# label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # # grid.attach_next_to(label, label7, Gtk.PositionType.RIGHT,",
"parsemetadata gi.require_version('Gtk', '3.0') # basics: keyboard name, package version, description",
"label = Gtk.Label() # # label.set_text(secure_lookup(info, 'version', 'description')) # #",
"keyboards, files = parsemetadata(kmp_json) if info is None: # Dialog",
"lbl_pkg_cpy label = Gtk.Label() if secure_lookup(info, 'copyright', 'description'): label.set_text(secure_lookup(info, 'copyright',",
"lbl_pkg_id, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_vrs = Gtk.Label() lbl_pkg_vrs.set_text(_(\"Package version: \"))",
"# #TODO need to know which area keyboard is installed",
"path import qrcode import tempfile import gi from gi.repository import",
"\")) lbl_kbd_name.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_name, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_name",
"grid.add(lbl_pkg_name) prevlabel = lbl_pkg_name label = Gtk.Label() if secure_lookup(info, 'name',",
"lbl_kbd_desc = Gtk.Label() lbl_kbd_desc.set_text(_(\"Keyboard description: \")) lbl_kbd_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_desc, prevlabel, Gtk.PositionType.BOTTOM,",
"= lbl_pad # If it doesn't exist, generate QR code",
"lbl_pkg_name.set_text(_(\"Package name: \")) lbl_pkg_name.set_halign(Gtk.Align.END) grid.add(lbl_pkg_name) prevlabel = lbl_pkg_name label =",
"grid.add(lbl_invalid_metadata) self.resize(700, 200) self.show_all() return kbdata = None jsonfile =",
"width horizontal divider lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel,",
"system, options, keyboards, files = parsemetadata(kmp_json) if info is None:",
"# # if path.isfile(welcome_file): # # label.set_text(_(\"Installed\")) # # else:",
"lbl_pkg_name, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_id = Gtk.Label() lbl_pkg_id.set_text(_(\"Package id: \"))",
"prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad # show the",
"prevlabel = label8 # #TODO need to know which area",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_desc label = Gtk.Label() label.set_text(kbdata['description'])",
"as read_file: kbdata = json.load(read_file) except Exception as e: logging.warning('Exception",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"):",
"kmx?: keyboard version, encoding, layout type # there is data",
"1) lbl_kbd_id = Gtk.Label() lbl_kbd_id.set_text(_(\"Keyboard id: \")) lbl_kbd_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_id, prevlabel,",
"Gtk.Label() if secure_lookup(kbdata, 'id'): label.set_text(kbdata['id']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_id, Gtk.PositionType.RIGHT,",
"is damaged.\\nPlease \\\"Uninstall\\\" and then \\\"Install\\\" the keyboard.\")) lbl_invalid_metadata.set_halign(Gtk.Align.END) grid.add(lbl_invalid_metadata)",
"if secure_lookup(info, 'author', 'description'): label.set_text(secure_lookup(info, 'author', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"prevlabel = lbl_kbd_file label = Gtk.Label() label.set_text(path.join(packageDir, kbd['id'] + \".kmx\"))",
"secure_lookup(kbdata, 'description'): label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_kbd_desc, Gtk.PositionType.RIGHT, 1,",
"from keyman_config import KeymanComUrl, _, secure_lookup from keyman_config.accelerators import init_accel",
"path.isfile(jsonfile): try: with open(jsonfile, \"r\") as read_file: kbdata = json.load(read_file)",
"grid.attach_next_to(label, lbl_pkg_id, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_vrs = Gtk.Label() lbl_pkg_vrs.set_text(_(\"Package version:",
"Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_lic = Gtk.Label() lbl_kbd_lic.set_text(_(\"Keyboard license: \")) lbl_kbd_lic.set_halign(Gtk.Align.END)",
"Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_vrs = Gtk.Label() lbl_kbd_vrs.set_text(_(\"Keyboard version: \")) lbl_kbd_vrs.set_halign(Gtk.Align.END)",
"Gtk.ResponseType.CLOSE) grid = Gtk.Grid() self.get_content_area().pack_start(grid, True, True, 12) lbl_invalid_metadata =",
"file once have what we want def __init__(self, parent, kmp):",
"# there is data in kmp.inf/kmp.json # there is possibly",
"1, 1) if secure_lookup(info, \"copyright\"): lbl_pkg_cpy = Gtk.Label() lbl_pkg_cpy.set_text(_(\"Package copyright:",
"# label8.set_text(_(\"Documentation: \")) # label8.set_halign(Gtk.Align.END) # grid.attach_next_to(label8, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"lbl_pad divider_pkg = Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel",
"'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_cpy, Gtk.PositionType.RIGHT, 1, 1) # Padding",
"information that is available # especially what is displayed for",
"there is data in kmp.inf/kmp.json # there is possibly data",
"grid.attach_next_to(label, lbl_pkg_desc, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"): lbl_pkg_auth =",
"# grid.attach_next_to(label, label8, Gtk.PositionType.RIGHT, 1, 1) # label9 = Gtk.Label()",
"2 columns so it will be centered image = Gtk.Image()",
"= Gtk.Label() lbl_kbd_name.set_text(_(\"Keyboard name: \")) lbl_kbd_name.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_name, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_vrs label = Gtk.Label() if",
"label = Gtk.Label() if secure_lookup(kbdata, 'license'): label.set_text(kbdata['license']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"label.set_text(secure_lookup(info, 'author', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_auth, Gtk.PositionType.RIGHT, 1, 1)",
"path.isfile(welcome_file): # # label.set_text(_(\"Installed\")) # # else: # # label.set_text(_(\"Not",
"grid.attach_next_to(lbl_kbd_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_desc label =",
"divider_pkg # Keyboard info for each keyboard if keyboards: for",
"label.set_text(secure_lookup(info, 'version', 'description')) # # label.set_halign(Gtk.Align.START) # # label.set_selectable(True) #",
"# label7.set_halign(Gtk.Align.END) # grid.attach_next_to(label7, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel",
"lbl_kbd_id label = Gtk.Label() if secure_lookup(kbdata, 'id'): label.set_text(kbdata['id']) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"lbl_kbd_vrs label = Gtk.Label() if secure_lookup(kbdata, 'version'): label.set_text(kbdata['version']) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"lbl_kbd_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_id label",
"Gtk.Label() lbl_share_kbd.set_markup(_(\"Scan this code to load this keyboard\\non another device",
"def __init__(self, parent, kmp): # kmp has name, version, packageID,",
"# #label.set_text(kmp[\"description\"]) # label.set_halign(Gtk.Align.START) # label.set_selectable(True) # grid.attach_next_to(label, label9, Gtk.PositionType.RIGHT,",
"available # especially what is displayed for Keyman on Windows",
"prevlabel = lbl_pkg_name label = Gtk.Label() if secure_lookup(info, 'name', 'description'):",
"= lbl_pad # show the icon somewhere lbl_kbd_file = Gtk.Label()",
"1, 1) prevlabel = lbl_kbd_id label = Gtk.Label() if secure_lookup(kbdata,",
"to know which area keyboard is installed in to show",
"1) if secure_lookup(info, \"author\"): lbl_kbd_auth = Gtk.Label() lbl_kbd_auth.set_text(_(\"Keyboard author: \"))",
"\")) lbl_kbd_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_id",
"grid.attach_next_to(label, lbl_pkg_cpy, Gtk.PositionType.RIGHT, 1, 1) # Padding and full width",
"= Gtk.Label() lbl_share_kbd.set_markup(_(\"Scan this code to load this keyboard\\non another",
"Gtk.Label() if secure_lookup(info, 'version', 'description'): label.set_text(secure_lookup(info, 'version', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_file label = Gtk.Label()",
"2, 1) prevlabel = lbl_pad # If it doesn't exist,",
"Windows # TODO clean up file once have what we",
"= lbl_kbd_auth label = Gtk.Label() if secure_lookup(kbdata, 'authorName'): label.set_text(kbdata['authorName']) label.set_halign(Gtk.Align.START)",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_id, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_vrs = Gtk.Label()",
"= path.join(packageDir, kmp['packageID'] + \".json\") if path.isfile(jsonfile): try: with open(jsonfile,",
"keyman_config.kmpmetadata import parsemetadata gi.require_version('Gtk', '3.0') # basics: keyboard name, package",
"Gtk.Label() lbl_kbd_lic.set_text(_(\"Keyboard license: \")) lbl_kbd_lic.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_lic, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"1) if secure_lookup(info, \"author\"): lbl_pkg_auth = Gtk.Label() lbl_pkg_auth.set_text(_(\"Package author: \"))",
"kmp_json = path.join(packageDir, \"kmp.json\") info, system, options, keyboards, files =",
"lbl_kbd_desc, Gtk.PositionType.RIGHT, 1, 1) # Padding and full width horizontal",
"OSK availability, documentation availability, package copyright # also: supported languages,",
"lbl_pkg_id = Gtk.Label() lbl_pkg_id.set_text(_(\"Package id: \")) lbl_pkg_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_id, prevlabel, Gtk.PositionType.BOTTOM,",
"info lbl_pkg_name = Gtk.Label() lbl_pkg_name.set_text(_(\"Package name: \")) lbl_pkg_name.set_halign(Gtk.Align.END) grid.add(lbl_pkg_name) prevlabel",
"\"This keyboard is distributed under the MIT license (MIT) as",
"from keyman_config.accelerators import init_accel from keyman_config.kmpmetadata import parsemetadata gi.require_version('Gtk', '3.0')",
"info, system, options, keyboards, files = parsemetadata(kmp_json) if info is",
"keyboards: for kbd in keyboards: kbdata = None jsonfile =",
"path.isfile(path_qr): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=4, border=4) qr.add_data(url) qr.make(fit=True)",
"Gtk.Label() lbl_kbd_name.set_text(_(\"Keyboard name: \")) lbl_kbd_name.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_name, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"label.set_text(kbdata['license']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_lic, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_desc =",
"<reponame>srl295/keyman #!/usr/bin/python3 # Keyboard details window import logging import json",
"1, 1) prevlabel = lbl_kbd_auth label = Gtk.Label() if secure_lookup(kbdata,",
"lbl_kbd_lic, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_desc = Gtk.Label() lbl_kbd_desc.set_text(_(\"Keyboard description: \"))",
"installed in to show this # # label = Gtk.Label()",
"None jsonfile = path.join(packageDir, kmp['packageID'] + \".json\") if path.isfile(jsonfile): try:",
"image = Gtk.Image() image.set_from_file(path_qr) grid.attach_next_to(image, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) lbl_share_kbd",
"1, 1) lbl_kbd_lic = Gtk.Label() lbl_kbd_lic.set_text(_(\"Keyboard license: \")) lbl_kbd_lic.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_lic,",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_file, Gtk.PositionType.RIGHT, 1, 1) if kbdata and",
"'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_auth, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info,",
"# start with padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad,",
"lbl_kbd_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_auth label",
"grid.attach_next_to(image, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) lbl_share_kbd = Gtk.Label() lbl_share_kbd.set_markup(_(\"Scan this",
"be centered image = Gtk.Image() image.set_from_file(path_qr) grid.attach_next_to(image, prevlabel, Gtk.PositionType.BOTTOM, 2,",
"qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=4, border=4) qr.add_data(url) qr.make(fit=True) img",
"lbl_kbd_name.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_name, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_name label",
"Gtk.Label() lbl_kbd_file.set_text(_(\"Keyboard filename: \")) lbl_kbd_file.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_file, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"# label = Gtk.Label() # # label.set_text(secure_lookup(info, 'version', 'description')) #",
"keyboard package path_qr = path.join(tempfile.gettempdir(), kmp['packageID'] + '_qrcode.png') url =",
"= Gtk.Label() if secure_lookup(kbdata, 'id'): label.set_text(kbdata['id']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_id,",
"# other things: filename (of kmx), , # OSK availability,",
"error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=4, border=4) qr.add_data(url) qr.make(fit=True) img = qr.make_image() img.save(path_qr) #",
"TODO Display all the information that is available # especially",
"'description'): label.set_text(secure_lookup(info, 'version', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_vrs, Gtk.PositionType.RIGHT, 1,",
"grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad divider_pkg =",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_vrs label = Gtk.Label()",
"horizontal divider lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM,",
"lbl_kbd_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_vrs label",
"code to load this keyboard\\non another device or <a href='{uri}'>share",
"1) prevlabel = lbl_share_kbd self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) self.get_content_area().pack_start(grid, True, True, 12)",
"<a href='{uri}'>share online</a>\").format(uri=url)) lbl_share_kbd.set_halign(Gtk.Align.CENTER) lbl_share_kbd.set_line_wrap(True) grid.attach_next_to(lbl_share_kbd, image, Gtk.PositionType.BOTTOM, 2, 1)",
"lbl_pkg_name = Gtk.Label() lbl_pkg_name.set_text(_(\"Package name: \")) lbl_pkg_name.set_halign(Gtk.Align.END) grid.add(lbl_pkg_name) prevlabel =",
"encoding, layout type # there is data in kmp.inf/kmp.json #",
"Gtk.Label() lbl_kbd_auth.set_text(_(\"Keyboard author: \")) lbl_kbd_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"divider_pkg = Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) # label7",
"1, 1) lbl_pkg_id = Gtk.Label() lbl_pkg_id.set_text(_(\"Package id: \")) lbl_pkg_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_id,",
"'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_name, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_id =",
"label.set_text(path.join(packageDir, kbd['id'] + \".kmx\")) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_file, Gtk.PositionType.RIGHT, 1,",
"welcome_file = path.join(\"/usr/local/share/doc/keyman\", kmp[\"id\"], \"welcome.htm\") # # if path.isfile(welcome_file): #",
"prevlabel = lbl_pad # If it doesn't exist, generate QR",
"grid.attach_next_to(label, lbl_kbd_desc, Gtk.PositionType.RIGHT, 1, 1) # Padding and full width",
"Gtk.Label() # # stored in kmx # label9.set_text(_(\"Message: \")) #",
"= lbl_kbd_lic label = Gtk.Label() if secure_lookup(kbdata, 'license'): label.set_text(kbdata['license']) label.set_halign(Gtk.Align.START)",
"# especially what is displayed for Keyman on Windows #",
"label9 # label = Gtk.Label() # label.set_line_wrap(True) # label.set_text( #",
"1) # label9 = Gtk.Label() # # stored in kmx",
"label9.set_halign(Gtk.Align.END) # grid.attach_next_to(label9, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel =",
"# TODO clean up file once have what we want",
"and then \\\"Install\\\" the keyboard.\")) lbl_invalid_metadata.set_halign(Gtk.Align.END) grid.add(lbl_invalid_metadata) self.resize(700, 200) self.show_all()",
"= Gtk.Label() lbl_pkg_vrs.set_text(_(\"Package version: \")) lbl_pkg_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"lbl_share_kbd = Gtk.Label() lbl_share_kbd.set_markup(_(\"Scan this code to load this keyboard\\non",
"if path.isfile(jsonfile): try: with open(jsonfile, \"r\") as read_file: kbdata =",
"+ \"/go/keyboard/\" + kmp['packageID'] + \"/share\" if not path.isfile(path_qr): qr",
"secure_lookup(kbdata, 'description'): lbl_pkg_desc = Gtk.Label() lbl_pkg_desc.set_text(_(\"Package description: \")) lbl_pkg_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_desc,",
"'description'): lbl_pkg_desc = Gtk.Label() lbl_pkg_desc.set_text(_(\"Package description: \")) lbl_pkg_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_desc, prevlabel,",
"TODO clean up file once have what we want def",
"1) # Padding and full width horizontal divider lbl_pad =",
"keyman_config import KeymanComUrl, _, secure_lookup from keyman_config.accelerators import init_accel from",
"os import path import qrcode import tempfile import gi from",
"label = Gtk.Label() label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_pkg_desc, Gtk.PositionType.RIGHT,",
"'authorName'): label.set_text(kbdata['authorName']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_auth, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_lic",
"# label.set_selectable(True) # # grid.attach_next_to(label, label8, Gtk.PositionType.RIGHT, 1, 1) #",
"path.join(tempfile.gettempdir(), kmp['packageID'] + '_qrcode.png') url = KeymanComUrl + \"/go/keyboard/\" +",
"columns so it will be centered image = Gtk.Image() image.set_from_file(path_qr)",
"code to share keyboard package path_qr = path.join(tempfile.gettempdir(), kmp['packageID'] +",
"= None jsonfile = path.join(packageDir, kmp['packageID'] + \".json\") if path.isfile(jsonfile):",
"= Gtk.Label() lbl_kbd_id.set_text(_(\"Keyboard id: \")) lbl_kbd_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_id, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"'description')) # # label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # # grid.attach_next_to(label,",
"= lbl_share_kbd self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) self.get_content_area().pack_start(grid, True, True, 12) self.resize(800, 450)",
"2, 1) prevlabel = lbl_share_kbd self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) self.get_content_area().pack_start(grid, True, True,",
"1) # label7 = Gtk.Label() # label7.set_text(_(\"On Screen Keyboard: \"))",
"lbl_pkg_id.set_text(_(\"Package id: \")) lbl_pkg_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_share_kbd self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) self.get_content_area().pack_start(grid, True,",
"= Gtk.Label() # # welcome_file = path.join(\"/usr/local/share/doc/keyman\", kmp[\"id\"], \"welcome.htm\") #",
"grid.attach_next_to(lbl_kbd_name, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_name label =",
"1, 1) prevlabel = lbl_pkg_auth label = Gtk.Label() if secure_lookup(info,",
"\".json\") if path.isfile(jsonfile): try: with open(jsonfile, \"r\") as read_file: kbdata",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_id label = Gtk.Label() if",
"invalid metadata self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) grid = Gtk.Grid() self.get_content_area().pack_start(grid, True, True,",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_cpy, Gtk.PositionType.RIGHT, 1, 1) # Padding and",
"= Gtk.Label() if secure_lookup(kmp, 'packageID'): label.set_text(kmp['packageID']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_id,",
"and secure_lookup(kbdata, 'id') != secure_lookup(kmp, 'packageID'): lbl_kbd_name = Gtk.Label() lbl_kbd_name.set_text(_(\"Keyboard",
"Gtk.Label() if secure_lookup(kbdata, 'description'): label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_kbd_desc,",
"or <a href='{uri}'>share online</a>\").format(uri=url)) lbl_share_kbd.set_halign(Gtk.Align.CENTER) lbl_share_kbd.set_line_wrap(True) grid.attach_next_to(lbl_share_kbd, image, Gtk.PositionType.BOTTOM, 2,",
"Gtk from keyman_config import KeymanComUrl, _, secure_lookup from keyman_config.accelerators import",
"1) prevlabel = lbl_pkg_desc label = Gtk.Label() label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label8 # #TODO",
"keyboards: kbdata = None jsonfile = path.join(packageDir, kbd['id'] + \".json\")",
"# # stored in kmx # label9.set_text(_(\"Message: \")) # label9.set_halign(Gtk.Align.END)",
"grid.attach_next_to(lbl_pkg_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_id label =",
"jsonfile, e.args) # start with padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\")",
"Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad # show the icon",
"label9, Gtk.PositionType.RIGHT, 1, 1) # Add an entire row of",
"label7 # # label = Gtk.Label() # # label.set_text(secure_lookup(info, 'version',",
"label9.set_text(_(\"Message: \")) # label9.set_halign(Gtk.Align.END) # grid.attach_next_to(label9, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"lbl_pkg_desc = Gtk.Label() lbl_pkg_desc.set_text(_(\"Package description: \")) lbl_pkg_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_desc, prevlabel, Gtk.PositionType.BOTTOM,",
"label.set_text(kbdata['name']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_name, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_id =",
"grid.attach_next_to(label7, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label7 #",
"1) prevlabel = lbl_kbd_vrs label = Gtk.Label() if secure_lookup(kbdata, 'version'):",
"href='{uri}'>share online</a>\").format(uri=url)) lbl_share_kbd.set_halign(Gtk.Align.CENTER) lbl_share_kbd.set_line_wrap(True) grid.attach_next_to(lbl_share_kbd, image, Gtk.PositionType.BOTTOM, 2, 1) prevlabel",
"path.join(\"/usr/local/share/keyman\", kmp[\"id\"], kmp[\"id\"] + \".json\") # Package info lbl_pkg_name =",
"Gtk.Label() if secure_lookup(kbdata, 'authorName'): label.set_text(kbdata['authorName']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_auth, Gtk.PositionType.RIGHT,",
"label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_lic, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_desc = Gtk.Label() lbl_kbd_desc.set_text(_(\"Keyboard",
"divider_pkg = Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel =",
"# label.set_text(_(\"Not installed\")) # # label.set_halign(Gtk.Align.START) # # label.set_selectable(True) #",
"= kmp[\"name\"] else: wintitle = _(\"{name} keyboard\").format(name=kmp[\"name\"]) Gtk.Dialog.__init__(self, wintitle, parent)",
"if info is None: # Dialog when invalid metadata self.add_button(_(\"_Close\"),",
"open(jsonfile, \"r\") as read_file: kbdata = json.load(read_file) except Exception as",
"kbdata = None jsonfile = path.join(packageDir, kbd['id'] + \".json\") if",
"if secure_lookup(info, \"author\"): lbl_pkg_auth = Gtk.Label() lbl_pkg_auth.set_text(_(\"Package author: \")) lbl_pkg_auth.set_halign(Gtk.Align.END)",
"lbl_invalid_metadata.set_halign(Gtk.Align.END) grid.add(lbl_invalid_metadata) self.resize(700, 200) self.show_all() return kbdata = None jsonfile",
"label.set_text(secure_lookup(info, 'version', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_vrs, Gtk.PositionType.RIGHT, 1, 1)",
"grid.attach_next_to(label8, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label8 #",
"label.set_selectable(True) # grid.attach_next_to(label, label9, Gtk.PositionType.RIGHT, 1, 1) # Add an",
"kbdata = json.load(read_file) except Exception as e: logging.warning('Exception %s reading",
"lbl_kbd_lic.set_text(_(\"Keyboard license: \")) lbl_kbd_lic.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_lic, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"\"/share\" if not path.isfile(path_qr): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=4,",
"prevlabel = lbl_pad divider_pkg = Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2,",
"lbl_pkg_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_auth label",
"lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad #",
"import KeymanComUrl, _, secure_lookup from keyman_config.accelerators import init_accel from keyman_config.kmpmetadata",
"generate QR code to share keyboard package path_qr = path.join(tempfile.gettempdir(),",
"kmp['packageID'] + \"/share\" if not path.isfile(path_qr): qr = qrcode.QRCode( version=1,",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_file label = Gtk.Label() label.set_text(path.join(packageDir,",
"label8.set_halign(Gtk.Align.END) # grid.attach_next_to(label8, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel =",
"grid.attach_next_to(lbl_pkg_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_vrs label =",
"lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM, 2, 1)",
"somewhere lbl_kbd_file = Gtk.Label() lbl_kbd_file.set_text(_(\"Keyboard filename: \")) lbl_kbd_file.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_file, prevlabel,",
"import gi from gi.repository import Gtk from keyman_config import KeymanComUrl,",
"label = Gtk.Label() if secure_lookup(kbdata, 'name'): label.set_text(kbdata['name']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_auth, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_lic = Gtk.Label() lbl_kbd_lic.set_text(_(\"Keyboard",
"grid.attach_next_to(label, lbl_kbd_auth, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_lic = Gtk.Label() lbl_kbd_lic.set_text(_(\"Keyboard license:",
"which area keyboard is installed in to show this #",
"# label.set_text(_(\"Installed\")) # # else: # # label.set_text(_(\"Not installed\")) #",
"grid.attach_next_to(lbl_kbd_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_id label =",
"= lbl_pad divider_pkg = Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1)",
"jsonfile, e.args) grid = Gtk.Grid() # grid.set_column_homogeneous(True) # kbdatapath =",
"Gtk.Label() # # label.set_text(secure_lookup(info, 'version', 'description')) # # label.set_halign(Gtk.Align.START) #",
"lbl_kbd_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"): lbl_kbd_auth = Gtk.Label()",
"1) prevlabel = lbl_kbd_file label = Gtk.Label() label.set_text(path.join(packageDir, kbd['id'] +",
"# label.set_line_wrap(True) # label.set_text( # \"This keyboard is distributed under",
"= Gtk.Label() # label7.set_text(_(\"On Screen Keyboard: \")) # label7.set_halign(Gtk.Align.END) #",
"\\\"Uninstall\\\" and then \\\"Install\\\" the keyboard.\")) lbl_invalid_metadata.set_halign(Gtk.Align.END) grid.add(lbl_invalid_metadata) self.resize(700, 200)",
"label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # # grid.attach_next_to(label, label7, Gtk.PositionType.RIGHT, 1,",
"label.set_selectable(True) # # grid.attach_next_to(label, label7, Gtk.PositionType.RIGHT, 1, 1) # label8",
"1) prevlabel = lbl_kbd_id label = Gtk.Label() if secure_lookup(kbdata, 'id'):",
"Gtk.PositionType.BOTTOM, 2, 1) # label7 = Gtk.Label() # label7.set_text(_(\"On Screen",
"= lbl_kbd_desc label = Gtk.Label() if secure_lookup(kbdata, 'description'): label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START)",
"lbl_pkg_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_desc label",
"start with padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel,",
"lbl_kbd_desc.set_text(_(\"Keyboard description: \")) lbl_kbd_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"1, 1) prevlabel = lbl_kbd_desc label = Gtk.Label() if secure_lookup(kbdata,",
"api) class KeyboardDetailsView(Gtk.Dialog): # TODO Display all the information that",
"= lbl_pkg_cpy label = Gtk.Label() if secure_lookup(info, 'copyright', 'description'): label.set_text(secure_lookup(info,",
"Keyman on Windows # TODO clean up file once have",
"in keyboards: kbdata = None jsonfile = path.join(packageDir, kbd['id'] +",
"\")) lbl_kbd_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_desc",
"keyboard\\non another device or <a href='{uri}'>share online</a>\").format(uri=url)) lbl_share_kbd.set_halign(Gtk.Align.CENTER) lbl_share_kbd.set_line_wrap(True) grid.attach_next_to(lbl_share_kbd,",
"kbdata = None jsonfile = path.join(packageDir, kmp['packageID'] + \".json\") if",
"json from os import path import qrcode import tempfile import",
"Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad divider_pkg = Gtk.HSeparator() grid.attach_next_to(divider_pkg,",
"'name'): label.set_text(kbdata['name']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_name, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_id",
"\"author\"): lbl_pkg_auth = Gtk.Label() lbl_pkg_auth.set_text(_(\"Package author: \")) lbl_pkg_auth.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_auth, prevlabel,",
"1, 1) prevlabel = lbl_pkg_id label = Gtk.Label() if secure_lookup(kmp,",
"lbl_pkg_cpy.set_text(_(\"Package copyright: \")) lbl_pkg_cpy.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_cpy, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"it doesn't exist, generate QR code to share keyboard package",
"self.show_all() return kbdata = None jsonfile = path.join(packageDir, kmp['packageID'] +",
"grid.attach_next_to(lbl_pkg_cpy, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_cpy label =",
"Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad # If it doesn't",
"lbl_pkg_name.set_halign(Gtk.Align.END) grid.add(lbl_pkg_name) prevlabel = lbl_pkg_name label = Gtk.Label() if secure_lookup(info,",
"# basics: keyboard name, package version, description # other things:",
"# grid.attach_next_to(label7, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label7",
"Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"copyright\"): lbl_pkg_cpy = Gtk.Label() lbl_pkg_cpy.set_text(_(\"Package",
"# # label.set_selectable(True) # # grid.attach_next_to(label, label7, Gtk.PositionType.RIGHT, 1, 1)",
"copyright: \")) lbl_pkg_cpy.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_cpy, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"= lbl_pkg_desc label = Gtk.Label() label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label,",
"then \\\"Install\\\" the keyboard.\")) lbl_invalid_metadata.set_halign(Gtk.Align.END) grid.add(lbl_invalid_metadata) self.resize(700, 200) self.show_all() return",
"Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label7 # # label",
"label8.set_text(_(\"Documentation: \")) # label8.set_halign(Gtk.Align.END) # grid.attach_next_to(label8, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"label8, Gtk.PositionType.RIGHT, 1, 1) # label9 = Gtk.Label() # #",
"share keyboard package path_qr = path.join(tempfile.gettempdir(), kmp['packageID'] + '_qrcode.png') url",
"entire row of padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad,",
"lbl_kbd_name label = Gtk.Label() if secure_lookup(kbdata, 'name'): label.set_text(kbdata['name']) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"label.set_line_wrap(80) grid.attach_next_to(label, lbl_pkg_desc, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"): lbl_pkg_auth",
"# label7.set_text(_(\"On Screen Keyboard: \")) # label7.set_halign(Gtk.Align.END) # grid.attach_next_to(label7, prevlabel,",
"= Gtk.Label() label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_pkg_desc, Gtk.PositionType.RIGHT, 1,",
"has name, version, packageID, area if \"keyboard\" in kmp[\"name\"].lower(): wintitle",
"label = Gtk.Label() if secure_lookup(kmp, 'packageID'): label.set_text(kmp['packageID']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"\")) # label7.set_halign(Gtk.Align.END) # grid.attach_next_to(label7, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) #",
"#TODO need to know which area keyboard is installed in",
"MIT license (MIT) as described somewhere\") # #label.set_text(kmp[\"description\"]) # label.set_halign(Gtk.Align.START)",
"grid.attach_next_to(label, lbl_pkg_auth, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"copyright\"): lbl_pkg_cpy =",
"grid.attach_next_to(label9, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel = label9 #",
"especially what is displayed for Keyman on Windows # TODO",
"grid.attach_next_to(lbl_pkg_auth, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_auth label =",
"label = Gtk.Label() if secure_lookup(info, 'copyright', 'description'): label.set_text(secure_lookup(info, 'copyright', 'description'))",
"True, True, 12) lbl_invalid_metadata = Gtk.Label() lbl_invalid_metadata.set_text(_(\"ERROR: Keyboard metadata is",
"grid.attach_next_to(lbl_kbd_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_vrs label =",
"label.set_text( # \"This keyboard is distributed under the MIT license",
"If it doesn't exist, generate QR code to share keyboard",
"= KeymanComUrl + \"/go/keyboard/\" + kmp['packageID'] + \"/share\" if not",
"'name', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_name, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_id",
"= Gtk.Label() # label8.set_text(_(\"Documentation: \")) # label8.set_halign(Gtk.Align.END) # grid.attach_next_to(label8, prevlabel,",
"= Gtk.HSeparator() grid.attach_next_to(divider_pkg, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = divider_pkg",
"prevlabel = divider_pkg # Keyboard info for each keyboard if",
"id: \")) lbl_kbd_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"lbl_kbd_file.set_text(_(\"Keyboard filename: \")) lbl_kbd_file.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_file, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"grid.attach_next_to(label, lbl_kbd_id, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_vrs = Gtk.Label() lbl_kbd_vrs.set_text(_(\"Keyboard version:",
"1, 1) # label9 = Gtk.Label() # # stored in",
"= Gtk.Label() # # stored in kmx # label9.set_text(_(\"Message: \"))",
"of padding lbl_pad = Gtk.Label() lbl_pad.set_text(\"\") lbl_pad.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pad, prevlabel, Gtk.PositionType.BOTTOM,",
"packageDir = path.join(kmp['areapath'], kmp['packageID']) kmp_json = path.join(packageDir, \"kmp.json\") info, system,",
"lbl_kbd_file, Gtk.PositionType.RIGHT, 1, 1) if kbdata and secure_lookup(kbdata, 'id') !=",
"e: logging.warning('Exception %s reading %s %s', type(e), jsonfile, e.args) grid",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_lic label = Gtk.Label() if",
"label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_cpy, Gtk.PositionType.RIGHT, 1, 1) # Padding and full",
"# Keyboard details window import logging import json from os",
"lbl_invalid_metadata.set_text(_(\"ERROR: Keyboard metadata is damaged.\\nPlease \\\"Uninstall\\\" and then \\\"Install\\\" the",
"# # label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # # grid.attach_next_to(label, label7,",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_id label = Gtk.Label()",
"have what we want def __init__(self, parent, kmp): # kmp",
"name, package version, description # other things: filename (of kmx),",
"# prevlabel = label9 # label = Gtk.Label() # label.set_line_wrap(True)",
"Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(kbdata, 'description'): lbl_pkg_desc = Gtk.Label() lbl_pkg_desc.set_text(_(\"Package",
"Gtk.Label() lbl_kbd_id.set_text(_(\"Keyboard id: \")) lbl_kbd_id.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_id, prevlabel, Gtk.PositionType.BOTTOM, 1, 1)",
"jsonfile = path.join(packageDir, kmp['packageID'] + \".json\") if path.isfile(jsonfile): try: with",
"Gtk.PositionType.RIGHT, 1, 1) if kbdata and secure_lookup(kbdata, 'id') != secure_lookup(kmp,",
"Gtk.Image() image.set_from_file(path_qr) grid.attach_next_to(image, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) lbl_share_kbd = Gtk.Label()",
"= Gtk.Label() lbl_pkg_desc.set_text(_(\"Package description: \")) lbl_pkg_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_desc, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"secure_lookup(info, 'name', 'description'): label.set_text(secure_lookup(info, 'name', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_name,",
"1, 1) prevlabel = lbl_pkg_desc label = Gtk.Label() label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START)",
"label = Gtk.Label() if secure_lookup(kbdata, 'authorName'): label.set_text(kbdata['authorName']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"Screen Keyboard: \")) # label7.set_halign(Gtk.Align.END) # grid.attach_next_to(label7, prevlabel, Gtk.PositionType.BOTTOM, 1,",
"+ \".json\") # Package info lbl_pkg_name = Gtk.Label() lbl_pkg_name.set_text(_(\"Package name:",
"Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(info, \"author\"): lbl_pkg_auth = Gtk.Label() lbl_pkg_auth.set_text(_(\"Package",
"kmp[\"id\"], \"welcome.htm\") # # if path.isfile(welcome_file): # # label.set_text(_(\"Installed\")) #",
"Gtk.PositionType.RIGHT, 1, 1) # Add an entire row of padding",
"lbl_kbd_lic = Gtk.Label() lbl_kbd_lic.set_text(_(\"Keyboard license: \")) lbl_kbd_lic.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_lic, prevlabel, Gtk.PositionType.BOTTOM,",
"label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_pkg_desc, Gtk.PositionType.RIGHT, 1, 1) if",
"init_accel from keyman_config.kmpmetadata import parsemetadata gi.require_version('Gtk', '3.0') # basics: keyboard",
"label8 # #TODO need to know which area keyboard is",
"in kmx # label9.set_text(_(\"Message: \")) # label9.set_halign(Gtk.Align.END) # grid.attach_next_to(label9, prevlabel,",
"label = Gtk.Label() if secure_lookup(kbdata, 'version'): label.set_text(kbdata['version']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_id = Gtk.Label() lbl_pkg_id.set_text(_(\"Package id: \")) lbl_pkg_id.set_halign(Gtk.Align.END)",
"grid.attach_next_to(label, lbl_pkg_name, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_id = Gtk.Label() lbl_pkg_id.set_text(_(\"Package id:",
"label = Gtk.Label() if secure_lookup(kbdata, 'description'): label.set_text(kbdata['description']) label.set_halign(Gtk.Align.START) label.set_selectable(True) label.set_line_wrap(80)",
"prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad # If it",
"description: \")) lbl_pkg_desc.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_desc, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"path.join(packageDir, \"kmp.json\") info, system, options, keyboards, files = parsemetadata(kmp_json) if",
"label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_id, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_vrs = Gtk.Label() lbl_pkg_vrs.set_text(_(\"Package",
"1) # prevlabel = label8 # #TODO need to know",
"= Gtk.Label() if secure_lookup(info, 'name', 'description'): label.set_text(secure_lookup(info, 'name', 'description')) label.set_halign(Gtk.Align.START)",
"lbl_kbd_file.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_file, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_file label",
"lbl_kbd_name.set_text(_(\"Keyboard name: \")) lbl_kbd_name.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_name, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel",
"Gtk.Label() # label7.set_text(_(\"On Screen Keyboard: \")) # label7.set_halign(Gtk.Align.END) # grid.attach_next_to(label7,",
"Gtk.Label() if secure_lookup(kbdata, 'name'): label.set_text(kbdata['name']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_name, Gtk.PositionType.RIGHT,",
"= Gtk.Label() if secure_lookup(kbdata, 'version'): label.set_text(kbdata['version']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_kbd_vrs,",
"the information that is available # especially what is displayed",
"prevlabel = lbl_kbd_auth label = Gtk.Label() if secure_lookup(kbdata, 'authorName'): label.set_text(kbdata['authorName'])",
"\")) lbl_pkg_vrs.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_pkg_vrs, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_pkg_vrs",
"filename: \")) lbl_kbd_file.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_file, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel =",
"'version', 'description'): label.set_text(secure_lookup(info, 'version', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_vrs, Gtk.PositionType.RIGHT,",
"Gtk.Grid() # grid.set_column_homogeneous(True) # kbdatapath = path.join(\"/usr/local/share/keyman\", kmp[\"id\"], kmp[\"id\"] +",
"= lbl_kbd_vrs label = Gtk.Label() if secure_lookup(kbdata, 'version'): label.set_text(kbdata['version']) label.set_halign(Gtk.Align.START)",
"prevlabel = lbl_kbd_lic label = Gtk.Label() if secure_lookup(kbdata, 'license'): label.set_text(kbdata['license'])",
"prevlabel = lbl_pkg_vrs label = Gtk.Label() if secure_lookup(info, 'version', 'description'):",
"Gtk.Label() if secure_lookup(info, 'author', 'description'): label.set_text(secure_lookup(info, 'author', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True)",
"# also: supported languages, fonts # from kmx?: keyboard version,",
"= lbl_pkg_id label = Gtk.Label() if secure_lookup(kmp, 'packageID'): label.set_text(kmp['packageID']) label.set_halign(Gtk.Align.START)",
"if secure_lookup(info, 'version', 'description'): label.set_text(secure_lookup(info, 'version', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"# # label.set_halign(Gtk.Align.START) # # label.set_selectable(True) # # grid.attach_next_to(label, label8,",
"read_file: kbdata = json.load(read_file) except Exception as e: logging.warning('Exception %s",
"label.set_text(kmp['packageID']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_id, Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_vrs =",
"name: \")) lbl_pkg_name.set_halign(Gtk.Align.END) grid.add(lbl_pkg_name) prevlabel = lbl_pkg_name label = Gtk.Label()",
"# label9.set_halign(Gtk.Align.END) # grid.attach_next_to(label9, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) # prevlabel",
"= Gtk.Grid() # grid.set_column_homogeneous(True) # kbdatapath = path.join(\"/usr/local/share/keyman\", kmp[\"id\"], kmp[\"id\"]",
"label = Gtk.Label() if secure_lookup(kbdata, 'id'): label.set_text(kbdata['id']) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label,",
"the icon somewhere lbl_kbd_file = Gtk.Label() lbl_kbd_file.set_text(_(\"Keyboard filename: \")) lbl_kbd_file.set_halign(Gtk.Align.END)",
"label8 = Gtk.Label() # label8.set_text(_(\"Documentation: \")) # label8.set_halign(Gtk.Align.END) # grid.attach_next_to(label8,",
"gi.require_version('Gtk', '3.0') # basics: keyboard name, package version, description #",
"prevlabel, Gtk.PositionType.BOTTOM, 2, 1) lbl_share_kbd = Gtk.Label() lbl_share_kbd.set_markup(_(\"Scan this code",
"1, 1) # Padding and full width horizontal divider lbl_pad",
"prevlabel, Gtk.PositionType.BOTTOM, 2, 1) prevlabel = lbl_pad divider_pkg = Gtk.HSeparator()",
"if path.isfile(welcome_file): # # label.set_text(_(\"Installed\")) # # else: # #",
"lbl_pkg_cpy, Gtk.PositionType.RIGHT, 1, 1) # Padding and full width horizontal",
"# Display QR Code, spanning 2 columns so it will",
"keyboard is installed in to show this # # label",
"what we want def __init__(self, parent, kmp): # kmp has",
"\")) lbl_kbd_lic.set_halign(Gtk.Align.END) grid.attach_next_to(lbl_kbd_lic, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_lic",
"basics: keyboard name, package version, description # other things: filename",
"label = Gtk.Label() if secure_lookup(info, 'author', 'description'): label.set_text(secure_lookup(info, 'author', 'description'))",
"prevlabel = label9 # label = Gtk.Label() # label.set_line_wrap(True) #",
"prevlabel = label7 # # label = Gtk.Label() # #",
"e.args) grid = Gtk.Grid() # grid.set_column_homogeneous(True) # kbdatapath = path.join(\"/usr/local/share/keyman\",",
"Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_auth label = Gtk.Label() if",
"label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_vrs, Gtk.PositionType.RIGHT, 1, 1) if secure_lookup(kbdata, 'description'):",
"# label7 = Gtk.Label() # label7.set_text(_(\"On Screen Keyboard: \")) #",
"1) prevlabel = lbl_kbd_name label = Gtk.Label() if secure_lookup(kbdata, 'name'):",
"with open(jsonfile, \"r\") as read_file: kbdata = json.load(read_file) except Exception",
"kmx), , # OSK availability, documentation availability, package copyright #",
"grid.set_column_homogeneous(True) # kbdatapath = path.join(\"/usr/local/share/keyman\", kmp[\"id\"], kmp[\"id\"] + \".json\") #",
"possibly data in kbid.json (downloaded from api) class KeyboardDetailsView(Gtk.Dialog): #",
"kmp[\"name\"] else: wintitle = _(\"{name} keyboard\").format(name=kmp[\"name\"]) Gtk.Dialog.__init__(self, wintitle, parent) init_accel(self)",
"Exception as e: logging.warning('Exception %s reading %s %s', type(e), jsonfile,",
"version, packageID, area if \"keyboard\" in kmp[\"name\"].lower(): wintitle = kmp[\"name\"]",
"lbl_kbd_name, Gtk.PositionType.RIGHT, 1, 1) lbl_kbd_id = Gtk.Label() lbl_kbd_id.set_text(_(\"Keyboard id: \"))",
"# # else: # # label.set_text(_(\"Not installed\")) # # label.set_halign(Gtk.Align.START)",
"info is None: # Dialog when invalid metadata self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE)",
"'3.0') # basics: keyboard name, package version, description # other",
"in kbid.json (downloaded from api) class KeyboardDetailsView(Gtk.Dialog): # TODO Display",
"# label.set_text( # \"This keyboard is distributed under the MIT",
"languages, fonts # from kmx?: keyboard version, encoding, layout type",
"label.set_selectable(True) label.set_line_wrap(80) grid.attach_next_to(label, lbl_kbd_desc, Gtk.PositionType.RIGHT, 1, 1) # Padding and",
"label = Gtk.Label() if secure_lookup(info, 'version', 'description'): label.set_text(secure_lookup(info, 'version', 'description'))",
"'copyright', 'description'): label.set_text(secure_lookup(info, 'copyright', 'description')) label.set_halign(Gtk.Align.START) label.set_selectable(True) grid.attach_next_to(label, lbl_pkg_cpy, Gtk.PositionType.RIGHT,",
"label.set_selectable(True) # # grid.attach_next_to(label, label8, Gtk.PositionType.RIGHT, 1, 1) # label9",
"what is displayed for Keyman on Windows # TODO clean",
"except Exception as e: logging.warning('Exception %s reading %s %s', type(e),",
"grid.attach_next_to(lbl_kbd_file, prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_file label =",
"200) self.show_all() return kbdata = None jsonfile = path.join(packageDir, kmp['packageID']",
"QR code to share keyboard package path_qr = path.join(tempfile.gettempdir(), kmp['packageID']",
"prevlabel = lbl_pkg_auth label = Gtk.Label() if secure_lookup(info, 'author', 'description'):",
"__init__(self, parent, kmp): # kmp has name, version, packageID, area",
"filename (of kmx), , # OSK availability, documentation availability, package",
"border=4) qr.add_data(url) qr.make(fit=True) img = qr.make_image() img.save(path_qr) # Display QR",
"layout type # there is data in kmp.inf/kmp.json # there",
"is None: # Dialog when invalid metadata self.add_button(_(\"_Close\"), Gtk.ResponseType.CLOSE) grid",
"None jsonfile = path.join(packageDir, kbd['id'] + \".json\") if path.isfile(jsonfile): try:",
"# label.set_text(secure_lookup(info, 'version', 'description')) # # label.set_halign(Gtk.Align.START) # # label.set_selectable(True)",
"= Gtk.Label() if secure_lookup(info, 'author', 'description'): label.set_text(secure_lookup(info, 'author', 'description')) label.set_halign(Gtk.Align.START)",
"= path.join(\"/usr/local/share/doc/keyman\", kmp[\"id\"], \"welcome.htm\") # # if path.isfile(welcome_file): # #",
"Gtk.PositionType.RIGHT, 1, 1) lbl_pkg_vrs = Gtk.Label() lbl_pkg_vrs.set_text(_(\"Package version: \")) lbl_pkg_vrs.set_halign(Gtk.Align.END)",
"prevlabel, Gtk.PositionType.BOTTOM, 1, 1) prevlabel = lbl_kbd_desc label = Gtk.Label()",
"image.set_from_file(path_qr) grid.attach_next_to(image, prevlabel, Gtk.PositionType.BOTTOM, 2, 1) lbl_share_kbd = Gtk.Label() lbl_share_kbd.set_markup(_(\"Scan",
"package version, description # other things: filename (of kmx), ,",
"1) if kbdata and secure_lookup(kbdata, 'id') != secure_lookup(kmp, 'packageID'): lbl_kbd_name"
] |
[
"TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/libraries' TARGET_DIR = 'SAM.app/Contents/libraries' if os.path.exists(TARGET_DIR):",
"import os import shutil SOURCE_DIR = '../deploy/runtime' TARGET_DIR = 'SAM.app/Contents/runtime'",
"TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/solar_resource' TARGET_DIR = 'SAM.app/Contents/solar_resource' if os.path.exists(TARGET_DIR):",
"ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/libraries' TARGET_DIR = 'SAM.app/Contents/libraries' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR)",
"shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/libraries' TARGET_DIR = 'SAM.app/Contents/libraries' if",
"if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/libraries' TARGET_DIR",
"= 'SAM.app/Contents/runtime' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR =",
"'../deploy/wind_resource' TARGET_DIR = 'SAM.app/Contents/wind_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git'))",
"= '../deploy/runtime' TARGET_DIR = 'SAM.app/Contents/runtime' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR,",
"SOURCE_DIR = '../deploy/libraries' TARGET_DIR = 'SAM.app/Contents/libraries' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR,",
"os import shutil SOURCE_DIR = '../deploy/runtime' TARGET_DIR = 'SAM.app/Contents/runtime' if",
"os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/libraries' TARGET_DIR =",
"'../deploy/solar_resource' TARGET_DIR = 'SAM.app/Contents/solar_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git'))",
"ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/solar_resource' TARGET_DIR = 'SAM.app/Contents/solar_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR)",
"SOURCE_DIR = '../deploy/wind_resource' TARGET_DIR = 'SAM.app/Contents/wind_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR,",
"SOURCE_DIR = '../deploy/solar_resource' TARGET_DIR = 'SAM.app/Contents/solar_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR,",
"= '../deploy/wind_resource' TARGET_DIR = 'SAM.app/Contents/wind_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR,",
"import shutil SOURCE_DIR = '../deploy/runtime' TARGET_DIR = 'SAM.app/Contents/runtime' if os.path.exists(TARGET_DIR):",
"= 'SAM.app/Contents/wind_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR =",
"TARGET_DIR = 'SAM.app/Contents/solar_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR",
"if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/solar_resource' TARGET_DIR",
"ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/wind_resource' TARGET_DIR = 'SAM.app/Contents/wind_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR)",
"shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/wind_resource' TARGET_DIR = 'SAM.app/Contents/wind_resource'",
"= '../deploy/solar_resource' TARGET_DIR = 'SAM.app/Contents/solar_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR,",
"os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/wind_resource' TARGET_DIR =",
"'SAM.app/Contents/runtime' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/solar_resource'",
"shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/wind_resource' TARGET_DIR = 'SAM.app/Contents/wind_resource' if",
"'../deploy/libraries' TARGET_DIR = 'SAM.app/Contents/libraries' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git'))",
"os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/solar_resource' TARGET_DIR =",
"SOURCE_DIR = '../deploy/runtime' TARGET_DIR = 'SAM.app/Contents/runtime' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR,",
"shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/solar_resource' TARGET_DIR = 'SAM.app/Contents/solar_resource' if",
"= 'SAM.app/Contents/solar_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR =",
"'SAM.app/Contents/solar_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/wind_resource'",
"TARGET_DIR = 'SAM.app/Contents/runtime' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR",
"= '../deploy/libraries' TARGET_DIR = 'SAM.app/Contents/libraries' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR,",
"if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/wind_resource' TARGET_DIR",
"shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/solar_resource' TARGET_DIR = 'SAM.app/Contents/solar_resource'",
"TARGET_DIR = 'SAM.app/Contents/wind_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR",
"shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/libraries' TARGET_DIR = 'SAM.app/Contents/libraries'",
"TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/wind_resource' TARGET_DIR = 'SAM.app/Contents/wind_resource' if os.path.exists(TARGET_DIR):",
"shutil SOURCE_DIR = '../deploy/runtime' TARGET_DIR = 'SAM.app/Contents/runtime' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR)",
"'SAM.app/Contents/wind_resource' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git')) SOURCE_DIR = '../deploy/libraries'",
"'../deploy/runtime' TARGET_DIR = 'SAM.app/Contents/runtime' if os.path.exists(TARGET_DIR): shutil.rmtree(TARGET_DIR) shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns('.git'))"
] |
[
"################################################################################ # Functions to normalize paths and check that they",
"a symbolic link to source at path. This is basically",
"overall_hash = hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode()) return overall_hash.hexdigest() def hash_file_contents(path): \"\"\" Return",
"False): \"\"\" Copy |source_path| to |dest_path|. Assume dest_path doesn't exist.",
"os.walk: %s' % (root,) directories.append(root) for file_name in file_names: files.append(os.path.join(root,",
"sys from typing import Optional from codalab.common import precondition, UsageError,",
"all directories and then compute a hash of the hashes.",
"path in itertools.chain(*dirs_and_files)) def hash_directory(path, dirs_and_files=None): \"\"\" Return the hash",
"hash is unambiguous - # if we updated directory_hash with",
"these names, which could be generated # in multiple ways.",
"path: %s' % (path,) precondition(os.path.isabs(path), message) if os.path.islink(path): contents_hash =",
"################################################################################ # Functions that modify that filesystem in controlled ways.",
"= os.path.join(root, subpath) if os.path.islink(full_subpath) and os.path.isdir(full_subpath): files.append(full_subpath) return (directories,",
"file_name)): files.append(file_name) else: directories.append(file_name) return (directories, files) def recursive_ls(path): \"\"\"",
"file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode()) # Return a hash of the two hashes.",
"Return the hash of the file's contents, read in blocks",
"to' % source_path, dest_path) def make_directory(path): \"\"\" Create the directory",
"'-R', 'u+w', path]) def rename(old_path, new_path): # Allow write permissions,",
"with relative path: %s' % (path,) precondition(os.path.isabs(path), message) if os.path.islink(path):",
"is not absolute or normalized. Raise a UsageError if the",
"'ftp']: if path.startswith(prefix + '://'): return True return False ################################################################################",
"def safe_join(*paths): \"\"\" Join a sequence of paths but filter",
"given path. This hash is independent of the path itself",
"Blob Storage, we just use the directory size for the",
"\"\"\" Get the size (in bytes) of the file or",
"or under the given path. Does not include symlinked files",
"subprocess import sys from typing import Optional from codalab.common import",
"sorted(directories): relative_path = get_relative_path(path, directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) # Use a similar",
"relative root in os.walk: %s' % (root,) directories.append(root) for file_name",
"check_isdir(path, 'make_directory') def set_write_permissions(path): # Recursively give give write permissions",
"try: shutil.rmtree(path) except shutil.Error: pass else: os.remove(path) if os.path.exists(path): print('Failed",
"files.append(full_subpath) return (directories, files) ################################################################################ # Functions to read files",
"we updated directory_hash with the directory names themselves, then #",
"the hashed contents. return get_size(path) (directories, files) = dirs_and_files or",
"results to stdout, etc: getmtime, get_size, hash_directory, hash_file_contents Functions that",
"path_is_url Functions to list directories and to deal with subpaths",
"etc: getmtime, get_size, hash_directory, hash_file_contents Functions that modify that filesystem",
"targets. Note that os.path.join has this functionality EXCEPT at the",
"return (directories, files) def recursive_ls(path): \"\"\" Return a (list of",
"nested subdirectories. All paths returned are absolute. Symlinks are returned",
"follow symlinks. \"\"\" return os.lstat(path).st_mtime def get_size(path, dirs_and_files=None): \"\"\" Get",
"if not follow_symlinks and os.path.islink(source_path): raise path_error('not following symlinks', source_path)",
"directories. This makes it possible to distinguish between real and",
"fail. set_write_permissions(old_path) subprocess.call(['mv', old_path, new_path]) def remove(path): \"\"\" Remove the",
"at the given path. This hash is independent of the",
"os.path.isdir(path): return os.lstat(path).st_size dirs_and_files = dirs_and_files or recursive_ls(path) return sum(os.lstat(path).st_size",
"dest: file_util.copy( sys.stdin, dest, autoflush=False, print_status='Copying %s to %s' %",
"raise path_error('not following symlinks', source_path) if not os.path.exists(source_path): raise path_error('does",
"path_util contains helpers for working with local filesystem paths. There",
"contents of the folder at the given path. This hash",
"source at path. This is basically the same as doing",
"fn_name) if os.path.isdir(path): raise path_error('%s got directory:' % (fn_name,), path)",
"but filter out any that are empty. Used for targets.",
"as doing \"ln -s $source $path\" \"\"\" check_isvalid(source, 'soft_link') os.symlink(source,",
"hashes. # This two-level hash is necessary so that the",
"Join a sequence of paths but filter out any that",
"if the file at that path does not exist. \"\"\"",
"got non-existent path:' % (fn_name,), path) def check_isdir(path, fn_name): \"\"\"",
"the location specified by the given path. This path is",
"and to deal with subpaths of paths. ################################################################################ def safe_join(*paths):",
"recursive_ls(path) # Sort and then hash all directories and then",
"because a) we don't want # to descend into directories",
"and then hash all directories and then compute a hash",
"Create a symbolic link to source at path. This is",
"is basically the same as doing \"ln -s $source $path\"",
"if not os.path.isdir(path): raise path_error('%s got non-directory:' % (fn_name,), path)",
"for subpath in os.listdir(root): full_subpath = os.path.join(root, subpath) if os.path.islink(full_subpath)",
"list of files, even if they point to directories. This",
"that they are in normal form: normalize, check_isvalid, check_isdir, check_isfile,",
"precondition(os.path.isabs(path), message) if os.path.islink(path): contents_hash = hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode()) else: contents_hash",
"else: os.remove(path) if os.path.exists(path): print('Failed to remove %s' % path)",
"to descend into directories and b) we could end up",
"check_isdir, check_isfile, path_is_url Functions to list directories and to deal",
"stdout, etc: getmtime, get_size, hash_directory, hash_file_contents Functions that modify that",
"a file. \"\"\" check_isvalid(path, fn_name) if os.path.isdir(path): raise path_error('%s got",
"list directories and to deal with subpaths of paths. ################################################################################",
"= ([], []) for file_name in os.listdir(path): if os.path.isfile(os.path.join(path, file_name)):",
"but we should count them as files. # However, we",
"result. \"\"\" if parse_linked_bundle_url(path).uses_beam: # On Azure Blob Storage, we",
"the file name and contents. file_hash = hashlib.sha1() for file_name",
"UsageError(message + ': ' + path) ################################################################################ # Functions to",
"of the hashes. # This two-level hash is necessary so",
"controlled ways. ################################################################################ def copy(source_path: str, dest_path: str, follow_symlinks: Optional[bool]",
"Copy |source_path| to |dest_path|. Assume dest_path doesn't exist. |follow_symlinks|: whether",
"the given path, whether it is a directory, file, or",
"are empty. Used for targets. Note that os.path.join has this",
"else 'l'), source_path + ('/' if not os.path.islink(source_path) and os.path.isdir(source_path)",
"for directory in sorted(directories): relative_path = get_relative_path(path, directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) #",
"raise path_error('%s got directory:' % (fn_name,), path) def path_is_url(path): if",
"descend into directories and b) we could end up in",
"symlinks Note: this only works in Linux. \"\"\" if os.path.exists(dest_path):",
"symlinks', source_path) if not os.path.exists(source_path): raise path_error('does not exist', source_path)",
"file. \"\"\" check_isvalid(path, fn_name) if not os.path.isdir(path): raise path_error('%s got",
"for (root, _, file_names) in os.walk(path): assert os.path.isabs(root), 'Got relative",
"str, dest_path: str, follow_symlinks: Optional[bool] = False): \"\"\" Copy |source_path|",
"path:' % (fn_name,), path) def check_isdir(path, fn_name): \"\"\" Check that",
"import FileSystems if not FileSystems.exists(path): FileSystems.delete([path]) return check_isvalid(path, 'remove') set_write_permissions(path)",
"def normalize(path): \"\"\" Return the absolute path of the location",
"read files to compute hashes, write results to stdout, etc.",
"path) ################################################################################ # Functions to normalize paths and check that",
"\"\"\" if parse_linked_bundle_url(path).uses_beam: # On Azure Blob Storage, we just",
"hashes. overall_hash = hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode()) return overall_hash.hexdigest() def hash_file_contents(path): \"\"\"",
"contents_hash = hashlib.sha1(FILE_PREFIX.encode()) with open(path, 'rb') as file_handle: while True:",
"under root. \"\"\" precondition(path.startswith(root), '%s is not under %s' %",
"in Linux. \"\"\" if os.path.exists(dest_path): raise path_error('already exists', dest_path) if",
"they point to directories. This makes it possible to distinguish",
"not follow symlinks. \"\"\" return os.lstat(path).st_mtime def get_size(path, dirs_and_files=None): \"\"\"",
"_f in paths if _f]) def get_relative_path(root, path): \"\"\" Return",
"returned in the list of files, even if they point",
"('L' if follow_symlinks else 'l'), source_path + ('/' if not",
"the path is valid, then raise UsageError if the path",
"could end up in an infinite loop if # we",
"prefix in ['http', 'https', 'ftp']: if path.startswith(prefix + '://'): return",
"return sum(os.lstat(path).st_size for path in itertools.chain(*dirs_and_files)) def hash_directory(path, dirs_and_files=None): \"\"\"",
"ls, recursive_ls Functions to read files to compute hashes, write",
"modify that filesystem in controlled ways: copy, make_directory, set_write_permissions, rename,",
"of the file or directory at or under the given",
"0x40000 FILE_PREFIX = 'file' LINK_PREFIX = 'link' def path_error(message, path):",
"+ ('/' if not os.path.islink(source_path) and os.path.isdir(source_path) else ''), dest_path,",
"str, follow_symlinks: Optional[bool] = False): \"\"\" Copy |source_path| to |dest_path|.",
"################################################################################ def copy(source_path: str, dest_path: str, follow_symlinks: Optional[bool] = False):",
"in ['http', 'https', 'ftp']: if path.startswith(prefix + '://'): return True",
"of directories, list of files) in the given directory. \"\"\"",
"overall_hash.hexdigest() def hash_file_contents(path): \"\"\" Return the hash of the file's",
"check_isvalid(path, fn_name) if os.path.isdir(path): raise path_error('%s got directory:' % (fn_name,),",
"%s' % path) def soft_link(source, path): \"\"\" Create a symbolic",
"the hashes. # This two-level hash is necessary so that",
"if the path is not absolute or normalized. Raise a",
"list of files) in the given directory. \"\"\" check_isdir(path, 'ls')",
"directory at or under the given path. Does not include",
"'file' LINK_PREFIX = 'link' def path_error(message, path): \"\"\" Raised when",
"ways: copy, make_directory, set_write_permissions, rename, remove \"\"\" import errno import",
"get_relative_path(path, file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode()) # Return a hash of the",
"give give write permissions to |path|, so that we can",
"subprocess.call(['chmod', '-R', 'u+w', path]) def rename(old_path, new_path): # Allow write",
"etc. ################################################################################ def getmtime(path): \"\"\" Like os.path.getmtime, but does not",
"root to path, which should be nested under root. \"\"\"",
"file_util from codalab.worker.file_util import get_path_size # Block sizes and canonical",
"follow symlinks Note: this only works in Linux. \"\"\" if",
"hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode()) else: contents_hash = hashlib.sha1(FILE_PREFIX.encode()) with open(path, 'rb') as",
"= 0x40000 FILE_PREFIX = 'file' LINK_PREFIX = 'link' def path_error(message,",
"problems when a target subpath is empty. \"\"\" return os.path.join(*[_f",
"the directory size for the hashed contents. return get_size(path) (directories,",
"at the given path. \"\"\" try: os.mkdir(path) except OSError as",
"data: break contents_hash.update(data) return contents_hash.hexdigest() ################################################################################ # Functions that modify",
"print_status='Copying %s to %s' % (source_path, dest_path), ) else: if",
"def hash_directory(path, dirs_and_files=None): \"\"\" Return the hash of the contents",
"path_error('not following symlinks', source_path) if not os.path.exists(source_path): raise path_error('does not",
"check that they are in normal form. ################################################################################ def normalize(path):",
"lexists instead of exists. if not os.path.lexists(path): raise path_error('%s got",
"directory in sorted(directories): relative_path = get_relative_path(path, directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) # Use",
"(source_path, dest_path), ) else: if not follow_symlinks and os.path.islink(source_path): raise",
"os.mkdir(path) except OSError as e: if e.errno != errno.EEXIST: raise",
"codalab.common import precondition, UsageError, parse_linked_bundle_url from codalab.lib import file_util from",
"else: return os.path.abspath(os.path.expanduser(path)) def check_isvalid(path, fn_name): \"\"\" Raise a PreconditionViolation",
"while True: data = file_handle.read(BLOCK_SIZE) if not data: break contents_hash.update(data)",
"+ ': ' + path) ################################################################################ # Functions to normalize",
"path: %s' % (fn_name, path)) # Broken symbolic links are",
"end of the list, which causes problems when a target",
"the followlinks parameter, because a) we don't want # to",
"'link' def path_error(message, path): \"\"\" Raised when a user-supplied path",
"just use the directory size for the hashed contents. return",
"symlinks to directories, but we should count them as files.",
"sys.stdin, dest, autoflush=False, print_status='Copying %s to %s' % (source_path, dest_path),",
"instead of exists. if not os.path.lexists(path): raise path_error('%s got non-existent",
"form: normalize, check_isvalid, check_isdir, check_isfile, path_is_url Functions to list directories",
"relative path from root to path, which should be nested",
"os.listdir(root): full_subpath = os.path.join(root, subpath) if os.path.islink(full_subpath) and os.path.isdir(full_subpath): files.append(full_subpath)",
"to move the directory and call get_hash again, you would",
"set_write_permissions(path): # Recursively give give write permissions to |path|, so",
"to |path|, so that we can operate # on it.",
"helpers for working with local filesystem paths. There are a",
"when a target subpath is empty. \"\"\" return os.path.join(*[_f for",
"import precondition, UsageError, parse_linked_bundle_url from codalab.lib import file_util from codalab.worker.file_util",
"the folder at the given path. This hash is independent",
"check_isdir(path, 'recursive_ls') (directories, files) = ([], []) for (root, _,",
"to read files to compute hashes, write results to stdout,",
"need write permissions if symlink subprocess.call(['chmod', '-R', 'u+w', path]) def",
"path == '-': return '/dev/stdin' elif path_is_url(path): return path else:",
"not os.path.exists(source_path): raise path_error('does not exist', source_path) command = [",
"returned in a \"canonical form\", without ~'s, .'s, ..'s. \"\"\"",
"getmtime, get_size, hash_directory, hash_file_contents Functions that modify that filesystem in",
"directories and to deal with subpaths of paths. ################################################################################ def",
"exception. \"\"\" return UsageError(message + ': ' + path) ################################################################################",
"you were to move the directory and call get_hash again,",
"between real and symlinked directories when computing the hash of",
"valid, then raise UsageError if the path is a file.",
"we don't want # to descend into directories and b)",
"contents_hash.update(os.readlink(path).encode()) else: contents_hash = hashlib.sha1(FILE_PREFIX.encode()) with open(path, 'rb') as file_handle:",
"'/dev/stdin': with open(dest_path, 'wb') as dest: file_util.copy( sys.stdin, dest, autoflush=False,",
"to stdout, etc. ################################################################################ def getmtime(path): \"\"\" Like os.path.getmtime, but",
"path of the location specified by the given path. This",
"it is a directory, file, or link. \"\"\" if parse_linked_bundle_url(path).uses_beam:",
"\"\"\" Raise a PreconditionViolation if the path is not absolute",
"it. if not os.path.islink(path): # Don't need write permissions if",
"safe_join, get_relative_path, ls, recursive_ls Functions to read files to compute",
"\"\"\" precondition(path.startswith(root), '%s is not under %s' % (path, root))",
"check that they are in normal form: normalize, check_isvalid, check_isdir,",
"e.errno != errno.EEXIST: raise check_isdir(path, 'make_directory') def set_write_permissions(path): # Recursively",
"'u+w', path]) def rename(old_path, new_path): # Allow write permissions, or",
"hash of a directory. This function will NOT descend into",
"Return a (list of directories, list of files) in the",
"codalab.worker.file_util import get_path_size # Block sizes and canonical strings used",
"descend into symlinked directories. \"\"\" check_isdir(path, 'recursive_ls') (directories, files) =",
"directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) # Use a similar two-level hashing scheme for all",
"paths if _f]) def get_relative_path(root, path): \"\"\" Return the relative",
"= get_relative_path(path, file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode()) # Return a hash of",
"not exist', source_path) command = [ 'rsync', '-pr%s' % ('L'",
"of these names, which could be generated # in multiple",
"to source at path. This is basically the same as",
"files to compute hashes, write results to stdout, etc: getmtime,",
"directories.append(file_name) return (directories, files) def recursive_ls(path): \"\"\" Return a (list",
"path. This path is returned in a \"canonical form\", without",
"not under %s' % (path, root)) return path[len(root) :] def",
"path) def path_is_url(path): if isinstance(path, str): for prefix in ['http',",
"up in an infinite loop if # we were to",
"sequence of paths but filter out any that are empty.",
"def ls(path): \"\"\" Return a (list of directories, list of",
"'hash_file called with relative path: %s' % (path,) precondition(os.path.isabs(path), message)",
"def copy(source_path: str, dest_path: str, follow_symlinks: Optional[bool] = False): \"\"\"",
"This hash is independent of the path itself - if",
"'wb') as dest: file_util.copy( sys.stdin, dest, autoflush=False, print_status='Copying %s to",
"and os.path.islink(source_path): raise path_error('not following symlinks', source_path) if not os.path.exists(source_path):",
"fn_name): \"\"\" Raise a PreconditionViolation if the path is not",
"methods provided here: Functions to normalize paths and check that",
"if # we were to pass that flag. Instead, we",
"%s' % (source_path, dest_path), ) else: if not follow_symlinks and",
"source_path == '/dev/stdin': with open(dest_path, 'wb') as dest: file_util.copy( sys.stdin,",
"specified by the given path. This path is returned in",
"to stdout, etc: getmtime, get_size, hash_directory, hash_file_contents Functions that modify",
"functionality EXCEPT at the end of the list, which causes",
"files) = ([], []) for (root, _, file_names) in os.walk(path):",
"directory:' % (fn_name,), path) def path_is_url(path): if isinstance(path, str): for",
"the directory and call get_hash again, you would get the",
"directory size for the hashed contents. return get_size(path) (directories, files)",
"all of its nested subdirectories. All paths returned are absolute.",
"recursive_ls(path): \"\"\" Return a (list of directories, list of files)",
"of methods provided here: Functions to normalize paths and check",
"hashes, write results to stdout, etc. ################################################################################ def getmtime(path): \"\"\"",
"Functions that modify that filesystem in controlled ways. ################################################################################ def",
"exists', dest_path) if source_path == '/dev/stdin': with open(dest_path, 'wb') as",
"root in os.walk: %s' % (root,) directories.append(root) for file_name in",
"path. Does not include symlinked files and directories. \"\"\" if",
"': ' + path) ################################################################################ # Functions to normalize paths",
"here: Functions to normalize paths and check that they are",
"hashing files. BLOCK_SIZE = 0x40000 FILE_PREFIX = 'file' LINK_PREFIX =",
"all files, but incorporate a # hash of both the",
"path, whether it is a directory, file, or link. \"\"\"",
"def soft_link(source, path): \"\"\" Create a symbolic link to source",
"get_relative_path(root, path): \"\"\" Return the relative path from root to",
"'Got relative root in os.walk: %s' % (root,) directories.append(root) for",
"import itertools import os import shutil import subprocess import sys",
"write results to stdout, etc: getmtime, get_size, hash_directory, hash_file_contents Functions",
"FILE_PREFIX = 'file' LINK_PREFIX = 'link' def path_error(message, path): \"\"\"",
"(fn_name,), path) def path_is_url(path): if isinstance(path, str): for prefix in",
"def recursive_ls(path): \"\"\" Return a (list of directories, list of",
"Functions to normalize paths and check that they are in",
"path): \"\"\" Raised when a user-supplied path causes an exception.",
"strings used when hashing files. BLOCK_SIZE = 0x40000 FILE_PREFIX =",
"a file. \"\"\" check_isvalid(path, fn_name) if not os.path.isdir(path): raise path_error('%s",
"real and symlinked directories when computing the hash of a",
"is independent of the path itself - if you were",
"compute a hash of the hashes. # This two-level hash",
"and os.path.isdir(full_subpath): files.append(full_subpath) return (directories, files) ################################################################################ # Functions to",
"def make_directory(path): \"\"\" Create the directory at the given path.",
"os.path.getmtime, but does not follow symlinks. \"\"\" return os.lstat(path).st_mtime def",
"in the list of files, even if they point to",
"[ 'rsync', '-pr%s' % ('L' if follow_symlinks else 'l'), source_path",
"return check_isvalid(path, 'remove') set_write_permissions(path) # Allow permissions if os.path.islink(path): os.unlink(path)",
"return overall_hash.hexdigest() def hash_file_contents(path): \"\"\" Return the hash of the",
"which could be generated # in multiple ways. directory_hash =",
"want # to descend into directories and b) we could",
"not os.path.isdir(path): return os.lstat(path).st_size dirs_and_files = dirs_and_files or recursive_ls(path) return",
"given path. This path is returned in a \"canonical form\",",
":] def ls(path): \"\"\" Return a (list of directories, list",
") else: if not follow_symlinks and os.path.islink(source_path): raise path_error('not following",
"contents. file_hash = hashlib.sha1() for file_name in sorted(files): relative_path =",
"infinite loop if # we were to pass that flag.",
"in an infinite loop if # we were to pass",
"and call get_hash again, you would get the same result.",
"a directory. This function will NOT descend into symlinked directories.",
"\"\"\" Return the relative path from root to path, which",
"to compute hashes, write results to stdout, etc. ################################################################################ def",
"of both the file name and contents. file_hash = hashlib.sha1()",
"os.remove(path) if os.path.exists(path): print('Failed to remove %s' % path) def",
"same as doing \"ln -s $source $path\" \"\"\" check_isvalid(source, 'soft_link')",
"and all of its nested subdirectories. All paths returned are",
"follow_symlinks and os.path.islink(source_path): raise path_error('not following symlinks', source_path) if not",
"read in blocks of size BLOCK_SIZE. \"\"\" message = 'hash_file",
"precondition(os.path.isabs(path), '%s got relative path: %s' % (fn_name, path)) #",
"rename(old_path, new_path): # Allow write permissions, or else the move",
"else the move will fail. set_write_permissions(old_path) subprocess.call(['mv', old_path, new_path]) def",
"%s' % (path, root)) return path[len(root) :] def ls(path): \"\"\"",
"'rsync', '-pr%s' % ('L' if follow_symlinks else 'l'), source_path +",
"not data: break contents_hash.update(data) return contents_hash.hexdigest() ################################################################################ # Functions that",
"os.path.islink(source_path) and os.path.isdir(source_path) else ''), dest_path, ] if subprocess.call(command) !=",
"However, we can't used the followlinks parameter, because a) we",
"os.unlink(path) elif os.path.isdir(path): try: shutil.rmtree(path) except shutil.Error: pass else: os.remove(path)",
"it possible to distinguish between real and symlinked directories when",
"return os.path.join(*[_f for _f in paths if _f]) def get_relative_path(root,",
"# Functions to read files to compute hashes, write results",
"os.lstat(path).st_mtime def get_size(path, dirs_and_files=None): \"\"\" Get the size (in bytes)",
"subpath is empty. \"\"\" return os.path.join(*[_f for _f in paths",
"symlinked files and directories. \"\"\" if parse_linked_bundle_url(path).uses_beam: return get_path_size(path) if",
"updated directory_hash with the directory names themselves, then # we'd",
"contains helpers for working with local filesystem paths. There are",
"os.walk(path): assert os.path.isabs(root), 'Got relative root in os.walk: %s' %",
"'l'), source_path + ('/' if not os.path.islink(source_path) and os.path.isdir(source_path) else",
"file at that path does not exist. \"\"\" precondition(os.path.isabs(path), '%s",
"################################################################################ # Functions to list directories and to deal with",
"will fail. set_write_permissions(old_path) subprocess.call(['mv', old_path, new_path]) def remove(path): \"\"\" Remove",
"exists. if not os.path.lexists(path): raise path_error('%s got non-existent path:' %",
"names, which could be generated # in multiple ways. directory_hash",
"you would get the same result. \"\"\" if parse_linked_bundle_url(path).uses_beam: #",
"import subprocess import sys from typing import Optional from codalab.common",
"compute hashes, write results to stdout, etc: getmtime, get_size, hash_directory,",
"safe_join(*paths): \"\"\" Join a sequence of paths but filter out",
"paths and check that they are in normal form. ################################################################################",
"\"\"\" precondition(os.path.isabs(path), '%s got relative path: %s' % (fn_name, path))",
"(path, root)) return path[len(root) :] def ls(path): \"\"\" Return a",
"\"\"\" Return a (list of directories, list of files) in",
"absolute path of the location specified by the given path.",
"All paths returned are absolute. Symlinks are returned in the",
"for all files, but incorporate a # hash of both",
"symlinked directories. \"\"\" check_isdir(path, 'recursive_ls') (directories, files) = ([], [])",
"(directories, files) ################################################################################ # Functions to read files to compute",
"non-directory:' % (fn_name,), path) def check_isfile(path, fn_name): \"\"\" Check that",
"the list, which causes problems when a target subpath is",
"new_path): # Allow write permissions, or else the move will",
"form. ################################################################################ def normalize(path): \"\"\" Return the absolute path of",
"will NOT descend into symlinked directories. \"\"\" check_isdir(path, 'recursive_ls') (directories,",
"\"canonical form\", without ~'s, .'s, ..'s. \"\"\" if path ==",
"get_relative_path, ls, recursive_ls Functions to read files to compute hashes,",
"that the path is valid, then raise UsageError if the",
"paths but filter out any that are empty. Used for",
"Create the directory at the given path. \"\"\" try: os.mkdir(path)",
"(root,) directories.append(root) for file_name in file_names: files.append(os.path.join(root, file_name)) # os.walk",
"files to compute hashes, write results to stdout, etc. ################################################################################",
"we'd be hashing the concatenation of these names, which could",
"of the path itself - if you were to move",
"# Functions that modify that filesystem in controlled ways. ################################################################################",
"% ('L' if follow_symlinks else 'l'), source_path + ('/' if",
"def rename(old_path, new_path): # Allow write permissions, or else the",
"full_subpath = os.path.join(root, subpath) if os.path.islink(full_subpath) and os.path.isdir(full_subpath): files.append(full_subpath) return",
"parse_linked_bundle_url(path).uses_beam: return get_path_size(path) if os.path.islink(path) or not os.path.isdir(path): return os.lstat(path).st_size",
"shutil import subprocess import sys from typing import Optional from",
"overall hash is unambiguous - # if we updated directory_hash",
"if parse_linked_bundle_url(path).uses_beam: return get_path_size(path) if os.path.islink(path) or not os.path.isdir(path): return",
"% (fn_name,), path) def check_isfile(path, fn_name): \"\"\" Check that the",
"in the given directory and all of its nested subdirectories.",
"make_directory(path): \"\"\" Create the directory at the given path. \"\"\"",
"the file at that path does not exist. \"\"\" precondition(os.path.isabs(path),",
"the move will fail. set_write_permissions(old_path) subprocess.call(['mv', old_path, new_path]) def remove(path):",
"check_isvalid(path, 'remove') set_write_permissions(path) # Allow permissions if os.path.islink(path): os.unlink(path) elif",
"with subpaths of paths: safe_join, get_relative_path, ls, recursive_ls Functions to",
"This path is returned in a \"canonical form\", without ~'s,",
"location specified by the given path. This path is returned",
"a \"canonical form\", without ~'s, .'s, ..'s. \"\"\" if path",
"str): for prefix in ['http', 'https', 'ftp']: if path.startswith(prefix +",
"% (root,) directories.append(root) for file_name in file_names: files.append(os.path.join(root, file_name)) #",
"in sorted(files): relative_path = get_relative_path(path, file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode()) # Return",
"list, which causes problems when a target subpath is empty.",
"'https', 'ftp']: if path.startswith(prefix + '://'): return True return False",
"'://'): return True return False ################################################################################ # Functions to list",
"modify that filesystem in controlled ways. ################################################################################ def copy(source_path: str,",
"return os.lstat(path).st_mtime def get_size(path, dirs_and_files=None): \"\"\" Get the size (in",
"relative_path = get_relative_path(path, directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) # Use a similar two-level",
"\"\"\" Return the hash of the file's contents, read in",
"relative path: %s' % (fn_name, path)) # Broken symbolic links",
"Like os.path.getmtime, but does not follow symlinks. \"\"\" return os.lstat(path).st_mtime",
"path): \"\"\" Return the relative path from root to path,",
"directory. \"\"\" check_isdir(path, 'ls') (directories, files) = ([], []) for",
"directory and all of its nested subdirectories. All paths returned",
"valid paths, so we use lexists instead of exists. if",
"shutil.rmtree(path) except shutil.Error: pass else: os.remove(path) if os.path.exists(path): print('Failed to",
"that flag. Instead, we handle symlinks here: for subpath in",
"directories. \"\"\" if parse_linked_bundle_url(path).uses_beam: return get_path_size(path) if os.path.islink(path) or not",
"recursive_ls(path) return sum(os.lstat(path).st_size for path in itertools.chain(*dirs_and_files)) def hash_directory(path, dirs_and_files=None):",
"empty. Used for targets. Note that os.path.join has this functionality",
"a few classes of methods provided here: Functions to normalize",
"follow_symlinks: Optional[bool] = False): \"\"\" Copy |source_path| to |dest_path|. Assume",
"This is basically the same as doing \"ln -s $source",
"a (list of directories, list of files) in the given",
"|follow_symlinks|: whether to follow symlinks Note: this only works in",
"dest_path, ] if subprocess.call(command) != 0: raise path_error('Unable to copy",
"root. \"\"\" precondition(path.startswith(root), '%s is not under %s' % (path,",
"to |dest_path|. Assume dest_path doesn't exist. |follow_symlinks|: whether to follow",
"new_path]) def remove(path): \"\"\" Remove the given path, whether it",
"two hashes. overall_hash = hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode()) return overall_hash.hexdigest() def hash_file_contents(path):",
"remove \"\"\" import errno import hashlib import itertools import os",
"% (path,) precondition(os.path.isabs(path), message) if os.path.islink(path): contents_hash = hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode())",
"size (in bytes) of the file or directory at or",
"subprocess.call(['mv', old_path, new_path]) def remove(path): \"\"\" Remove the given path,",
"return UsageError(message + ': ' + path) ################################################################################ # Functions",
"if we updated directory_hash with the directory names themselves, then",
"%s to %s' % (source_path, dest_path), ) else: if not",
"to remove %s' % path) def soft_link(source, path): \"\"\" Create",
"\"\"\" Join a sequence of paths but filter out any",
"that filesystem in controlled ways: copy, make_directory, set_write_permissions, rename, remove",
"to directories, but we should count them as files. #",
"if not os.path.exists(source_path): raise path_error('does not exist', source_path) command =",
"hash of the contents of the folder at the given",
"path.startswith(prefix + '://'): return True return False ################################################################################ # Functions",
"(fn_name, path)) # Broken symbolic links are valid paths, so",
"would get the same result. \"\"\" if parse_linked_bundle_url(path).uses_beam: # On",
"exist. |follow_symlinks|: whether to follow symlinks Note: this only works",
"'ls') (directories, files) = ([], []) for file_name in os.listdir(path):",
"dirs_and_files or recursive_ls(path) return sum(os.lstat(path).st_size for path in itertools.chain(*dirs_and_files)) def",
"of paths but filter out any that are empty. Used",
"False ################################################################################ # Functions to list directories and to deal",
"in os.walk(path): assert os.path.isabs(root), 'Got relative root in os.walk: %s'",
"link. \"\"\" if parse_linked_bundle_url(path).uses_beam: from apache_beam.io.filesystems import FileSystems if not",
"if you were to move the directory and call get_hash",
"the size (in bytes) of the file or directory at",
"% source_path, dest_path) def make_directory(path): \"\"\" Create the directory at",
"without ~'s, .'s, ..'s. \"\"\" if path == '-': return",
"not exist. \"\"\" precondition(os.path.isabs(path), '%s got relative path: %s' %",
"= ([], []) for (root, _, file_names) in os.walk(path): assert",
"directory_hash with the directory names themselves, then # we'd be",
"follow_symlinks else 'l'), source_path + ('/' if not os.path.islink(source_path) and",
"of files) in the given directory and all of its",
"os.path.islink(path): # Don't need write permissions if symlink subprocess.call(['chmod', '-R',",
"= hashlib.sha1() for file_name in sorted(files): relative_path = get_relative_path(path, file_name)",
"files) = ([], []) for file_name in os.listdir(path): if os.path.isfile(os.path.join(path,",
"os.listdir(path): if os.path.isfile(os.path.join(path, file_name)): files.append(file_name) else: directories.append(file_name) return (directories, files)",
"copy, make_directory, set_write_permissions, rename, remove \"\"\" import errno import hashlib",
"hash is independent of the path itself - if you",
"# This two-level hash is necessary so that the overall",
"copy(source_path: str, dest_path: str, follow_symlinks: Optional[bool] = False): \"\"\" Copy",
"sorted(files): relative_path = get_relative_path(path, file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode()) # Return a",
"\"\"\" return os.path.join(*[_f for _f in paths if _f]) def",
"# Functions to normalize paths and check that they are",
"causes problems when a target subpath is empty. \"\"\" return",
"'recursive_ls') (directories, files) = ([], []) for (root, _, file_names)",
"directories and b) we could end up in an infinite",
"here: for subpath in os.listdir(root): full_subpath = os.path.join(root, subpath) if",
"return os.lstat(path).st_size dirs_and_files = dirs_and_files or recursive_ls(path) return sum(os.lstat(path).st_size for",
"and symlinked directories when computing the hash of a directory.",
"sum(os.lstat(path).st_size for path in itertools.chain(*dirs_and_files)) def hash_directory(path, dirs_and_files=None): \"\"\" Return",
"files. BLOCK_SIZE = 0x40000 FILE_PREFIX = 'file' LINK_PREFIX = 'link'",
"typing import Optional from codalab.common import precondition, UsageError, parse_linked_bundle_url from",
"relative path: %s' % (path,) precondition(os.path.isabs(path), message) if os.path.islink(path): contents_hash",
"for targets. Note that os.path.join has this functionality EXCEPT at",
"message = 'hash_file called with relative path: %s' % (path,)",
"[]) for file_name in os.listdir(path): if os.path.isfile(os.path.join(path, file_name)): files.append(file_name) else:",
"be nested under root. \"\"\" precondition(path.startswith(root), '%s is not under",
"hash_directory(path, dirs_and_files=None): \"\"\" Return the hash of the contents of",
"import hashlib import itertools import os import shutil import subprocess",
"the absolute path of the location specified by the given",
"sizes and canonical strings used when hashing files. BLOCK_SIZE =",
"\"\"\" Create a symbolic link to source at path. This",
"files.append(os.path.join(root, file_name)) # os.walk ignores symlinks to directories, but we",
"paths and check that they are in normal form: normalize,",
"or recursive_ls(path) return sum(os.lstat(path).st_size for path in itertools.chain(*dirs_and_files)) def hash_directory(path,",
"flag. Instead, we handle symlinks here: for subpath in os.listdir(root):",
"os.path.islink(full_subpath) and os.path.isdir(full_subpath): files.append(full_subpath) return (directories, files) ################################################################################ # Functions",
"write permissions, or else the move will fail. set_write_permissions(old_path) subprocess.call(['mv',",
"os.lstat(path).st_size dirs_and_files = dirs_and_files or recursive_ls(path) return sum(os.lstat(path).st_size for path",
"directory and call get_hash again, you would get the same",
"file_names: files.append(os.path.join(root, file_name)) # os.walk ignores symlinks to directories, but",
"fn_name) if not os.path.isdir(path): raise path_error('%s got non-directory:' % (fn_name,),",
"and contents. file_hash = hashlib.sha1() for file_name in sorted(files): relative_path",
"link to source at path. This is basically the same",
"[]) for (root, _, file_names) in os.walk(path): assert os.path.isabs(root), 'Got",
"Used for targets. Note that os.path.join has this functionality EXCEPT",
"subprocess.call(command) != 0: raise path_error('Unable to copy %s to' %",
"permissions if symlink subprocess.call(['chmod', '-R', 'u+w', path]) def rename(old_path, new_path):",
"pass else: os.remove(path) if os.path.exists(path): print('Failed to remove %s' %",
"get_path_size(path) if os.path.islink(path) or not os.path.isdir(path): return os.lstat(path).st_size dirs_and_files =",
"normalize paths and check that they are in normal form:",
"and check that they are in normal form: normalize, check_isvalid,",
"the given path. This path is returned in a \"canonical",
"include symlinked files and directories. \"\"\" if parse_linked_bundle_url(path).uses_beam: return get_path_size(path)",
"path_is_url(path): return path else: return os.path.abspath(os.path.expanduser(path)) def check_isvalid(path, fn_name): \"\"\"",
"which should be nested under root. \"\"\" precondition(path.startswith(root), '%s is",
"is a file. \"\"\" check_isvalid(path, fn_name) if os.path.isdir(path): raise path_error('%s",
"path is a file. \"\"\" check_isvalid(path, fn_name) if not os.path.isdir(path):",
"precondition(path.startswith(root), '%s is not under %s' % (path, root)) return",
"names themselves, then # we'd be hashing the concatenation of",
"# in multiple ways. directory_hash = hashlib.sha1() for directory in",
"if e.errno != errno.EEXIST: raise check_isdir(path, 'make_directory') def set_write_permissions(path): #",
"filesystem in controlled ways. ################################################################################ def copy(source_path: str, dest_path: str,",
"permissions to |path|, so that we can operate # on",
"\"\"\" Check that the path is valid, then raise UsageError",
"if not data: break contents_hash.update(data) return contents_hash.hexdigest() ################################################################################ # Functions",
"hash_directory, hash_file_contents Functions that modify that filesystem in controlled ways:",
"to %s' % (source_path, dest_path), ) else: if not follow_symlinks",
"################################################################################ def safe_join(*paths): \"\"\" Join a sequence of paths but",
"errno.EEXIST: raise check_isdir(path, 'make_directory') def set_write_permissions(path): # Recursively give give",
"os.path.isdir(path): raise path_error('%s got non-directory:' % (fn_name,), path) def check_isfile(path,",
"is necessary so that the overall hash is unambiguous -",
"of paths. ################################################################################ def safe_join(*paths): \"\"\" Join a sequence of",
"Symlinks are returned in the list of files, even if",
"permissions, or else the move will fail. set_write_permissions(old_path) subprocess.call(['mv', old_path,",
"the same result. \"\"\" if parse_linked_bundle_url(path).uses_beam: # On Azure Blob",
"can operate # on it. if not os.path.islink(path): # Don't",
"~'s, .'s, ..'s. \"\"\" if path == '-': return '/dev/stdin'",
"results to stdout, etc. ################################################################################ def getmtime(path): \"\"\" Like os.path.getmtime,",
"file_name)) # os.walk ignores symlinks to directories, but we should",
"hashlib import itertools import os import shutil import subprocess import",
"This function will NOT descend into symlinked directories. \"\"\" check_isdir(path,",
"operate # on it. if not os.path.islink(path): # Don't need",
"to distinguish between real and symlinked directories when computing the",
"of paths: safe_join, get_relative_path, ls, recursive_ls Functions to read files",
"path does not exist. \"\"\" precondition(os.path.isabs(path), '%s got relative path:",
"# os.walk ignores symlinks to directories, but we should count",
"files) in the given directory. \"\"\" check_isdir(path, 'ls') (directories, files)",
"data = file_handle.read(BLOCK_SIZE) if not data: break contents_hash.update(data) return contents_hash.hexdigest()",
"not FileSystems.exists(path): FileSystems.delete([path]) return check_isvalid(path, 'remove') set_write_permissions(path) # Allow permissions",
"(in bytes) of the file or directory at or under",
"def set_write_permissions(path): # Recursively give give write permissions to |path|,",
"if not FileSystems.exists(path): FileSystems.delete([path]) return check_isvalid(path, 'remove') set_write_permissions(path) # Allow",
"contents_hash = hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode()) else: contents_hash = hashlib.sha1(FILE_PREFIX.encode()) with open(path,",
"else: if not follow_symlinks and os.path.islink(source_path): raise path_error('not following symlinks',",
"subpath in os.listdir(root): full_subpath = os.path.join(root, subpath) if os.path.islink(full_subpath) and",
"Check that the path is valid, then raise UsageError if",
"from codalab.common import precondition, UsageError, parse_linked_bundle_url from codalab.lib import file_util",
"stdout, etc. ################################################################################ def getmtime(path): \"\"\" Like os.path.getmtime, but does",
"and canonical strings used when hashing files. BLOCK_SIZE = 0x40000",
"check_isdir(path, fn_name): \"\"\" Check that the path is valid, then",
"of the contents of the folder at the given path.",
"form\", without ~'s, .'s, ..'s. \"\"\" if path == '-':",
"a UsageError if the file at that path does not",
"so we use lexists instead of exists. if not os.path.lexists(path):",
"path. This hash is independent of the path itself -",
"+ path) ################################################################################ # Functions to normalize paths and check",
"This two-level hash is necessary so that the overall hash",
"path. This is basically the same as doing \"ln -s",
"in itertools.chain(*dirs_and_files)) def hash_directory(path, dirs_and_files=None): \"\"\" Return the hash of",
"return os.path.abspath(os.path.expanduser(path)) def check_isvalid(path, fn_name): \"\"\" Raise a PreconditionViolation if",
"under %s' % (path, root)) return path[len(root) :] def ls(path):",
"in os.listdir(path): if os.path.isfile(os.path.join(path, file_name)): files.append(file_name) else: directories.append(file_name) return (directories,",
"of a directory. This function will NOT descend into symlinked",
"a sequence of paths but filter out any that are",
"is a directory, file, or link. \"\"\" if parse_linked_bundle_url(path).uses_beam: from",
"deal with subpaths of paths: safe_join, get_relative_path, ls, recursive_ls Functions",
"the given path. This hash is independent of the path",
"they are in normal form. ################################################################################ def normalize(path): \"\"\" Return",
"function will NOT descend into symlinked directories. \"\"\" check_isdir(path, 'recursive_ls')",
"symbolic links are valid paths, so we use lexists instead",
"file name and contents. file_hash = hashlib.sha1() for file_name in",
"out any that are empty. Used for targets. Note that",
"the hash of the file's contents, read in blocks of",
"hashlib.sha1(FILE_PREFIX.encode()) with open(path, 'rb') as file_handle: while True: data =",
"loop if # we were to pass that flag. Instead,",
"this only works in Linux. \"\"\" if os.path.exists(dest_path): raise path_error('already",
"Raise a UsageError if the file at that path does",
"path_error(message, path): \"\"\" Raised when a user-supplied path causes an",
"if os.path.islink(path): contents_hash = hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode()) else: contents_hash = hashlib.sha1(FILE_PREFIX.encode())",
"that they are in normal form. ################################################################################ def normalize(path): \"\"\"",
"pass that flag. Instead, we handle symlinks here: for subpath",
"for the hashed contents. return get_size(path) (directories, files) = dirs_and_files",
"import file_util from codalab.worker.file_util import get_path_size # Block sizes and",
"check_isvalid(path, fn_name): \"\"\" Raise a PreconditionViolation if the path is",
"dirs_and_files=None): \"\"\" Get the size (in bytes) of the file",
"directory_hash = hashlib.sha1() for directory in sorted(directories): relative_path = get_relative_path(path,",
"\"\"\" return os.lstat(path).st_mtime def get_size(path, dirs_and_files=None): \"\"\" Get the size",
"but incorporate a # hash of both the file name",
"absolute. Symlinks are returned in the list of files, even",
"def getmtime(path): \"\"\" Like os.path.getmtime, but does not follow symlinks.",
"are a few classes of methods provided here: Functions to",
"files) ################################################################################ # Functions to read files to compute hashes,",
"the list of files, even if they point to directories.",
"normalize paths and check that they are in normal form.",
"point to directories. This makes it possible to distinguish between",
"os.path.isfile(os.path.join(path, file_name)): files.append(file_name) else: directories.append(file_name) return (directories, files) def recursive_ls(path):",
"files, even if they point to directories. This makes it",
"source_path) if not os.path.exists(source_path): raise path_error('does not exist', source_path) command",
"\"\"\" if path == '-': return '/dev/stdin' elif path_is_url(path): return",
"path causes an exception. \"\"\" return UsageError(message + ': '",
"source_path) command = [ 'rsync', '-pr%s' % ('L' if follow_symlinks",
"PreconditionViolation if the path is not absolute or normalized. Raise",
"is unambiguous - # if we updated directory_hash with the",
"def get_relative_path(root, path): \"\"\" Return the relative path from root",
"\"\"\" Return the hash of the contents of the folder",
"were to move the directory and call get_hash again, you",
"itertools.chain(*dirs_and_files)) def hash_directory(path, dirs_and_files=None): \"\"\" Return the hash of the",
"dest_path) def make_directory(path): \"\"\" Create the directory at the given",
"call get_hash again, you would get the same result. \"\"\"",
"e: if e.errno != errno.EEXIST: raise check_isdir(path, 'make_directory') def set_write_permissions(path):",
"'/dev/stdin' elif path_is_url(path): return path else: return os.path.abspath(os.path.expanduser(path)) def check_isvalid(path,",
"ignores symlinks to directories, but we should count them as",
"hashing the concatenation of these names, which could be generated",
"recursive_ls Functions to read files to compute hashes, write results",
"def get_size(path, dirs_and_files=None): \"\"\" Get the size (in bytes) of",
"we were to pass that flag. Instead, we handle symlinks",
"_, file_names) in os.walk(path): assert os.path.isabs(root), 'Got relative root in",
"as e: if e.errno != errno.EEXIST: raise check_isdir(path, 'make_directory') def",
"get_relative_path(path, directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) # Use a similar two-level hashing scheme",
"autoflush=False, print_status='Copying %s to %s' % (source_path, dest_path), ) else:",
"os.path.join has this functionality EXCEPT at the end of the",
"|dest_path|. Assume dest_path doesn't exist. |follow_symlinks|: whether to follow symlinks",
"path): \"\"\" Create a symbolic link to source at path.",
"in os.walk: %s' % (root,) directories.append(root) for file_name in file_names:",
"permissions if os.path.islink(path): os.unlink(path) elif os.path.isdir(path): try: shutil.rmtree(path) except shutil.Error:",
"if os.path.isfile(os.path.join(path, file_name)): files.append(file_name) else: directories.append(file_name) return (directories, files) def",
"use lexists instead of exists. if not os.path.lexists(path): raise path_error('%s",
"import get_path_size # Block sizes and canonical strings used when",
"parse_linked_bundle_url from codalab.lib import file_util from codalab.worker.file_util import get_path_size #",
"['http', 'https', 'ftp']: if path.startswith(prefix + '://'): return True return",
"file_handle.read(BLOCK_SIZE) if not data: break contents_hash.update(data) return contents_hash.hexdigest() ################################################################################ #",
"whether it is a directory, file, or link. \"\"\" if",
"raise path_error('%s got non-directory:' % (fn_name,), path) def check_isfile(path, fn_name):",
"\"\"\" if parse_linked_bundle_url(path).uses_beam: return get_path_size(path) if os.path.islink(path) or not os.path.isdir(path):",
"] if subprocess.call(command) != 0: raise path_error('Unable to copy %s",
"Note: this only works in Linux. \"\"\" if os.path.exists(dest_path): raise",
"!= errno.EEXIST: raise check_isdir(path, 'make_directory') def set_write_permissions(path): # Recursively give",
"local filesystem paths. There are a few classes of methods",
"isinstance(path, str): for prefix in ['http', 'https', 'ftp']: if path.startswith(prefix",
"if follow_symlinks else 'l'), source_path + ('/' if not os.path.islink(source_path)",
"raise UsageError if the path is a file. \"\"\" check_isvalid(path,",
"the hash of the contents of the folder at the",
"hash of the hashes. # This two-level hash is necessary",
"os.walk ignores symlinks to directories, but we should count them",
"path is valid, then raise UsageError if the path is",
"that path does not exist. \"\"\" precondition(os.path.isabs(path), '%s got relative",
"called with relative path: %s' % (path,) precondition(os.path.isabs(path), message) if",
"if os.path.exists(dest_path): raise path_error('already exists', dest_path) if source_path == '/dev/stdin':",
"from apache_beam.io.filesystems import FileSystems if not FileSystems.exists(path): FileSystems.delete([path]) return check_isvalid(path,",
"to pass that flag. Instead, we handle symlinks here: for",
"handle symlinks here: for subpath in os.listdir(root): full_subpath = os.path.join(root,",
"to path, which should be nested under root. \"\"\" precondition(path.startswith(root),",
"they are in normal form: normalize, check_isvalid, check_isdir, check_isfile, path_is_url",
"Functions to read files to compute hashes, write results to",
"compute hashes, write results to stdout, etc. ################################################################################ def getmtime(path):",
"paths returned are absolute. Symlinks are returned in the list",
"are valid paths, so we use lexists instead of exists.",
"necessary so that the overall hash is unambiguous - #",
"%s' % (path,) precondition(os.path.isabs(path), message) if os.path.islink(path): contents_hash = hashlib.sha1(LINK_PREFIX.encode())",
"normalized. Raise a UsageError if the file at that path",
"followlinks parameter, because a) we don't want # to descend",
"= False): \"\"\" Copy |source_path| to |dest_path|. Assume dest_path doesn't",
"= [ 'rsync', '-pr%s' % ('L' if follow_symlinks else 'l'),",
"Recursively give give write permissions to |path|, so that we",
"move will fail. set_write_permissions(old_path) subprocess.call(['mv', old_path, new_path]) def remove(path): \"\"\"",
"provided here: Functions to normalize paths and check that they",
"if path == '-': return '/dev/stdin' elif path_is_url(path): return path",
"filter out any that are empty. Used for targets. Note",
"\"\"\" try: os.mkdir(path) except OSError as e: if e.errno !=",
"similar two-level hashing scheme for all files, but incorporate a",
"check_isvalid, check_isdir, check_isfile, path_is_url Functions to list directories and to",
"if source_path == '/dev/stdin': with open(dest_path, 'wb') as dest: file_util.copy(",
"files) in the given directory and all of its nested",
"Use a similar two-level hashing scheme for all files, but",
"apache_beam.io.filesystems import FileSystems if not FileSystems.exists(path): FileSystems.delete([path]) return check_isvalid(path, 'remove')",
"basically the same as doing \"ln -s $source $path\" \"\"\"",
".'s, ..'s. \"\"\" if path == '-': return '/dev/stdin' elif",
"we could end up in an infinite loop if #",
"both the file name and contents. file_hash = hashlib.sha1() for",
"directories, list of files) in the given directory and all",
"as files. # However, we can't used the followlinks parameter,",
"'rb') as file_handle: while True: data = file_handle.read(BLOCK_SIZE) if not",
"that modify that filesystem in controlled ways. ################################################################################ def copy(source_path:",
"(fn_name,), path) def check_isdir(path, fn_name): \"\"\" Check that the path",
"..'s. \"\"\" if path == '-': return '/dev/stdin' elif path_is_url(path):",
"of files, even if they point to directories. This makes",
"the file or directory at or under the given path.",
"and then compute a hash of the hashes. # This",
"Assume dest_path doesn't exist. |follow_symlinks|: whether to follow symlinks Note:",
"directories, but we should count them as files. # However,",
"|path|, so that we can operate # on it. if",
"raise check_isdir(path, 'make_directory') def set_write_permissions(path): # Recursively give give write",
"Block sizes and canonical strings used when hashing files. BLOCK_SIZE",
"at or under the given path. Does not include symlinked",
"the hash of a directory. This function will NOT descend",
"ways. ################################################################################ def copy(source_path: str, dest_path: str, follow_symlinks: Optional[bool] =",
"be generated # in multiple ways. directory_hash = hashlib.sha1() for",
"# if we updated directory_hash with the directory names themselves,",
"subpath) if os.path.islink(full_subpath) and os.path.isdir(full_subpath): files.append(full_subpath) return (directories, files) ################################################################################",
"os import shutil import subprocess import sys from typing import",
"move the directory and call get_hash again, you would get",
"the relative path from root to path, which should be",
"directories.append(root) for file_name in file_names: files.append(os.path.join(root, file_name)) # os.walk ignores",
"if _f]) def get_relative_path(root, path): \"\"\" Return the relative path",
"soft_link(source, path): \"\"\" Create a symbolic link to source at",
"file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode()) # Return a hash of the two",
"subdirectories. All paths returned are absolute. Symlinks are returned in",
"return '/dev/stdin' elif path_is_url(path): return path else: return os.path.abspath(os.path.expanduser(path)) def",
"directories when computing the hash of a directory. This function",
"\"\"\" Like os.path.getmtime, but does not follow symlinks. \"\"\" return",
"file_name in sorted(files): relative_path = get_relative_path(path, file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode()) #",
"target subpath is empty. \"\"\" return os.path.join(*[_f for _f in",
"then compute a hash of the hashes. # This two-level",
"normalize, check_isvalid, check_isdir, check_isfile, path_is_url Functions to list directories and",
"errno import hashlib import itertools import os import shutil import",
"Return the absolute path of the location specified by the",
"set_write_permissions(path) # Allow permissions if os.path.islink(path): os.unlink(path) elif os.path.isdir(path): try:",
"UsageError if the file at that path does not exist.",
"% path) def soft_link(source, path): \"\"\" Create a symbolic link",
"normal form: normalize, check_isvalid, check_isdir, check_isfile, path_is_url Functions to list",
"are absolute. Symlinks are returned in the list of files,",
"we use lexists instead of exists. if not os.path.lexists(path): raise",
"to list directories and to deal with subpaths of paths:",
"the end of the list, which causes problems when a",
"in normal form. ################################################################################ def normalize(path): \"\"\" Return the absolute",
"to directories. This makes it possible to distinguish between real",
"def path_error(message, path): \"\"\" Raised when a user-supplied path causes",
"not os.path.islink(source_path) and os.path.isdir(source_path) else ''), dest_path, ] if subprocess.call(command)",
"get_size, hash_directory, hash_file_contents Functions that modify that filesystem in controlled",
"= hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode()) else: contents_hash = hashlib.sha1(FILE_PREFIX.encode()) with open(path, 'rb')",
"hashlib.sha1() for file_name in sorted(files): relative_path = get_relative_path(path, file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode())",
"doesn't exist. |follow_symlinks|: whether to follow symlinks Note: this only",
"doing \"ln -s $source $path\" \"\"\" check_isvalid(source, 'soft_link') os.symlink(source, path)",
"or not os.path.isdir(path): return os.lstat(path).st_size dirs_and_files = dirs_and_files or recursive_ls(path)",
"- # if we updated directory_hash with the directory names",
"a user-supplied path causes an exception. \"\"\" return UsageError(message +",
"import sys from typing import Optional from codalab.common import precondition,",
"source_path, dest_path) def make_directory(path): \"\"\" Create the directory at the",
"open(path, 'rb') as file_handle: while True: data = file_handle.read(BLOCK_SIZE) if",
"unambiguous - # if we updated directory_hash with the directory",
"hashlib.sha1() for directory in sorted(directories): relative_path = get_relative_path(path, directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode())",
"Return a hash of the two hashes. overall_hash = hashlib.sha1(directory_hash.hexdigest().encode())",
"in the given directory. \"\"\" check_isdir(path, 'ls') (directories, files) =",
"then raise UsageError if the path is a file. \"\"\"",
"try: os.mkdir(path) except OSError as e: if e.errno != errno.EEXIST:",
"folder at the given path. This hash is independent of",
"directory names themselves, then # we'd be hashing the concatenation",
"hashing scheme for all files, but incorporate a # hash",
"raise path_error('does not exist', source_path) command = [ 'rsync', '-pr%s'",
"given path. \"\"\" try: os.mkdir(path) except OSError as e: if",
"file_hash.update(hash_file_contents(file_name).encode()) # Return a hash of the two hashes. overall_hash",
"to deal with subpaths of paths. ################################################################################ def safe_join(*paths): \"\"\"",
"\"\"\" if parse_linked_bundle_url(path).uses_beam: from apache_beam.io.filesystems import FileSystems if not FileSystems.exists(path):",
"FileSystems.delete([path]) return check_isvalid(path, 'remove') set_write_permissions(path) # Allow permissions if os.path.islink(path):",
"size BLOCK_SIZE. \"\"\" message = 'hash_file called with relative path:",
"the given directory and all of its nested subdirectories. All",
"or directory at or under the given path. Does not",
"contents, read in blocks of size BLOCK_SIZE. \"\"\" message =",
"paths: safe_join, get_relative_path, ls, recursive_ls Functions to read files to",
"message) if os.path.islink(path): contents_hash = hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode()) else: contents_hash =",
"write results to stdout, etc. ################################################################################ def getmtime(path): \"\"\" Like",
"of the list, which causes problems when a target subpath",
"be hashing the concatenation of these names, which could be",
"not os.path.isdir(path): raise path_error('%s got non-directory:' % (fn_name,), path) def",
"the concatenation of these names, which could be generated #",
"is a file. \"\"\" check_isvalid(path, fn_name) if not os.path.isdir(path): raise",
"\"\"\" Remove the given path, whether it is a directory,",
"(directories, files) = ([], []) for (root, _, file_names) in",
"# on it. if not os.path.islink(path): # Don't need write",
"################################################################################ # Functions to read files to compute hashes, write",
"a PreconditionViolation if the path is not absolute or normalized.",
"os.path.lexists(path): raise path_error('%s got non-existent path:' % (fn_name,), path) def",
"got non-directory:' % (fn_name,), path) def check_isfile(path, fn_name): \"\"\" Check",
"if they point to directories. This makes it possible to",
"This makes it possible to distinguish between real and symlinked",
"True: data = file_handle.read(BLOCK_SIZE) if not data: break contents_hash.update(data) return",
"%s to' % source_path, dest_path) def make_directory(path): \"\"\" Create the",
"possible to distinguish between real and symlinked directories when computing",
"open(dest_path, 'wb') as dest: file_util.copy( sys.stdin, dest, autoflush=False, print_status='Copying %s",
"os.path.islink(path): os.unlink(path) elif os.path.isdir(path): try: shutil.rmtree(path) except shutil.Error: pass else:",
"raise path_error('already exists', dest_path) if source_path == '/dev/stdin': with open(dest_path,",
"path. \"\"\" try: os.mkdir(path) except OSError as e: if e.errno",
"the same as doing \"ln -s $source $path\" \"\"\" check_isvalid(source,",
"are in normal form: normalize, check_isvalid, check_isdir, check_isfile, path_is_url Functions",
"elif path_is_url(path): return path else: return os.path.abspath(os.path.expanduser(path)) def check_isvalid(path, fn_name):",
"contents_hash.hexdigest() ################################################################################ # Functions that modify that filesystem in controlled",
"for file_name in sorted(files): relative_path = get_relative_path(path, file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode())",
"in sorted(directories): relative_path = get_relative_path(path, directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) # Use a",
"to deal with subpaths of paths: safe_join, get_relative_path, ls, recursive_ls",
"# we were to pass that flag. Instead, we handle",
"os.path.islink(source_path): raise path_error('not following symlinks', source_path) if not os.path.exists(source_path): raise",
"not follow_symlinks and os.path.islink(source_path): raise path_error('not following symlinks', source_path) if",
"% (path, root)) return path[len(root) :] def ls(path): \"\"\" Return",
"a hash of the two hashes. overall_hash = hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode())",
"directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) # Use a similar two-level hashing scheme for",
"in controlled ways. ################################################################################ def copy(source_path: str, dest_path: str, follow_symlinks:",
"if symlink subprocess.call(['chmod', '-R', 'u+w', path]) def rename(old_path, new_path): #",
"\"\"\" Raised when a user-supplied path causes an exception. \"\"\"",
"name and contents. file_hash = hashlib.sha1() for file_name in sorted(files):",
"if path.startswith(prefix + '://'): return True return False ################################################################################ #",
"\"\"\" check_isvalid(path, fn_name) if os.path.isdir(path): raise path_error('%s got directory:' %",
"contents_hash.update(data) return contents_hash.hexdigest() ################################################################################ # Functions that modify that filesystem",
"\"\"\" if os.path.exists(dest_path): raise path_error('already exists', dest_path) if source_path ==",
"working with local filesystem paths. There are a few classes",
"ls(path): \"\"\" Return a (list of directories, list of files)",
"directories and to deal with subpaths of paths: safe_join, get_relative_path,",
"subpaths of paths: safe_join, get_relative_path, ls, recursive_ls Functions to read",
"os.path.isdir(path): raise path_error('%s got directory:' % (fn_name,), path) def path_is_url(path):",
"def path_is_url(path): if isinstance(path, str): for prefix in ['http', 'https',",
"as dest: file_util.copy( sys.stdin, dest, autoflush=False, print_status='Copying %s to %s'",
"if os.path.islink(path): os.unlink(path) elif os.path.isdir(path): try: shutil.rmtree(path) except shutil.Error: pass",
"path is not absolute or normalized. Raise a UsageError if",
"def check_isvalid(path, fn_name): \"\"\" Raise a PreconditionViolation if the path",
"of the file's contents, read in blocks of size BLOCK_SIZE.",
"Return the hash of the contents of the folder at",
"|source_path| to |dest_path|. Assume dest_path doesn't exist. |follow_symlinks|: whether to",
"%s' % (root,) directories.append(root) for file_name in file_names: files.append(os.path.join(root, file_name))",
"empty. \"\"\" return os.path.join(*[_f for _f in paths if _f])",
"symbolic link to source at path. This is basically the",
"fn_name): \"\"\" Check that the path is valid, then raise",
"few classes of methods provided here: Functions to normalize paths",
"On Azure Blob Storage, we just use the directory size",
"does not follow symlinks. \"\"\" return os.lstat(path).st_mtime def get_size(path, dirs_and_files=None):",
"files. # However, we can't used the followlinks parameter, because",
"were to pass that flag. Instead, we handle symlinks here:",
"remove(path): \"\"\" Remove the given path, whether it is a",
"path, which should be nested under root. \"\"\" precondition(path.startswith(root), '%s",
"get_hash again, you would get the same result. \"\"\" if",
"# On Azure Blob Storage, we just use the directory",
"Don't need write permissions if symlink subprocess.call(['chmod', '-R', 'u+w', path])",
"%s' % (fn_name, path)) # Broken symbolic links are valid",
"or link. \"\"\" if parse_linked_bundle_url(path).uses_beam: from apache_beam.io.filesystems import FileSystems if",
"to normalize paths and check that they are in normal",
"- if you were to move the directory and call",
"in controlled ways: copy, make_directory, set_write_permissions, rename, remove \"\"\" import",
"the given path. Does not include symlinked files and directories.",
"an exception. \"\"\" return UsageError(message + ': ' + path)",
"' + path) ################################################################################ # Functions to normalize paths and",
"scheme for all files, but incorporate a # hash of",
"which causes problems when a target subpath is empty. \"\"\"",
"to follow symlinks Note: this only works in Linux. \"\"\"",
"get the same result. \"\"\" if parse_linked_bundle_url(path).uses_beam: # On Azure",
"bytes) of the file or directory at or under the",
"dest_path: str, follow_symlinks: Optional[bool] = False): \"\"\" Copy |source_path| to",
"(path,) precondition(os.path.isabs(path), message) if os.path.islink(path): contents_hash = hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode()) else:",
"# hash of both the file name and contents. file_hash",
"# Sort and then hash all directories and then compute",
"if os.path.islink(full_subpath) and os.path.isdir(full_subpath): files.append(full_subpath) return (directories, files) ################################################################################ #",
"# However, we can't used the followlinks parameter, because a)",
"for prefix in ['http', 'https', 'ftp']: if path.startswith(prefix + '://'):",
"if os.path.isdir(path): raise path_error('%s got directory:' % (fn_name,), path) def",
"used the followlinks parameter, because a) we don't want #",
"or normalized. Raise a UsageError if the file at that",
"when computing the hash of a directory. This function will",
"([], []) for (root, _, file_names) in os.walk(path): assert os.path.isabs(root),",
"computing the hash of a directory. This function will NOT",
"a similar two-level hashing scheme for all files, but incorporate",
"give write permissions to |path|, so that we can operate",
"if parse_linked_bundle_url(path).uses_beam: from apache_beam.io.filesystems import FileSystems if not FileSystems.exists(path): FileSystems.delete([path])",
"directories and then compute a hash of the hashes. #",
"directory at the given path. \"\"\" try: os.mkdir(path) except OSError",
"= get_relative_path(path, directory) directory_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) # Use a similar two-level hashing",
"if not os.path.lexists(path): raise path_error('%s got non-existent path:' % (fn_name,),",
"([], []) for file_name in os.listdir(path): if os.path.isfile(os.path.join(path, file_name)): files.append(file_name)",
"Sort and then hash all directories and then compute a",
"concatenation of these names, which could be generated # in",
"as file_handle: while True: data = file_handle.read(BLOCK_SIZE) if not data:",
"path) def check_isdir(path, fn_name): \"\"\" Check that the path is",
"exist. \"\"\" precondition(os.path.isabs(path), '%s got relative path: %s' % (fn_name,",
"non-existent path:' % (fn_name,), path) def check_isdir(path, fn_name): \"\"\" Check",
"(directories, files) = ([], []) for file_name in os.listdir(path): if",
"in paths if _f]) def get_relative_path(root, path): \"\"\" Return the",
"of files) in the given directory. \"\"\" check_isdir(path, 'ls') (directories,",
"itself - if you were to move the directory and",
"################################################################################ def normalize(path): \"\"\" Return the absolute path of the",
"= 'link' def path_error(message, path): \"\"\" Raised when a user-supplied",
"old_path, new_path]) def remove(path): \"\"\" Remove the given path, whether",
"subpaths of paths. ################################################################################ def safe_join(*paths): \"\"\" Join a sequence",
"path) def soft_link(source, path): \"\"\" Create a symbolic link to",
"check_isvalid(path, fn_name) if not os.path.isdir(path): raise path_error('%s got non-directory:' %",
"in normal form: normalize, check_isvalid, check_isdir, check_isfile, path_is_url Functions to",
"causes an exception. \"\"\" return UsageError(message + ': ' +",
"count them as files. # However, we can't used the",
"Get the size (in bytes) of the file or directory",
"the path is not absolute or normalized. Raise a UsageError",
"list of files) in the given directory and all of",
"in multiple ways. directory_hash = hashlib.sha1() for directory in sorted(directories):",
"if not os.path.islink(path): # Don't need write permissions if symlink",
"we just use the directory size for the hashed contents.",
"same result. \"\"\" if parse_linked_bundle_url(path).uses_beam: # On Azure Blob Storage,",
"% (source_path, dest_path), ) else: if not follow_symlinks and os.path.islink(source_path):",
"a target subpath is empty. \"\"\" return os.path.join(*[_f for _f",
"(list of directories, list of files) in the given directory",
"Allow write permissions, or else the move will fail. set_write_permissions(old_path)",
"\"\"\" path_util contains helpers for working with local filesystem paths.",
"path) def check_isfile(path, fn_name): \"\"\" Check that the path is",
"so that we can operate # on it. if not",
"\"\"\" import errno import hashlib import itertools import os import",
"when hashing files. BLOCK_SIZE = 0x40000 FILE_PREFIX = 'file' LINK_PREFIX",
"make_directory, set_write_permissions, rename, remove \"\"\" import errno import hashlib import",
"paths. ################################################################################ def safe_join(*paths): \"\"\" Join a sequence of paths",
"symlinked directories when computing the hash of a directory. This",
"filesystem in controlled ways: copy, make_directory, set_write_permissions, rename, remove \"\"\"",
"check_isdir(path, 'ls') (directories, files) = ([], []) for file_name in",
"root)) return path[len(root) :] def ls(path): \"\"\" Return a (list",
"only works in Linux. \"\"\" if os.path.exists(dest_path): raise path_error('already exists',",
"hashes, write results to stdout, etc: getmtime, get_size, hash_directory, hash_file_contents",
"distinguish between real and symlinked directories when computing the hash",
"Linux. \"\"\" if os.path.exists(dest_path): raise path_error('already exists', dest_path) if source_path",
"independent of the path itself - if you were to",
"= hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode()) return overall_hash.hexdigest() def hash_file_contents(path): \"\"\" Return the",
"and os.path.isdir(source_path) else ''), dest_path, ] if subprocess.call(command) != 0:",
"os.path.islink(path): contents_hash = hashlib.sha1(LINK_PREFIX.encode()) contents_hash.update(os.readlink(path).encode()) else: contents_hash = hashlib.sha1(FILE_PREFIX.encode()) with",
"list directories and to deal with subpaths of paths: safe_join,",
"path_error('%s got non-existent path:' % (fn_name,), path) def check_isdir(path, fn_name):",
"file. \"\"\" check_isvalid(path, fn_name) if os.path.isdir(path): raise path_error('%s got directory:'",
"at the end of the list, which causes problems when",
"for _f in paths if _f]) def get_relative_path(root, path): \"\"\"",
"Allow permissions if os.path.islink(path): os.unlink(path) elif os.path.isdir(path): try: shutil.rmtree(path) except",
"import shutil import subprocess import sys from typing import Optional",
"file_hash = hashlib.sha1() for file_name in sorted(files): relative_path = get_relative_path(path,",
"path else: return os.path.abspath(os.path.expanduser(path)) def check_isvalid(path, fn_name): \"\"\" Raise a",
"os.path.exists(source_path): raise path_error('does not exist', source_path) command = [ 'rsync',",
"path from root to path, which should be nested under",
"return get_path_size(path) if os.path.islink(path) or not os.path.isdir(path): return os.lstat(path).st_size dirs_and_files",
"Functions that modify that filesystem in controlled ways: copy, make_directory,",
"of the two hashes. overall_hash = hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode()) return overall_hash.hexdigest()",
"path_error('already exists', dest_path) if source_path == '/dev/stdin': with open(dest_path, 'wb')",
"any that are empty. Used for targets. Note that os.path.join",
"absolute or normalized. Raise a UsageError if the file at",
"parse_linked_bundle_url(path).uses_beam: from apache_beam.io.filesystems import FileSystems if not FileSystems.exists(path): FileSystems.delete([path]) return",
"paths. There are a few classes of methods provided here:",
"in blocks of size BLOCK_SIZE. \"\"\" message = 'hash_file called",
"links are valid paths, so we use lexists instead of",
"% (fn_name,), path) def check_isdir(path, fn_name): \"\"\" Check that the",
"that are empty. Used for targets. Note that os.path.join has",
"os.path.abspath(os.path.expanduser(path)) def check_isvalid(path, fn_name): \"\"\" Raise a PreconditionViolation if the",
"path is returned in a \"canonical form\", without ~'s, .'s,",
"for working with local filesystem paths. There are a few",
"+ '://'): return True return False ################################################################################ # Functions to",
"of directories, list of files) in the given directory and",
"file_names) in os.walk(path): assert os.path.isabs(root), 'Got relative root in os.walk:",
"def hash_file_contents(path): \"\"\" Return the hash of the file's contents,",
"os.path.join(root, subpath) if os.path.islink(full_subpath) and os.path.isdir(full_subpath): files.append(full_subpath) return (directories, files)",
"read files to compute hashes, write results to stdout, etc:",
"'-pr%s' % ('L' if follow_symlinks else 'l'), source_path + ('/'",
"check_isfile(path, fn_name): \"\"\" Check that the path is valid, then",
"symlinks. \"\"\" return os.lstat(path).st_mtime def get_size(path, dirs_and_files=None): \"\"\" Get the",
"is not under %s' % (path, root)) return path[len(root) :]",
"OSError as e: if e.errno != errno.EEXIST: raise check_isdir(path, 'make_directory')",
"the overall hash is unambiguous - # if we updated",
"print('Failed to remove %s' % path) def soft_link(source, path): \"\"\"",
"path)) # Broken symbolic links are valid paths, so we",
"Raised when a user-supplied path causes an exception. \"\"\" return",
"dest_path) if source_path == '/dev/stdin': with open(dest_path, 'wb') as dest:",
"BLOCK_SIZE = 0x40000 FILE_PREFIX = 'file' LINK_PREFIX = 'link' def",
"overall_hash.update(file_hash.hexdigest().encode()) return overall_hash.hexdigest() def hash_file_contents(path): \"\"\" Return the hash of",
"don't want # to descend into directories and b) we",
"precondition, UsageError, parse_linked_bundle_url from codalab.lib import file_util from codalab.worker.file_util import",
"Raise a PreconditionViolation if the path is not absolute or",
"BLOCK_SIZE. \"\"\" message = 'hash_file called with relative path: %s'",
"we can't used the followlinks parameter, because a) we don't",
"def remove(path): \"\"\" Remove the given path, whether it is",
"is valid, then raise UsageError if the path is a",
"the directory at the given path. \"\"\" try: os.mkdir(path) except",
"multiple ways. directory_hash = hashlib.sha1() for directory in sorted(directories): relative_path",
"'remove') set_write_permissions(path) # Allow permissions if os.path.islink(path): os.unlink(path) elif os.path.isdir(path):",
"are returned in the list of files, even if they",
"we can operate # on it. if not os.path.islink(path): #",
"file_util.copy( sys.stdin, dest, autoflush=False, print_status='Copying %s to %s' % (source_path,",
"nested under root. \"\"\" precondition(path.startswith(root), '%s is not under %s'",
"= 'hash_file called with relative path: %s' % (path,) precondition(os.path.isabs(path),",
"dirs_and_files=None): \"\"\" Return the hash of the contents of the",
"should count them as files. # However, we can't used",
"path itself - if you were to move the directory",
"= hashlib.sha1(FILE_PREFIX.encode()) with open(path, 'rb') as file_handle: while True: data",
"hash all directories and then compute a hash of the",
"contents. return get_size(path) (directories, files) = dirs_and_files or recursive_ls(path) #",
"the directory names themselves, then # we'd be hashing the",
"returned are absolute. Symlinks are returned in the list of",
"import os import shutil import subprocess import sys from typing",
"os.path.exists(path): print('Failed to remove %s' % path) def soft_link(source, path):",
"Instead, we handle symlinks here: for subpath in os.listdir(root): full_subpath",
"hashed contents. return get_size(path) (directories, files) = dirs_and_files or recursive_ls(path)",
"itertools import os import shutil import subprocess import sys from",
"of the folder at the given path. This hash is",
"given path. Does not include symlinked files and directories. \"\"\"",
"(directories, files) def recursive_ls(path): \"\"\" Return a (list of directories,",
"given path, whether it is a directory, file, or link.",
"remove %s' % path) def soft_link(source, path): \"\"\" Create a",
"got directory:' % (fn_name,), path) def path_is_url(path): if isinstance(path, str):",
"0: raise path_error('Unable to copy %s to' % source_path, dest_path)",
"path_error('%s got directory:' % (fn_name,), path) def path_is_url(path): if isinstance(path,",
"path]) def rename(old_path, new_path): # Allow write permissions, or else",
"to list directories and to deal with subpaths of paths.",
"that filesystem in controlled ways. ################################################################################ def copy(source_path: str, dest_path:",
"with open(path, 'rb') as file_handle: while True: data = file_handle.read(BLOCK_SIZE)",
"os.path.isdir(path): try: shutil.rmtree(path) except shutil.Error: pass else: os.remove(path) if os.path.exists(path):",
"into symlinked directories. \"\"\" check_isdir(path, 'recursive_ls') (directories, files) = ([],",
"when a user-supplied path causes an exception. \"\"\" return UsageError(message",
"paths, so we use lexists instead of exists. if not",
"break contents_hash.update(data) return contents_hash.hexdigest() ################################################################################ # Functions that modify that",
"'make_directory') def set_write_permissions(path): # Recursively give give write permissions to",
"# Broken symbolic links are valid paths, so we use",
"os.path.islink(path) or not os.path.isdir(path): return os.lstat(path).st_size dirs_and_files = dirs_and_files or",
"is empty. \"\"\" return os.path.join(*[_f for _f in paths if",
"Broken symbolic links are valid paths, so we use lexists",
"then hash all directories and then compute a hash of",
"path_error('does not exist', source_path) command = [ 'rsync', '-pr%s' %",
"write permissions if symlink subprocess.call(['chmod', '-R', 'u+w', path]) def rename(old_path,",
"incorporate a # hash of both the file name and",
"os.path.isabs(root), 'Got relative root in os.walk: %s' % (root,) directories.append(root)",
"else: contents_hash = hashlib.sha1(FILE_PREFIX.encode()) with open(path, 'rb') as file_handle: while",
"that os.path.join has this functionality EXCEPT at the end of",
"Optional[bool] = False): \"\"\" Copy |source_path| to |dest_path|. Assume dest_path",
"themselves, then # we'd be hashing the concatenation of these",
"symlink subprocess.call(['chmod', '-R', 'u+w', path]) def rename(old_path, new_path): # Allow",
"return path else: return os.path.abspath(os.path.expanduser(path)) def check_isvalid(path, fn_name): \"\"\" Raise",
"again, you would get the same result. \"\"\" if parse_linked_bundle_url(path).uses_beam:",
"copy %s to' % source_path, dest_path) def make_directory(path): \"\"\" Create",
"path_error('%s got non-directory:' % (fn_name,), path) def check_isfile(path, fn_name): \"\"\"",
"not os.path.lexists(path): raise path_error('%s got non-existent path:' % (fn_name,), path)",
"generated # in multiple ways. directory_hash = hashlib.sha1() for directory",
"== '-': return '/dev/stdin' elif path_is_url(path): return path else: return",
"FileSystems.exists(path): FileSystems.delete([path]) return check_isvalid(path, 'remove') set_write_permissions(path) # Allow permissions if",
"= file_handle.read(BLOCK_SIZE) if not data: break contents_hash.update(data) return contents_hash.hexdigest() ################################################################################",
"!= 0: raise path_error('Unable to copy %s to' % source_path,",
"Does not include symlinked files and directories. \"\"\" if parse_linked_bundle_url(path).uses_beam:",
"('/' if not os.path.islink(source_path) and os.path.isdir(source_path) else ''), dest_path, ]",
"def check_isfile(path, fn_name): \"\"\" Check that the path is valid,",
"if not os.path.islink(source_path) and os.path.isdir(source_path) else ''), dest_path, ] if",
"if os.path.islink(path) or not os.path.isdir(path): return os.lstat(path).st_size dirs_and_files = dirs_and_files",
"an infinite loop if # we were to pass that",
"elif os.path.isdir(path): try: shutil.rmtree(path) except shutil.Error: pass else: os.remove(path) if",
"normal form. ################################################################################ def normalize(path): \"\"\" Return the absolute path",
"dest_path doesn't exist. |follow_symlinks|: whether to follow symlinks Note: this",
"classes of methods provided here: Functions to normalize paths and",
"(root, _, file_names) in os.walk(path): assert os.path.isabs(root), 'Got relative root",
"hash_file_contents Functions that modify that filesystem in controlled ways: copy,",
"except shutil.Error: pass else: os.remove(path) if os.path.exists(path): print('Failed to remove",
"# to descend into directories and b) we could end",
"from codalab.lib import file_util from codalab.worker.file_util import get_path_size # Block",
"for path in itertools.chain(*dirs_and_files)) def hash_directory(path, dirs_and_files=None): \"\"\" Return the",
"from root to path, which should be nested under root.",
"\"\"\" message = 'hash_file called with relative path: %s' %",
"on it. if not os.path.islink(path): # Don't need write permissions",
"except OSError as e: if e.errno != errno.EEXIST: raise check_isdir(path,",
"of exists. if not os.path.lexists(path): raise path_error('%s got non-existent path:'",
"the two hashes. overall_hash = hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode()) return overall_hash.hexdigest() def",
"in a \"canonical form\", without ~'s, .'s, ..'s. \"\"\" if",
"NOT descend into symlinked directories. \"\"\" check_isdir(path, 'recursive_ls') (directories, files)",
"source_path + ('/' if not os.path.islink(source_path) and os.path.isdir(source_path) else ''),",
"makes it possible to distinguish between real and symlinked directories",
"= hashlib.sha1() for directory in sorted(directories): relative_path = get_relative_path(path, directory)",
"file_name in os.listdir(path): if os.path.isfile(os.path.join(path, file_name)): files.append(file_name) else: directories.append(file_name) return",
"LINK_PREFIX = 'link' def path_error(message, path): \"\"\" Raised when a",
"command = [ 'rsync', '-pr%s' % ('L' if follow_symlinks else",
"get_path_size # Block sizes and canonical strings used when hashing",
"or else the move will fail. set_write_permissions(old_path) subprocess.call(['mv', old_path, new_path])",
"b) we could end up in an infinite loop if",
"of size BLOCK_SIZE. \"\"\" message = 'hash_file called with relative",
"set_write_permissions, rename, remove \"\"\" import errno import hashlib import itertools",
"and b) we could end up in an infinite loop",
"not os.path.islink(path): # Don't need write permissions if symlink subprocess.call(['chmod',",
"rename, remove \"\"\" import errno import hashlib import itertools import",
"directory, file, or link. \"\"\" if parse_linked_bundle_url(path).uses_beam: from apache_beam.io.filesystems import",
"are in normal form. ################################################################################ def normalize(path): \"\"\" Return the",
"of its nested subdirectories. All paths returned are absolute. Symlinks",
"\"\"\" check_isvalid(path, fn_name) if not os.path.isdir(path): raise path_error('%s got non-directory:'",
"from typing import Optional from codalab.common import precondition, UsageError, parse_linked_bundle_url",
"file_name in file_names: files.append(os.path.join(root, file_name)) # os.walk ignores symlinks to",
"size for the hashed contents. return get_size(path) (directories, files) =",
"UsageError, parse_linked_bundle_url from codalab.lib import file_util from codalab.worker.file_util import get_path_size",
"def check_isdir(path, fn_name): \"\"\" Check that the path is valid,",
"return True return False ################################################################################ # Functions to list directories",
"a hash of the hashes. # This two-level hash is",
"the path is a file. \"\"\" check_isvalid(path, fn_name) if os.path.isdir(path):",
"at that path does not exist. \"\"\" precondition(os.path.isabs(path), '%s got",
"os.path.join(*[_f for _f in paths if _f]) def get_relative_path(root, path):",
"files.append(file_name) else: directories.append(file_name) return (directories, files) def recursive_ls(path): \"\"\" Return",
"in os.listdir(root): full_subpath = os.path.join(root, subpath) if os.path.islink(full_subpath) and os.path.isdir(full_subpath):",
"files) = dirs_and_files or recursive_ls(path) # Sort and then hash",
"could be generated # in multiple ways. directory_hash = hashlib.sha1()",
"works in Linux. \"\"\" if os.path.exists(dest_path): raise path_error('already exists', dest_path)",
"and check that they are in normal form. ################################################################################ def",
"not include symlinked files and directories. \"\"\" if parse_linked_bundle_url(path).uses_beam: return",
"got relative path: %s' % (fn_name, path)) # Broken symbolic",
"so that the overall hash is unambiguous - # if",
"to copy %s to' % source_path, dest_path) def make_directory(path): \"\"\"",
"return get_size(path) (directories, files) = dirs_and_files or recursive_ls(path) # Sort",
"directory. This function will NOT descend into symlinked directories. \"\"\"",
"os.path.isdir(full_subpath): files.append(full_subpath) return (directories, files) ################################################################################ # Functions to read",
"relative_path = get_relative_path(path, file_name) file_hash.update(hashlib.sha1(relative_path.encode()).hexdigest().encode()) file_hash.update(hash_file_contents(file_name).encode()) # Return a hash",
"import Optional from codalab.common import precondition, UsageError, parse_linked_bundle_url from codalab.lib",
"True return False ################################################################################ # Functions to list directories and",
"return path[len(root) :] def ls(path): \"\"\" Return a (list of",
"if isinstance(path, str): for prefix in ['http', 'https', 'ftp']: if",
"EXCEPT at the end of the list, which causes problems",
"\"\"\" Return the absolute path of the location specified by",
"for file_name in file_names: files.append(os.path.join(root, file_name)) # os.walk ignores symlinks",
"'%s is not under %s' % (path, root)) return path[len(root)",
"Functions to list directories and to deal with subpaths of",
"(list of directories, list of files) in the given directory.",
"parse_linked_bundle_url(path).uses_beam: # On Azure Blob Storage, we just use the",
"the file's contents, read in blocks of size BLOCK_SIZE. \"\"\"",
"'%s got relative path: %s' % (fn_name, path)) # Broken",
"file_handle: while True: data = file_handle.read(BLOCK_SIZE) if not data: break",
"os.path.exists(dest_path): raise path_error('already exists', dest_path) if source_path == '/dev/stdin': with",
"Return the relative path from root to path, which should",
"a) we don't want # to descend into directories and",
"and to deal with subpaths of paths: safe_join, get_relative_path, ls,",
"(directories, files) = dirs_and_files or recursive_ls(path) # Sort and then",
"dirs_and_files or recursive_ls(path) # Sort and then hash all directories",
"end up in an infinite loop if # we were",
"os.path.isdir(source_path) else ''), dest_path, ] if subprocess.call(command) != 0: raise",
"a directory, file, or link. \"\"\" if parse_linked_bundle_url(path).uses_beam: from apache_beam.io.filesystems",
"if os.path.exists(path): print('Failed to remove %s' % path) def soft_link(source,",
"return False ################################################################################ # Functions to list directories and to",
"even if they point to directories. This makes it possible",
"blocks of size BLOCK_SIZE. \"\"\" message = 'hash_file called with",
"# Use a similar two-level hashing scheme for all files,",
"by the given path. This path is returned in a",
"files, but incorporate a # hash of both the file",
"with the directory names themselves, then # we'd be hashing",
"that the overall hash is unambiguous - # if we",
"with open(dest_path, 'wb') as dest: file_util.copy( sys.stdin, dest, autoflush=False, print_status='Copying",
"hash of the two hashes. overall_hash = hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode()) return",
"# Don't need write permissions if symlink subprocess.call(['chmod', '-R', 'u+w',",
"'-': return '/dev/stdin' elif path_is_url(path): return path else: return os.path.abspath(os.path.expanduser(path))",
"given directory. \"\"\" check_isdir(path, 'ls') (directories, files) = ([], [])",
"a # hash of both the file name and contents.",
"# Block sizes and canonical strings used when hashing files.",
"path_is_url(path): if isinstance(path, str): for prefix in ['http', 'https', 'ftp']:",
"set_write_permissions(old_path) subprocess.call(['mv', old_path, new_path]) def remove(path): \"\"\" Remove the given",
"_f]) def get_relative_path(root, path): \"\"\" Return the relative path from",
"hash_file_contents(path): \"\"\" Return the hash of the file's contents, read",
"can't used the followlinks parameter, because a) we don't want",
"this functionality EXCEPT at the end of the list, which",
"path[len(root) :] def ls(path): \"\"\" Return a (list of directories,",
"the given path. \"\"\" try: os.mkdir(path) except OSError as e:",
"Storage, we just use the directory size for the hashed",
"# we'd be hashing the concatenation of these names, which",
"# Functions to list directories and to deal with subpaths",
"whether to follow symlinks Note: this only works in Linux.",
"raise path_error('%s got non-existent path:' % (fn_name,), path) def check_isdir(path,",
"the given directory. \"\"\" check_isdir(path, 'ls') (directories, files) = ([],",
"under the given path. Does not include symlinked files and",
"then # we'd be hashing the concatenation of these names,",
"Optional from codalab.common import precondition, UsageError, parse_linked_bundle_url from codalab.lib import",
"assert os.path.isabs(root), 'Got relative root in os.walk: %s' % (root,)",
"path_error('Unable to copy %s to' % source_path, dest_path) def make_directory(path):",
"return (directories, files) ################################################################################ # Functions to read files to",
"if the path is a file. \"\"\" check_isvalid(path, fn_name) if",
"we handle symlinks here: for subpath in os.listdir(root): full_subpath =",
"to compute hashes, write results to stdout, etc: getmtime, get_size,",
"symlinks here: for subpath in os.listdir(root): full_subpath = os.path.join(root, subpath)",
"(fn_name,), path) def check_isfile(path, fn_name): \"\"\" Check that the path",
"get_size(path, dirs_and_files=None): \"\"\" Get the size (in bytes) of the",
"exist', source_path) command = [ 'rsync', '-pr%s' % ('L' if",
"parameter, because a) we don't want # to descend into",
"% (fn_name, path)) # Broken symbolic links are valid paths,",
"into directories and b) we could end up in an",
"= 'file' LINK_PREFIX = 'link' def path_error(message, path): \"\"\" Raised",
"file or directory at or under the given path. Does",
"controlled ways: copy, make_directory, set_write_permissions, rename, remove \"\"\" import errno",
"that modify that filesystem in controlled ways: copy, make_directory, set_write_permissions,",
"filesystem paths. There are a few classes of methods provided",
"get_size(path) (directories, files) = dirs_and_files or recursive_ls(path) # Sort and",
"= dirs_and_files or recursive_ls(path) # Sort and then hash all",
"# Return a hash of the two hashes. overall_hash =",
"in file_names: files.append(os.path.join(root, file_name)) # os.walk ignores symlinks to directories,",
"canonical strings used when hashing files. BLOCK_SIZE = 0x40000 FILE_PREFIX",
"use the directory size for the hashed contents. return get_size(path)",
"\"\"\" check_isdir(path, 'ls') (directories, files) = ([], []) for file_name",
"two-level hashing scheme for all files, but incorporate a #",
"hash of both the file name and contents. file_hash =",
"dest_path), ) else: if not follow_symlinks and os.path.islink(source_path): raise path_error('not",
"given directory and all of its nested subdirectories. All paths",
"following symlinks', source_path) if not os.path.exists(source_path): raise path_error('does not exist',",
"shutil.Error: pass else: os.remove(path) if os.path.exists(path): print('Failed to remove %s'",
"of the location specified by the given path. This path",
"# Allow permissions if os.path.islink(path): os.unlink(path) elif os.path.isdir(path): try: shutil.rmtree(path)",
"hash of the file's contents, read in blocks of size",
"files) def recursive_ls(path): \"\"\" Return a (list of directories, list",
"Azure Blob Storage, we just use the directory size for",
"at path. This is basically the same as doing \"ln",
"path is a file. \"\"\" check_isvalid(path, fn_name) if os.path.isdir(path): raise",
"% (fn_name,), path) def path_is_url(path): if isinstance(path, str): for prefix",
"file's contents, read in blocks of size BLOCK_SIZE. \"\"\" message",
"################################################################################ def getmtime(path): \"\"\" Like os.path.getmtime, but does not follow",
"them as files. # However, we can't used the followlinks",
"dirs_and_files = dirs_and_files or recursive_ls(path) return sum(os.lstat(path).st_size for path in",
"UsageError if the path is a file. \"\"\" check_isvalid(path, fn_name)",
"with subpaths of paths. ################################################################################ def safe_join(*paths): \"\"\" Join a",
"the contents of the folder at the given path. This",
"normalize(path): \"\"\" Return the absolute path of the location specified",
"if subprocess.call(command) != 0: raise path_error('Unable to copy %s to'",
"dest, autoflush=False, print_status='Copying %s to %s' % (source_path, dest_path), )",
"else ''), dest_path, ] if subprocess.call(command) != 0: raise path_error('Unable",
"or recursive_ls(path) # Sort and then hash all directories and",
"from codalab.worker.file_util import get_path_size # Block sizes and canonical strings",
"hash is necessary so that the overall hash is unambiguous",
"Note that os.path.join has this functionality EXCEPT at the end",
"we should count them as files. # However, we can't",
"There are a few classes of methods provided here: Functions",
"with local filesystem paths. There are a few classes of",
"codalab.lib import file_util from codalab.worker.file_util import get_path_size # Block sizes",
"directories, list of files) in the given directory. \"\"\" check_isdir(path,",
"return contents_hash.hexdigest() ################################################################################ # Functions that modify that filesystem in",
"Remove the given path, whether it is a directory, file,",
"FileSystems if not FileSystems.exists(path): FileSystems.delete([path]) return check_isvalid(path, 'remove') set_write_permissions(path) #",
"used when hashing files. BLOCK_SIZE = 0x40000 FILE_PREFIX = 'file'",
"has this functionality EXCEPT at the end of the list,",
"deal with subpaths of paths. ################################################################################ def safe_join(*paths): \"\"\" Join",
"file, or link. \"\"\" if parse_linked_bundle_url(path).uses_beam: from apache_beam.io.filesystems import FileSystems",
"if parse_linked_bundle_url(path).uses_beam: # On Azure Blob Storage, we just use",
"two-level hash is necessary so that the overall hash is",
"== '/dev/stdin': with open(dest_path, 'wb') as dest: file_util.copy( sys.stdin, dest,",
"import errno import hashlib import itertools import os import shutil",
"getmtime(path): \"\"\" Like os.path.getmtime, but does not follow symlinks. \"\"\"",
"and directories. \"\"\" if parse_linked_bundle_url(path).uses_beam: return get_path_size(path) if os.path.islink(path) or",
"''), dest_path, ] if subprocess.call(command) != 0: raise path_error('Unable to",
"\"\"\" Create the directory at the given path. \"\"\" try:",
"= dirs_and_files or recursive_ls(path) return sum(os.lstat(path).st_size for path in itertools.chain(*dirs_and_files))",
"hashlib.sha1(directory_hash.hexdigest().encode()) overall_hash.update(file_hash.hexdigest().encode()) return overall_hash.hexdigest() def hash_file_contents(path): \"\"\" Return the hash",
"\"\"\" return UsageError(message + ': ' + path) ################################################################################ #",
"not absolute or normalized. Raise a UsageError if the file",
"is returned in a \"canonical form\", without ~'s, .'s, ..'s.",
"raise path_error('Unable to copy %s to' % source_path, dest_path) def",
"write permissions to |path|, so that we can operate #",
"user-supplied path causes an exception. \"\"\" return UsageError(message + ':",
"that we can operate # on it. if not os.path.islink(path):",
"the path itself - if you were to move the",
"else: directories.append(file_name) return (directories, files) def recursive_ls(path): \"\"\" Return a",
"the path is a file. \"\"\" check_isvalid(path, fn_name) if not",
"does not exist. \"\"\" precondition(os.path.isabs(path), '%s got relative path: %s'",
"ways. directory_hash = hashlib.sha1() for directory in sorted(directories): relative_path =",
"# Allow write permissions, or else the move will fail.",
"check_isfile, path_is_url Functions to list directories and to deal with",
"directories. \"\"\" check_isdir(path, 'recursive_ls') (directories, files) = ([], []) for",
"\"\"\" check_isdir(path, 'recursive_ls') (directories, files) = ([], []) for (root,",
"its nested subdirectories. All paths returned are absolute. Symlinks are",
"should be nested under root. \"\"\" precondition(path.startswith(root), '%s is not",
"but does not follow symlinks. \"\"\" return os.lstat(path).st_mtime def get_size(path,",
"\"\"\" Copy |source_path| to |dest_path|. Assume dest_path doesn't exist. |follow_symlinks|:",
"# Recursively give give write permissions to |path|, so that",
"files and directories. \"\"\" if parse_linked_bundle_url(path).uses_beam: return get_path_size(path) if os.path.islink(path)",
"for file_name in os.listdir(path): if os.path.isfile(os.path.join(path, file_name)): files.append(file_name) else: directories.append(file_name)",
"<filename>codalab/lib/path_util.py \"\"\" path_util contains helpers for working with local filesystem"
] |
[
"ds_l_realinv HAC standard errors, bandwidth 4 (Bartlett kernel) coefficient std.",
"smsdia import statsmodels.stats.outliers_influence as oi def compare_ftest(contrast_res, other, decimal=(5,4)): assert_almost_equal(contrast_res.fvalue,",
"with p-value = P(F(1,198) > 5.24895) = 0.023 #heteroscedasticity White",
"s: s}) lev.dtype.names = names res = res_ols #for easier",
"1959:2-2009:3 (T = 202) Dependent variable: scaled uhat^2 coefficient std.",
"-27.665860 -36.294434 3.036851 -42.282972 - -30.305896 2009:1 -70.239280 -44.018178 4.007017",
"restriction - Null hypothesis: restriction is acceptable Test statistic: F(2,",
"= -0.108136 coefficient std. error t-ratio p-value ------------------------------------------------------------- const -9.50990",
"4: Cochrane-Orcutt, using observations 1959:3-2009:3 (T = 201) Dependent variable:",
"#print np.max(np.abs(lev['leverage'] - infl.hat_matrix_diag)) #print np.max(np.abs(lev['influence'] - infl.influence)) #just added",
"################ with OLS, HAC errors #Model 5: OLS, using observations",
"\"F\"] lm2_acorr4 = [4.771043, 0.312, 4, \"chi2\"] acorr_ljungbox4 = [5.23587,",
"Test statistic: LM = 7.30776 with p-value = P(Chi-square(4) >",
"of common factor restriction Test statistic: F(2, 195) = 0.426391,",
"LM test for autocorrelation up to order 4 - Null",
"0.4040 realint_1 0.00410778 0.0512274 0.08019 0.9362 Explained sum of squares",
"4.37422 0.328787 13.30 2.62e-029 *** realint_1 -0.613997 0.293619 -2.091 0.0378",
"Variance Inflation Factors Minimum possible value = 1.0 Values >",
"alpha(1) 0.176114 0.0714698 2.464 0.0146 ** alpha(2) -0.0488339 0.0724981 -0.6736",
"221.0475), f_pvalue = (\"P-value(F)\", 3.56e-51), resid_acf1 = (\"rho\", -0.003481), dw",
"8.078897 4.483669 1.315876 1.888819 - 7.078520 Forecast evaluation statistics Mean",
"d2['realint'][:-1].values], prepend=False) mod1 = GLSAR(g_inv, exogg, 1) res1 = mod1.iterative_fit(5)",
"(T = 202) Dependent variable: uhat coefficient std. error t-ratio",
"endogd = np.diff(d['realinv']) exogd = add_constant(np.c_[np.diff(d['realgdp'].values), d['realint'][:-1].values]) endogg = gs_l_realinv",
"with p-value = P(Chi-square(2) > 7.52477) = 0.0232283 LM test",
"22799.68), mse_resid_sqrt = (\"S.E. of regression\", 10.70380), rsquared = (\"R-squared\",",
"autolag=None) sm_arch = smsdia.het_arch(res.resid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=5) assert_almost_equal(sm_arch[1], arch_4[1],",
"3) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=7)",
"-*- coding: utf-8 -*- \"\"\"Tests of GLSAR and diagnostics against",
"/ 114.571 = 208.528 [p-value 1.47e-049] #LM-test autocorrelation Breusch-Godfrey test",
"#for logs: dropping 70 nan or incomplete observations, T=133 #(res_ols.model.exog",
"95% CONFIDENCE INTERVAL #for confidence interval t(199, 0.025) = 1.972",
"uhat^2 (Koenker robust variant) coefficient std. error t-ratio p-value ------------------------------------------------------------",
"assert_almost_equal(res.bse, partable[:,1], 3) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf,",
"T=133 #(res_ols.model.exog <=0).any(1).sum() = 69 ?not 70 linear_squares = [7.52477,",
"= names res = res_ols #for easier copying cov_hac =",
"(\"Schwarz criterion\", 1543.875), hqic = (\"Hannan-Quinn\", 1537.966), resid_acf1 = (\"rho\",",
"3.2 changed behavior if np.isnan(lev[-1]['f1']): lev = np.genfromtxt(fpath, skip_header=3, skip_footer=2,",
"1537.966 rho -0.107341 Durbin-Watson 2.213805 QLR test for structural break",
"HCx #assert_almost_equal(res2.fvalue, result_gretl_g1['fvalue'][1], decimal=0) #FAIL #assert_approx_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], significant=1) #FAIL #assert_almost_equal(res.durbin_watson,",
"break - Null hypothesis: no structural break Test statistic: max",
"realint_1 -0.579253 0.268009 -2.161 0.0319 ** Statistics based on the",
"sum of squares = 2.60403 Test statistic: LM = 1.302014,",
"0.430953, 2, \"chi2\"] #for logs: dropping 70 nan or incomplete",
"Null hypothesis: no autocorrelation Test statistic: LMF = 1.17928 with",
"lag coefficient assert_almost_equal(res.model.rho, rho, decimal=3) #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse,",
"2.946312 -22.987904 - -11.367905 2008:4 -27.665860 -36.294434 3.036851 -42.282972 -",
"Mean dependent var 3.257395 S.D. dependent var 18.73915 Sum squared",
"0.321197, 4, 195, \"F\"] lm2_acorr4 = [4.771043, 0.312, 4, \"chi2\"]",
"in [1,2]] infl = oi.OLSInfluence(res_ols) #print np.max(np.abs(lev['DFFITS'] - infl.dffits[0])) #print",
"0.676978 F(2, 199) = 23891.3 / 114.571 = 208.528 [p-value",
"test, low decimal in Gretl output, assert_almost_equal(lev['residual'], res.resid, decimal=3) assert_almost_equal(lev['DFFITS'],",
"1.427414 -15.099640 - -9.470044 2009:3 8.078897 4.483669 1.315876 1.888819 -",
"= 13.1897 with p-value = 0.00424384 Test for ARCH of",
"the rho-differenced data: result_gretl_g1 = dict( endog_mean = (\"Mean dependent",
"squared resid\", 22530.90), mse_resid_sqrt = (\"S.E. of regression\", 10.66735), rsquared",
"X'X: 1-norm = 6862.0664 Determinant = 1.0296049e+009 Reciprocal condition number",
"** ds_l_realinv_1 -0.108892 0.0715042 -1.523 0.1294 ds_l_realgdp_1 0.660443 0.390372 1.692",
"*** realint_1 -6.93102 6.95607 -0.9964 0.3203 sq_ds_l_realg 4.12054 0.684920 6.016",
"no change in parameters Test statistic: Harvey-Collier t(198) = 0.494432",
"1.17709, -8.055, 7.17e-014, -11.8029, -7.16049], # *** [4.37422, 0.328787, 13.30,",
"Root Mean Squared Error 14.785 Mean Absolute Error 12.646 Mean",
"104.920 21.5848 4.861 2.39e-06 *** ds_l_realgdp -29.7040 6.24983 -4.753 3.88e-06",
"alpha(0) 97.0386 20.3234 4.775 3.56e-06 *** alpha(1) 0.176114 0.0714698 2.464",
"import statsmodels.stats.outliers_influence as oi def compare_ftest(contrast_res, other, decimal=(5,4)): assert_almost_equal(contrast_res.fvalue, other[0],",
"LM = 7.30776 with p-value = P(Chi-square(4) > 7.30776) =",
"/ res4.params - 1), 0.03) assert_array_less(res4.ssr, res1.ssr) assert_array_less(np.abs(res4.bse / res1.bse)",
"ssr from statsmodels.datasets import macrodata d2 = macrodata.load_pandas().data g_gdp =",
"-43.867 Theil's U 0.4365 Bias proportion, UM 0.06394 Regression proportion,",
"np.array([ [-9.50990, 0.990456, -9.602, 3.65e-018, -11.4631, -7.55670], # *** [",
"3.94837e-005, 2] #tests res = res_g1 #with rho from Gretl",
"skip_footer=2, converters={0:lambda s: s}) lev.dtype.names = names res = res_ols",
"close to lag=1, and smaller ssr from statsmodels.datasets import macrodata",
"4.09) Non-linearity test (logs) - Null hypothesis: relationship is linear",
"gretl #assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=7) #FAIL #assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid),",
"1.68351 with p-value = P(Chi-square(2) > 1.68351) = 0.430953 Non-linearity",
"Performing iterative calculation of rho... ITER RHO ESS 1 -0.10734",
"- -30.305896 2009:1 -70.239280 -44.018178 4.007017 -51.919841 - -36.116516 2009:2",
"rho, decimal=3) #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 3) assert_almost_equal(res.tvalues,",
"ARCH of order 4 coefficient std. error t-ratio p-value --------------------------------------------------------",
"0.430953 Non-linearity test (squares) - Null hypothesis: relationship is linear",
"INTERVAL partable = np.array([ [-9.50990, 0.990456, -9.602, 3.65e-018, -11.4631, -7.55670],",
"-1.454 0.1475 uhat_2 -0.00898483 0.0742817 -0.1210 0.9039 uhat_3 0.0837332 0.0735015",
"-27.024588 -12.284842 10.798554 -33.579120 - 9.009436 2009:3 8.078897 4.483669 10.784377",
"Test statistic: LM = 1.68351 with p-value = P(Chi-square(2) >",
"= (\"Hannan-Quinn\", 1537.966), resid_acf1 = (\"rho\", -0.107341), dw = (\"Durbin-Watson\",",
"decimal=decimal[1]) assert_equal(contrast_res.df_num, other[2]) assert_equal(contrast_res.df_denom, other[3]) assert_equal(\"f\", other[4]) class TestGLSARGretl: def",
"of the HCx #assert_almost_equal(res2.fvalue, result_gretl_g1['fvalue'][1], decimal=0) #FAIL #assert_approx_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], significant=1)",
"fpath = os.path.join(cur_dir, 'results/leverage_influence_ols_nostars.txt') lev = np.genfromtxt(fpath, skip_header=3, skip_footer=1, converters={0:lambda",
"var\", 3.113973), endog_std = (\"S.D. dependent var\", 18.67447), ssr =",
"statsmodels.tools.tools import add_constant from statsmodels.datasets import macrodata import statsmodels.stats.sandwich_covariance as",
"'date residual leverage influence DFFITS'.split() cur_dir = os.path.abspath(os.path.dirname(__file__)) fpath =",
"4.37040 0.208146 21.00 2.93e-052 *** realint_1 -0.579253 0.268009 -2.161 0.0319",
"= P(Chi-square(4) > 4.77104) = 0.312 Ljung-Box Q' = 5.23587,",
"0.328787, 13.30, 2.62e-029, 3.72587, 5.02258], #*** [-0.613997, 0.293619, -2.091, 0.0378,",
"199)\", 90.79971), f_pvalue = (\"P-value(F)\", 9.53e-29), llf = (\"Log-likelihood\", -763.9752),",
"0.0378, -1.19300, -0.0349939]]) # ** result_gretl_g1 = dict( endog_mean =",
"F = 7.268492, with p-value = P(F(1,198) > 7.26849) =",
"between variable j and the other independent variables Properties of",
"assert_almost_equal(bse_hac, partable[:,1], 5) #TODO assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=4)",
"present Test statistic: LM = 3.43473 with p-value = P(Chi-square(4)",
"** result_gretl_g1 = dict( endog_mean = (\"Mean dependent var\", 3.257395),",
"p-value = P(Chi-square(4) > 7.30776) = 0.120491: ''' ''' Variance",
"= 0.321 Alternative statistic: TR^2 = 4.771043, with p-value =",
"any of the HCx #assert_almost_equal(res2.fvalue, result_gretl_g1['fvalue'][1], decimal=0) #FAIL #assert_approx_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1],",
"sum of squares = 33174.2 Test statistic: LM = 0.709924,",
"error 95% interval 2008:3 -7.134492 -17.177905 11.101892 -39.070353 - 4.714544",
"statsmodels.stats.diagnostic as smsdia import statsmodels.stats.outliers_influence as oi def compare_ftest(contrast_res, other,",
"#simple diff, not growthrate, I want heteroscedasticity later for testing",
"5) #TODO assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=4) #not in",
"trying any of the HCx #assert_almost_equal(res2.fvalue, result_gretl_g1['fvalue'][1], decimal=0) #FAIL #assert_approx_equal(res.f_pvalue,",
"95% confidence intervals, t(199, 0.025) = 1.972 Obs ds_l_realinv prediction",
"> 0.709924) = 0.701200 ########## forecast #forecast mean y For",
"0.120491: ''' ''' Variance Inflation Factors Minimum possible value =",
"mod1.iterative_fit(5) mod4 = GLSAR(g_inv, exogg, 4) res4 = mod4.iterative_fit(10) assert_array_less(np.abs(res1.params",
"#sm_arch = smsdia.acorr_lm(res.resid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.resid, nlags=4) assert_almost_equal(sm_arch[0],",
"4) res4 = mod4.iterative_fit(10) assert_array_less(np.abs(res1.params / res4.params - 1), 0.03)",
"= 0.321197 CUSUM test for parameter stability - Null hypothesis:",
"*** ds_l_realgdp -29.7040 6.24983 -4.753 3.88e-06 *** realint_1 -6.93102 6.95607",
"exogd = add_constant(np.c_[np.diff(d['realgdp'].values), d['realint'][:-1].values]) endogg = gs_l_realinv exogg = add_constant(np.c_[gs_l_realgdp,",
"= (\"rho\", -0.107341), dw = (\"Durbin-Watson\", 2.213805)) linear_logs = [1.68351,",
"decimal=(6,5)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(6,5)) linear_sq =",
"macrodata.load_pandas().data g_gdp = 400*np.diff(np.log(d2['realgdp'].values)) g_inv = 400*np.diff(np.log(d2['realinv'].values)) exogg = add_constant(np.c_[g_gdp,",
"p-value = 0.653468 ''' ################ with OLS, HAC errors #Model",
"= np.array([ [-9.48167, 1.17709, -8.055, 7.17e-014, -11.8029, -7.16049], # ***",
"* realint_2 0.0769695 0.341527 0.2254 0.8219 Sum of squared residuals",
"#TODO assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=4) #not in gretl",
"t(199, 0.025) = 1.972 partable = np.array([ [-9.48167, 1.17709, -8.055,",
"3, 196, \"maxF\"] #TODO check this, max at 2001:4 break_chow",
"stability - Null hypothesis: no change in parameters Test statistic:",
"= P(Chi-square(4) > 7.30776) = 0.120491 Test of common factor",
"reset_2, decimal=(6,5)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(6,5)) linear_sq",
"if __name__ == '__main__': t = TestGLSARGretl() t.test_all() ''' Model",
"== '__main__': t = TestGLSARGretl() t.test_all() ''' Model 5: OLS,",
"lev = np.genfromtxt(fpath, skip_header=3, skip_footer=1, converters={0:lambda s: s}) #either numpy",
"202) Dependent variable: uhat coefficient std. error t-ratio p-value ------------------------------------------------------------",
"g #d = g.load('5-1') #growth rates gs_l_realinv = 400 *",
"#not available cond_1norm = 5984.0525 determinant = 7.1087467e+008 reciprocal_condition_number =",
"skip_footer=1, converters={0:lambda s: s}) #either numpy 1.6 or python 3.2",
"assert_equal(\"f\", other[4]) class TestGLSARGretl: def test_all(self): d = macrodata.load_pandas().data #import",
"coefficient std. error t-ratio p-value ------------------------------------------------------------- const 104.920 21.5848 4.861",
"0.5014 alpha(3) -0.0705413 0.0737058 -0.9571 0.3397 alpha(4) 0.0384531 0.0725763 0.5298",
"error t-ratio p-value ------------------------------------------------------------- const 104.920 21.5848 4.861 2.39e-06 ***",
"using observations 1959:2-2009:3 (T = 202) Dependent variable: uhat coefficient",
"rsquared = (\"R-squared\", 0.676978), rsquared_adj = (\"Adjusted R-squared\", 0.673731), fvalue",
"-11.4631, -7.55670], # *** [ 4.37040, 0.208146, 21.00, 2.93e-052, 3.95993,",
"hypothesis: relationship is linear Test statistic: LM = 1.68351 with",
"as g #d = g.load('5-1') #growth rates gs_l_realinv = 400",
"autocorrelation up to order 4 OLS, using observations 1959:2-2009:3 (T",
"Sum of squares df Mean square Regression 47782.7 2 23891.3",
"data: result_gretl_g1 = dict( endog_mean = (\"Mean dependent var\", 3.113973),",
"0.653468 ''' ################ with OLS, HAC errors #Model 5: OLS,",
"smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=1) assert_almost_equal(sm_arch[1], arch_4[1], decimal=2) ''' Performing",
"against Gretl Created on Thu Feb 02 21:15:47 2012 Author:",
"4 OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable:",
"std. error t-ratio p-value ------------------------------------------------------------- const -9.50990 0.990456 -9.602 3.65e-018",
"0.023, 1, 198, \"f\"] #not available cond_1norm = 5984.0525 determinant",
"determinant = 1.0296049e+009 reciprocal_condition_number = 0.013819244 #Chi-square(2): test-statistic, pvalue, df",
"observations 1959:2-2009:3 (T = 202) #Dependent variable: ds_l_realinv #HAC standard",
"with p-value = P(Chi-square(4) > 7.30776) = 0.120491: ''' '''",
"** #Statistics based on the rho-differenced data: result_gretl_g1 = dict(",
"of regression\", 10.70380), rsquared = (\"R-squared\", 0.676978), rsquared_adj = (\"Adjusted",
"in files break_qlr = [3.01985, 0.1, 3, 196, \"maxF\"] #TODO",
"0.673710 F(2, 198) 221.0475 P-value(F) 3.56e-51 rho -0.003481 Durbin-Watson 1.993858",
"realint_1 -0.613997 0.293619 -2.091 0.0378 ** Mean dependent var 3.257395",
"2008:4 -27.665860 -36.294434 3.036851 -42.282972 - -30.305896 2009:1 -70.239280 -44.018178",
"(\"P-value(F)\", 3.56e-51), resid_acf1 = (\"rho\", -0.003481), dw = (\"Durbin-Watson\", 1.993858))",
"k) for k in [1,2]] infl = oi.OLSInfluence(res_ols) #print np.max(np.abs(lev['DFFITS']",
"4 - Null hypothesis: no autocorrelation Test statistic: LMF =",
"nan or incomplete observations, T=133 #(res_ols.model.exog <=0).any(1).sum() = 69 ?not",
"''' ''' Test for ARCH of order 4 coefficient std.",
"P-value(F) 3.56e-51 rho -0.003481 Durbin-Watson 1.993858 ''' ''' RESET test",
"INTERVAL #for confidence interval t(199, 0.025) = 1.972 partable =",
"p-value = P(Chi-square(4) > 3.43473) = 0.487871: #ANOVA Analysis of",
"-6.93102 6.95607 -0.9964 0.3203 sq_ds_l_realg 4.12054 0.684920 6.016 8.62e-09 ***",
"S.D. dependent var 18.73915 Sum squared resid 22799.68 S.E. of",
"determinant = 7.1087467e+008 reciprocal_condition_number = 0.013826504 vif = [1.001, 1.001]",
"regression 10.66735 R-squared 0.676973 Adjusted R-squared 0.673710 F(2, 198) 221.0475",
"1.6 or python 3.2 changed behavior if np.isnan(lev[-1]['f1']): lev =",
"sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=4) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6)",
"Mean Error -3.7387 Mean Squared Error 218.61 Root Mean Squared",
"11.429236 -66.556135 - -21.480222 2009:2 -27.024588 -12.284842 10.798554 -33.579120 -",
"UR 0.13557 Disturbance proportion, UD 0.80049 #forecast actual y For",
"#LM-test autocorrelation Breusch-Godfrey test for autocorrelation up to order 4",
"3.65e-018, -11.4631, -7.55670], # *** [ 4.37040, 0.208146, 21.00, 2.93e-052,",
"as smsdia import statsmodels.stats.outliers_influence as oi def compare_ftest(contrast_res, other, decimal=(5,4)):",
"-0.107341), dw = (\"Durbin-Watson\", 2.213805)) linear_logs = [1.68351, 0.430953, 2,",
"= 6862.0664 determinant = 1.0296049e+009 reciprocal_condition_number = 0.013819244 #Chi-square(2): test-statistic,",
"= P(F(1,198) > 7.26849) = 0.00762 RESET test for specification",
"2, \"chi2\"] #TODO: not available het_breusch_pagan_konker = [0.709924, 0.701200, 2,",
"0.0232283, 2, \"chi2\"] #Autocorrelation, Breusch-Godfrey test for autocorrelation up to",
"het_breusch_pagan_konker[1], decimal=6) hw = smsdia.het_white(res.resid, res.model.exog) assert_almost_equal(hw[:2], het_white[:2], 6) #arch",
"# -*- coding: utf-8 -*- \"\"\"Tests of GLSAR and diagnostics",
"Null hypothesis: no ARCH effect is present Test statistic: LM",
"\"t\"] #stats.t.sf(0.494432, 198)*2 #see cusum results in files break_qlr =",
"OLS, using observations 1959:2-2009:3 (T = 202) #Dependent variable: ds_l_realinv",
"** Mean dependent var 3.257395 S.D. dependent var 18.73915 Sum",
"11.101892 -39.070353 - 4.714544 2008:4 -27.665860 -36.294434 11.126262 -58.234939 -",
"present Test statistic: LM = 7.30776 with p-value = P(Chi-square(4)",
"R-squared 0.673710 F(2, 198) 221.0475 P-value(F) 3.56e-51 rho -0.003481 Durbin-Watson",
"6.95607 -0.9964 0.3203 sq_ds_l_realg 4.12054 0.684920 6.016 8.62e-09 *** X2_X3",
"res1.ssr) assert_array_less(np.abs(res4.bse / res1.bse) - 1, 0.015) assert_array_less(np.abs((res4.fittedvalues / res1.fittedvalues",
"in Gretl output, assert_almost_equal(lev['residual'], res.resid, decimal=3) assert_almost_equal(lev['DFFITS'], infl.dffits[0], decimal=3) assert_almost_equal(lev['leverage'],",
"LM = 0.709924, with p-value = P(Chi-square(2) > 0.709924) =",
"0.4924 0.6230 ds_l_realgdp -3.64704 4.36075 -0.8363 0.4040 realint_1 0.463643 5.78202",
"-29.7040 6.24983 -4.753 3.88e-06 *** realint_1 -6.93102 6.95607 -0.9964 0.3203",
"#sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0],",
"res1.fittedvalues - 1).mean()), 0.015) assert_equal(len(mod4.rho), 4) if __name__ == '__main__':",
"P(F(4,195) > 1.17928) = 0.321197 CUSUM test for parameter stability",
"a collinearity problem ds_l_realgdp 1.002 realint_1 1.002 VIF(j) = 1/(1",
"for parameter stability - Null hypothesis: no change in parameters",
"errors, bandwidth 4 (Bartlett kernel) coefficient std. error t-ratio p-value",
"available het_breusch_pagan_konker = [0.709924, 0.701200, 2, \"chi2\"] reset_2_3 = [5.219019,",
"\"chi2\"] het_breusch_pagan = [1.302014, 0.521520, 2, \"chi2\"] #TODO: not available",
"= 0.621549 Chow test for structural break at observation 1984:1",
"= (\"Sum squared resid\", 22799.68), mse_resid_sqrt = (\"S.E. of regression\",",
"regression\", 10.70380), rsquared = (\"R-squared\", 0.676978), rsquared_adj = (\"Adjusted R-squared\",",
"#tests res = res_g2 #with estimated rho #estimated lag coefficient",
"std. error t-ratio p-value ------------------------------------------------------------- const -9.48167 1.17709 -8.055 7.17e-014",
"= [0.494432, 0.621549, 198, \"t\"] #stats.t.sf(0.494432, 198)*2 #see cusum results",
"0.06006 0.9522 ds_l_realgdp -0.0456010 0.217377 -0.2098 0.8341 realint_1 0.0511769 0.293136",
"rho... ITER RHO ESS 1 -0.10734 22530.9 2 -0.10814 22530.9",
"var\", 18.67447), ssr = (\"Sum squared resid\", 22530.90), mse_resid_sqrt =",
"= 1.302014, with p-value = P(Chi-square(2) > 1.302014) = 0.521520",
"lev = np.genfromtxt(fpath, skip_header=3, skip_footer=2, converters={0:lambda s: s}) lev.dtype.names =",
"smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=4)",
"Error -7.1173 Mean Absolute Percentage Error -43.867 Theil's U 0.4365",
"(\"Durbin-Watson\", 2.213805)) linear_logs = [1.68351, 0.430953, 2, \"chi2\"] #for logs:",
"available cond_1norm = 5984.0525 determinant = 7.1087467e+008 reciprocal_condition_number = 0.013826504",
"-763.9752), aic = (\"Akaike criterion\", 1533.950), bic = (\"Schwarz criterion\",",
"#basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 3) assert_almost_equal(res.tvalues, partable[:,2], 2)",
"problem ds_l_realgdp 1.002 realint_1 1.002 VIF(j) = 1/(1 - R(j)^2),",
"result_gretl_g1['llf'][1], decimal=7) #not in gretl #assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=7) #FAIL #assert_almost_equal(res.rsquared_adj,",
"decimal in Gretl output, assert_almost_equal(lev['residual'], res.resid, decimal=3) assert_almost_equal(lev['DFFITS'], infl.dffits[0], decimal=3)",
"arch_4 = [3.43473, 0.487871, 4, \"chi2\"] normality = [23.962, 0.00001,",
"on the rho-differenced data: result_gretl_g1 = dict( endog_mean = (\"Mean",
"-27.665860 -36.294434 11.126262 -58.234939 - -14.353928 2009:1 -70.239280 -44.018178 11.429236",
"j and the other independent variables Properties of matrix X'X:",
"observations 1959:2-2009:3 (T = 202) Dependent variable: scaled uhat^2 coefficient",
"logs: dropping 70 nan or incomplete observations, T=133 #(res_ols.model.exog <=0).any(1).sum()",
"heteroskedasticity OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable:",
"result_gretl_g1 = dict( endog_mean = (\"Mean dependent var\", 3.257395), endog_std",
"mod4.iterative_fit(10) assert_array_less(np.abs(res1.params / res4.params - 1), 0.03) assert_array_less(res4.ssr, res1.ssr) assert_array_less(np.abs(res4.bse",
"nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=1) assert_almost_equal(sm_arch[1], arch_4[1], decimal=2) ''' Performing iterative",
"0.013819244 #Chi-square(2): test-statistic, pvalue, df normality = [20.2792, 3.94837e-005, 2]",
"R-squared 0.673731 F(2, 199) 90.79971 P-value(F) 9.53e-29 Log-likelihood -763.9752 Akaike",
"1959:3-2009:3 (T = 201) Dependent variable: ds_l_realinv rho = -0.108136",
"infl.hat_matrix_diag)) #print np.max(np.abs(lev['influence'] - infl.influence)) #just added this based on",
"4.78086], # *** [-0.579253, 0.268009, -2.161, 0.0319, -1.10777, -0.0507346]]) #",
"and smaller ssr from statsmodels.datasets import macrodata d2 = macrodata.load_pandas().data",
"*** ds_l_realgdp -0.0323119 0.0386353 -0.8363 0.4040 realint_1 0.00410778 0.0512274 0.08019",
"ds_l_realgdp -0.0323119 0.0386353 -0.8363 0.4040 realint_1 0.00410778 0.0512274 0.08019 0.9362",
"1.139 0.2560 uhat_4 -0.0636242 0.0737363 -0.8629 0.3893 Unadjusted R-squared =",
"1537.966), resid_acf1 = (\"rho\", -0.107341), dw = (\"Durbin-Watson\", 2.213805)) linear_logs",
"decimal=7) #TODO c = oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(2,4)) c",
"*** alpha(1) 0.176114 0.0714698 2.464 0.0146 ** alpha(2) -0.0488339 0.0724981",
"0.334872 -1.979 0.0492 ** ds_l_realinv_1 -0.108892 0.0715042 -1.523 0.1294 ds_l_realgdp_1",
"in gretl assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=6) #FAIL assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=6) #FAIL",
"het_breusch_pagan = [1.302014, 0.521520, 2, \"chi2\"] #TODO: not available het_breusch_pagan_konker",
"= macrodata.load_pandas().data #import datasetswsm.greene as g #d = g.load('5-1') #growth",
"= 0.430953 Non-linearity test (squares) - Null hypothesis: relationship is",
"#FAIL #assert_approx_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], significant=1) #FAIL #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c",
"os import numpy as np from numpy.testing import (assert_almost_equal, assert_equal,",
"P(Chi-square(4) > 4.77104) = 0.312 Ljung-Box Q' = 5.23587, with",
"-22.987904 - -11.367905 2008:4 -27.665860 -36.294434 3.036851 -42.282972 - -30.305896",
"0.9039 uhat_3 0.0837332 0.0735015 1.139 0.2560 uhat_4 -0.0636242 0.0737363 -0.8629",
"assert_equal(contrast_res.df_denom, other[3]) assert_equal(\"f\", other[4]) class TestGLSARGretl: def test_all(self): d =",
"0.521520 #heteroscedasticity Breusch-Pagan Koenker Breusch-Pagan test for heteroskedasticity OLS, using",
"= 202) Dependent variable: uhat coefficient std. error t-ratio p-value",
"factor restriction - Null hypothesis: restriction is acceptable Test statistic:",
"coefficient std. error t-ratio p-value ------------------------------------------------------------- const -9.50990 0.990456 -9.602",
"198) 221.0475 P-value(F) 3.56e-51 rho -0.003481 Durbin-Watson 1.993858 ''' '''",
"from statsmodels.datasets import macrodata import statsmodels.stats.sandwich_covariance as sw import statsmodels.stats.diagnostic",
"= [5.248951, 0.023, 1, 198, \"f\"] #LM-statistic, p-value, df arch_4",
"p-value = P(Chi-square(5) > 33.503723) = 0.000003: #heteroscedasticity Breusch-Pagan (original)",
"const 1.09468 0.192281 5.693 4.43e-08 *** ds_l_realgdp -0.0323119 0.0386353 -0.8363",
"2009:1 -70.239280 -44.018178 11.429236 -66.556135 - -21.480222 2009:2 -27.024588 -12.284842",
"= P(F(2, 195) > 0.426391) = 0.653468 Test for normality",
"#Chi-square(2): test-statistic, pvalue, df normality = [20.2792, 3.94837e-005, 2] #tests",
"5984.0525 determinant = 7.1087467e+008 reciprocal_condition_number = 0.013826504 vif = [1.001,",
"statistic: TR^2 = 33.503723, with p-value = P(Chi-square(5) > 33.503723)",
"= (\"S.D. dependent var\", 18.67447), ssr = (\"Sum squared resid\",",
"p-value, df arch_4 = [7.30776, 0.120491, 4, \"chi2\"] #multicollinearity vif",
"resid_acf1 = (\"rho\", -0.003481), dw = (\"Durbin-Watson\", 1.993858)) #fstatistic, p-value,",
"realint_2 0.0769695 0.341527 0.2254 0.8219 Sum of squared residuals =",
"dependent var\", 3.257395), endog_std = (\"S.D. dependent var\", 18.73915), ssr",
"R-squared = 0.165860 Test statistic: TR^2 = 33.503723, with p-value",
"assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) vif2 = [oi.variance_inflation_factor(res.model.exog, k) for k in",
"1.68351) = 0.430953 Non-linearity test (squares) - Null hypothesis: relationship",
"0.08019 0.9362 Explained sum of squares = 2.60403 Test statistic:",
"lag>1 is close to lag=1, and smaller ssr from statsmodels.datasets",
"= P(F(4,195) > 1.17928) = 0.321 Alternative statistic: TR^2 =",
"= [1.002, 1.002] cond_1norm = 6862.0664 determinant = 1.0296049e+009 reciprocal_condition_number",
"mod_g2.iterative_fit(maxiter=5) #print res_g2.params rho = -0.108136 # coefficient std. error",
"-66.556135 - -21.480222 2009:2 -27.024588 -12.284842 10.798554 -33.579120 - 9.009436",
"3.43473 with p-value = P(Chi-square(4) > 3.43473) = 0.487871: #ANOVA",
"Chi-square(2) = 20.2792 with p-value = 3.94837e-005: ''' #no idea",
"198)\", 221.0475), f_pvalue = (\"P-value(F)\", 3.56e-51), resid_acf1 = (\"rho\", -0.003481),",
"dependent var\", 18.67447), ssr = (\"Sum squared resid\", 22530.90), mse_resid_sqrt",
"P(F(2,197) > 5.21902) = 0.00619 RESET test for specification (squares",
"''' Augmented regression for common factor test OLS, using observations",
"change in parameters Test statistic: Harvey-Collier t(198) = 0.494432 with",
"14.785 Mean Absolute Error 12.646 Mean Percentage Error -7.1173 Mean",
"-15.099640 - -9.470044 2009:3 8.078897 4.483669 1.315876 1.888819 - 7.078520",
"with p-value = P(F(1,198) > 7.26849) = 0.00762 RESET test",
"assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=4) assert_allclose(res.f_pvalue, result_gretl_g1['f_pvalue'][1], rtol=1e-2) #assert_almost_equal(res.durbin_watson,",
"parameter stability - Null hypothesis: no change in parameters Test",
"res4.params - 1), 0.03) assert_array_less(res4.ssr, res1.ssr) assert_array_less(np.abs(res4.bse / res1.bse) -",
"0.00424384 Test for ARCH of order 4 - Null hypothesis:",
"R res_g2 = mod_g2.iterative_fit(maxiter=5) #print res_g2.params rho = -0.108136 #",
"** Statistics based on the rho-differenced data: Mean dependent var",
"-0.8363 0.4040 realint_1 0.463643 5.78202 0.08019 0.9362 Explained sum of",
"std. error t-ratio p-value -------------------------------------------------------- alpha(0) 97.0386 20.3234 4.775 3.56e-06",
"rates gs_l_realinv = 400 * np.diff(np.log(d['realinv'].values)) gs_l_realgdp = 400 *",
"Total 70582.3 201 351.156 R^2 = 47782.7 / 70582.3 =",
"2.60403 Test statistic: LM = 1.302014, with p-value = P(Chi-square(2)",
"from Gretl #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 6) assert_almost_equal(res.tvalues,",
"4 lm_acorr4 = [1.17928, 0.321197, 4, 195, \"F\"] lm2_acorr4 =",
"effect is present Test statistic: LM = 3.43473 with p-value",
"--------------------------------------------------------------- const -10.9481 1.35807 -8.062 7.44e-014 *** ds_l_realgdp 4.28893 0.229459",
"assert_almost_equal(res.params, partable[:,0], 5) assert_almost_equal(bse_hac, partable[:,1], 5) #TODO assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2)",
"= 400*np.diff(np.log(d2['realinv'].values)) exogg = add_constant(np.c_[g_gdp, d2['realint'][:-1].values], prepend=False) mod1 = GLSAR(g_inv,",
"/ res1.bse) - 1, 0.015) assert_array_less(np.abs((res4.fittedvalues / res1.fittedvalues - 1).mean()),",
"199 114.571 Total 70582.3 201 351.156 R^2 = 47782.7 /",
"= 0.676978 F(2, 199) = 23891.3 / 114.571 = 208.528",
"var 18.67447 Sum squared resid 22530.90 S.E. of regression 10.66735",
"1, 198, \"f\"] reset_3 = [5.248951, 0.023, 1, 198, \"f\"]",
"p-value ------------------------------------------------------------- const 104.920 21.5848 4.861 2.39e-06 *** ds_l_realgdp -29.7040",
"ds_l_realgdp 4.28893 0.229459 18.69 2.40e-045 *** realint_1 -0.662644 0.334872 -1.979",
"= oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(2,4)) #arch #sm_arch = smsdia.acorr_lm(res.wresid**2,",
"std. error t-ratio p-value ------------------------------------------------------------- const 1.09468 0.192281 5.693 4.43e-08",
"Bias proportion, UM 0.06394 Regression proportion, UR 0.13557 Disturbance proportion,",
"114.571 Total 70582.3 201 351.156 R^2 = 47782.7 / 70582.3",
"g_gdp = 400*np.diff(np.log(d2['realgdp'].values)) g_inv = 400*np.diff(np.log(d2['realinv'].values)) exogg = add_constant(np.c_[g_gdp, d2['realint'][:-1].values],",
"= 7.30776 with p-value = P(Chi-square(4) > 7.30776) = 0.120491:",
"number = 0.013819244 ''' ''' Test for ARCH of order",
"partable[:,1], 3) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1],",
"0.676973 Adjusted R-squared 0.673710 F(2, 198) 221.0475 P-value(F) 3.56e-51 rho",
"np.genfromtxt(fpath, skip_header=3, skip_footer=2, converters={0:lambda s: s}) lev.dtype.names = names res",
"# coefficient std. error t-ratio p-value 95% CONFIDENCE INTERVAL partable",
"Test of common factor restriction Test statistic: F(2, 195) =",
"= 1.0296049e+009 reciprocal_condition_number = 0.013819244 #Chi-square(2): test-statistic, pvalue, df normality",
"variable: uhat coefficient std. error t-ratio p-value ------------------------------------------------------------ const 0.0640964",
"test (squares) - Null hypothesis: relationship is linear Test statistic:",
"1.302014, with p-value = P(Chi-square(2) > 1.302014) = 0.521520 #heteroscedasticity",
"assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 6) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr,",
"Koenker Breusch-Pagan test for heteroskedasticity OLS, using observations 1959:2-2009:3 (T",
"4) if __name__ == '__main__': t = TestGLSARGretl() t.test_all() '''",
"exogg = add_constant(np.c_[g_gdp, d2['realint'][:-1].values], prepend=False) mod1 = GLSAR(g_inv, exogg, 1)",
"(\"rho\", -0.003481), dw = (\"Durbin-Watson\", 1.993858)) #fstatistic, p-value, df1, df2",
"dw = (\"Durbin-Watson\", 2.213805)) linear_logs = [1.68351, 0.430953, 2, \"chi2\"]",
"1.002] cond_1norm = 6862.0664 determinant = 1.0296049e+009 reciprocal_condition_number = 0.013819244",
"= [7.268492, 0.00762, 1, 198, \"f\"] reset_3 = [5.248951, 0.023,",
"#print res_g2.params rho = -0.108136 # coefficient std. error t-ratio",
"= 47782.7 / 70582.3 = 0.676978 F(2, 199) = 23891.3",
"0.176114 0.0714698 2.464 0.0146 ** alpha(2) -0.0488339 0.0724981 -0.6736 0.5014",
"\"chi2\"] #break cusum_Harvey_Collier = [0.494432, 0.621549, 198, \"t\"] #stats.t.sf(0.494432, 198)*2",
"Test statistic: LM = 7.52477 with p-value = P(Chi-square(2) >",
"hypothesis: no structural break Test statistic: max F(3, 196) =",
"= [5.248951, 0.023, 1, 198, \"f\"] #not available cond_1norm =",
"-1.979 0.0492 ** ds_l_realinv_1 -0.108892 0.0715042 -1.523 0.1294 ds_l_realgdp_1 0.660443",
"0.463643 5.78202 0.08019 0.9362 Explained sum of squares = 33174.2",
"endogg = gs_l_realinv exogg = add_constant(np.c_[gs_l_realgdp, d['realint'][:-1].values]) res_ols = OLS(endogg,",
"test for heteroskedasticity OLS, using observations 1959:2-2009:3 (T = 202)",
"1959:2-2009:3 (T = 202) Dependent variable: uhat^2 coefficient std. error",
"no ARCH effect is present Test statistic: LM = 3.43473",
"------------------------------------------------------------- const -9.50990 0.990456 -9.602 3.65e-018 *** ds_l_realgdp 4.37040 0.208146",
"= 0.312 Ljung-Box Q' = 5.23587, with p-value = P(Chi-square(4)",
"with p-value = P(t(198) > 0.494432) = 0.621549 Chow test",
"reset_2_3 = [5.219019, 0.00619, 2, 197, \"f\"] reset_2 = [7.268492,",
"CONFIDENCE INTERVAL partable = np.array([ [-9.50990, 0.990456, -9.602, 3.65e-018, -11.4631,",
"gs_l_realgdp = 400 * np.diff(np.log(d['realgdp'].values)) #simple diff, not growthrate, I",
"P(F(1,198) > 5.24895) = 0.023 #heteroscedasticity White White's test for",
"calculation of rho... ITER RHO ESS 1 -0.10734 22530.9 2",
"5.78202 0.08019 0.9362 Explained sum of squares = 33174.2 Test",
"> 4.77104) = 0.312 Ljung-Box Q' = 5.23587, with p-value",
"400 * np.diff(np.log(d['realinv'].values)) gs_l_realgdp = 400 * np.diff(np.log(d['realgdp'].values)) #simple diff,",
"error t-ratio p-value --------------------------------------------------------------- const -10.9481 1.35807 -8.062 7.44e-014 ***",
"[20.2792, 3.94837e-005, 2] #tests res = res_g1 #with rho from",
"of regression\", 10.66735), rsquared = (\"R-squared\", 0.676973), rsquared_adj = (\"Adjusted",
"Test statistic: LM = 3.43473 with p-value = P(Chi-square(4) >",
"uhat^2 coefficient std. error t-ratio p-value ------------------------------------------------------------- const 1.09468 0.192281",
"#just rough test, low decimal in Gretl output, assert_almost_equal(lev['residual'], res.resid,",
"squared residuals = 22432.8 Test of common factor restriction Test",
"decimal=5) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) vif2 = [oi.variance_inflation_factor(res.model.exog, k) for k",
"hbpk = smsdia.het_breuschpagan(res.resid, res.model.exog) assert_almost_equal(hbpk[0], het_breusch_pagan_konker[0], decimal=6) assert_almost_equal(hbpk[1], het_breusch_pagan_konker[1], decimal=6)",
"observation 2001:4 (10 percent critical value = 4.09) Non-linearity test",
"result_gretl_g1['dw'][1], decimal=7) #TODO #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch",
"(\"S.D. dependent var\", 18.73915), ssr = (\"Sum squared resid\", 22799.68),",
"for lag>1 is close to lag=1, and smaller ssr from",
"- -9.470044 2009:3 8.078897 4.483669 1.315876 1.888819 - 7.078520 Forecast",
"arch_4[1], decimal=6) #tests res = res_g2 #with estimated rho #estimated",
"0.0319 ** Statistics based on the rho-differenced data: Mean dependent",
"Test statistic: F(2, 195) = 0.426391 with p-value = P(F(2,",
"Minimum possible value = 1.0 Values > 10.0 may indicate",
"uhat_3 0.0837332 0.0735015 1.139 0.2560 uhat_4 -0.0636242 0.0737363 -0.8629 0.3893",
"add_constant(np.c_[np.diff(d['realgdp'].values), d['realint'][:-1].values]) endogg = gs_l_realinv exogg = add_constant(np.c_[gs_l_realgdp, d['realint'][:-1].values]) res_ols",
"result_gretl_g1['mse_resid_sqrt'][1], decimal=5) #f-value is based on cov_hac I guess #res2",
"result_gretl_g1['fvalue'][1], decimal=0) assert_almost_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], decimal=6) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c",
"Test for normality of residual - Null hypothesis: error is",
"[1.68351, 0.430953, 2, \"chi2\"] #for logs: dropping 70 nan or",
"[33.503723, 0.000003, 5, \"chi2\"] het_breusch_pagan = [1.302014, 0.521520, 2, \"chi2\"]",
"partable[:,0], 5) assert_almost_equal(bse_hac, partable[:,1], 5) #TODO assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) assert_almost_equal(res.llf,",
"0.268009 -2.161 0.0319 ** Statistics based on the rho-differenced data:",
"rho -0.107341 Durbin-Watson 2.213805 QLR test for structural break -",
"changed behavior if np.isnan(lev[-1]['f1']): lev = np.genfromtxt(fpath, skip_header=3, skip_footer=2, converters={0:lambda",
"S.D. dependent var 18.67447 Sum squared resid 22530.90 S.E. of",
"p-value = P(F(4,195) > 1.17928) = 0.321197 CUSUM test for",
"Determinant = 1.0296049e+009 Reciprocal condition number = 0.013819244 ''' '''",
"= 0.165860 Test statistic: TR^2 = 33.503723, with p-value =",
"2.93e-052, 3.95993, 4.78086], # *** [-0.579253, 0.268009, -2.161, 0.0319, -1.10777,",
"-0.0456010 0.217377 -0.2098 0.8341 realint_1 0.0511769 0.293136 0.1746 0.8616 uhat_1",
"value = 4.09) Non-linearity test (logs) - Null hypothesis: relationship",
"1.17928) = 0.321 Alternative statistic: TR^2 = 4.771043, with p-value",
"-7.1173 Mean Absolute Percentage Error -43.867 Theil's U 0.4365 Bias",
"5.693 4.43e-08 *** ds_l_realgdp -0.0323119 0.0386353 -0.8363 0.4040 realint_1 0.00410778",
"(\"R-squared\", 0.676978), rsquared_adj = (\"Adjusted R-squared\", 0.673731), fvalue = (\"F(2,",
"test for parameter stability - Null hypothesis: no change in",
"- infl.dffits[0])) #print np.max(np.abs(lev['leverage'] - infl.hat_matrix_diag)) #print np.max(np.abs(lev['influence'] - infl.influence))",
"351.156 R^2 = 47782.7 / 70582.3 = 0.676978 F(2, 199)",
"(\"Akaike criterion\", 1533.950), bic = (\"Schwarz criterion\", 1543.875), hqic =",
"Analysis of Variance: Sum of squares df Mean square Regression",
"up to order 4 OLS, using observations 1959:2-2009:3 (T =",
"2008:4 -27.665860 -36.294434 11.126262 -58.234939 - -14.353928 2009:1 -70.239280 -44.018178",
"0.673731), fvalue = (\"F(2, 199)\", 90.79971), f_pvalue = (\"P-value(F)\", 9.53e-29),",
"\"chi2\"] acorr_ljungbox4 = [5.23587, 0.264, 4, \"chi2\"] #break cusum_Harvey_Collier =",
"[7.30776, 0.120491, 4, \"chi2\"] #multicollinearity vif = [1.002, 1.002] cond_1norm",
"Null hypothesis: relationship is linear Test statistic: LM = 1.68351",
"90.79971), f_pvalue = (\"P-value(F)\", 9.53e-29), llf = (\"Log-likelihood\", -763.9752), aic",
"converters={0:lambda s: s}) #either numpy 1.6 or python 3.2 changed",
"with p-value = 3.94837e-005: ''' #no idea what this is",
"linear_logs = [1.68351, 0.430953, 2, \"chi2\"] #for logs: dropping 70",
"= 0.701200 ########## forecast #forecast mean y For 95% confidence",
"OLS, GLSAR from statsmodels.tools.tools import add_constant from statsmodels.datasets import macrodata",
"114.571 = 208.528 [p-value 1.47e-049] #LM-test autocorrelation Breusch-Godfrey test for",
"-17.177905 11.101892 -39.070353 - 4.714544 2008:4 -27.665860 -36.294434 11.126262 -58.234939",
"\"f\"] #LM-statistic, p-value, df arch_4 = [7.30776, 0.120491, 4, \"chi2\"]",
"0.00762, 1, 198, \"f\"] reset_3 = [5.248951, 0.023, 1, 198,",
"pvalue, df normality = [20.2792, 3.94837e-005, 2] #tests res =",
"Statistics based on the rho-differenced data: Mean dependent var 3.113973",
"= gs_l_realinv exogg = add_constant(np.c_[gs_l_realgdp, d['realint'][:-1].values]) res_ols = OLS(endogg, exogg).fit()",
"p-value 95% CONFIDENCE INTERVAL partable = np.array([ [-9.50990, 0.990456, -9.602,",
"test for specification (cubes only) Test statistic: F = 5.248951,",
"1.972 Obs ds_l_realinv prediction std. error 95% interval 2008:3 -7.134492",
"assert_equal(len(mod4.rho), 4) if __name__ == '__main__': t = TestGLSARGretl() t.test_all()",
"-0.8629 0.3893 Unadjusted R-squared = 0.023619 Test statistic: LMF =",
"= 5.248951, with p-value = P(F(1,198) > 5.24895) = 0.023:",
"= 0.426391, with p-value = 0.653468 ''' ################ with OLS,",
"3.95993, 4.78086], # *** [-0.579253, 0.268009, -2.161, 0.0319, -1.10777, -0.0507346]])",
"cur_dir = os.path.abspath(os.path.dirname(__file__)) fpath = os.path.join(cur_dir, 'results/leverage_influence_ols_nostars.txt') lev = np.genfromtxt(fpath,",
"result_gretl_g1['rsquared'][1], decimal=6) #FAIL assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=6) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5)",
"is linear Test statistic: LM = 7.52477 with p-value =",
"= 0.00762 RESET test for specification (cubes only) Test statistic:",
"decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=0) assert_almost_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], decimal=6) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7)",
"10.66735 R-squared 0.676973 Adjusted R-squared 0.673710 F(2, 198) 221.0475 P-value(F)",
"want heteroscedasticity later for testing endogd = np.diff(d['realinv']) exogd =",
"result_gretl_g1['fvalue'][1], decimal=0) #FAIL #assert_approx_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], significant=1) #FAIL #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7)",
"std. error t-ratio p-value 95% CONFIDENCE INTERVAL #for confidence interval",
"#arch #sm_arch = smsdia.acorr_lm(res.resid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.resid, nlags=4)",
"kernel) #coefficient std. error t-ratio p-value 95% CONFIDENCE INTERVAL #for",
"is present Test statistic: LM = 7.30776 with p-value =",
"statsmodels.datasets import macrodata import statsmodels.stats.sandwich_covariance as sw import statsmodels.stats.diagnostic as",
"#TODO: not available het_breusch_pagan_konker = [0.709924, 0.701200, 2, \"chi2\"] reset_2_3",
"dependent var\", 18.73915), ssr = (\"Sum squared resid\", 22799.68), mse_resid_sqrt",
"res_g2.params rho = -0.108136 # coefficient std. error t-ratio p-value",
"standard errors, bandwidth 4 (Bartlett kernel) coefficient std. error t-ratio",
"2012 Author: <NAME> License: BSD-3 \"\"\" import os import numpy",
"-0.579253 0.268009 -2.161 0.0319 ** Statistics based on the rho-differenced",
"Dependent variable: ds_l_realinv rho = -0.108136 coefficient std. error t-ratio",
"Q' = 5.23587, with p-value = P(Chi-square(4) > 5.23587) =",
"hw = smsdia.het_white(res.resid, res.model.exog) assert_almost_equal(hw[:2], het_white[:2], 6) #arch #sm_arch =",
"df Mean square Regression 47782.7 2 23891.3 Residual 22799.7 199",
"statistic: F(2, 195) = 0.426391, with p-value = 0.653468 '''",
"Mean square Regression 47782.7 2 23891.3 Residual 22799.7 199 114.571",
"= (\"P-value(F)\", 9.53e-29), llf = (\"Log-likelihood\", -763.9752), aic = (\"Akaike",
"1959:2-2009:3 (T = 202) Dependent variable: scaled uhat^2 (Koenker robust",
"1984:1 arch_4 = [3.43473, 0.487871, 4, \"chi2\"] normality = [23.962,",
"names = 'date residual leverage influence DFFITS'.split() cur_dir = os.path.abspath(os.path.dirname(__file__))",
"0.1475 uhat_2 -0.00898483 0.0742817 -0.1210 0.9039 uhat_3 0.0837332 0.0735015 1.139",
"compare_ftest(contrast_res, other, decimal=(5,4)): assert_almost_equal(contrast_res.fvalue, other[0], decimal=decimal[0]) assert_almost_equal(contrast_res.pvalue, other[1], decimal=decimal[1]) assert_equal(contrast_res.df_num,",
"0.165860 Test statistic: TR^2 = 33.503723, with p-value = P(Chi-square(5)",
"0.701200 ########## forecast #forecast mean y For 95% confidence intervals,",
"(\"P-value(F)\", 9.53e-29), llf = (\"Log-likelihood\", -763.9752), aic = (\"Akaike criterion\",",
"-27.024588 -12.284842 1.427414 -15.099640 - -9.470044 2009:3 8.078897 4.483669 1.315876",
"2009:3 8.078897 4.483669 10.784377 -16.782652 - 25.749991 Forecast evaluation statistics",
"''' Model 5: OLS, using observations 1959:2-2009:3 (T = 202)",
"mse_resid_sqrt = (\"S.E. of regression\", 10.70380), rsquared = (\"R-squared\", 0.676978),",
"res1 = mod1.iterative_fit(5) mod4 = GLSAR(g_inv, exogg, 4) res4 =",
"t-ratio p-value ------------------------------------------------------------ const 10.6870 21.7027 0.4924 0.6230 ds_l_realgdp -3.64704",
"res = res_g2 #with estimated rho #estimated lag coefficient assert_almost_equal(res.model.rho,",
"''' Test for ARCH of order 4 - Null hypothesis:",
"output, assert_almost_equal(lev['residual'], res.resid, decimal=3) assert_almost_equal(lev['DFFITS'], infl.dffits[0], decimal=3) assert_almost_equal(lev['leverage'], infl.hat_matrix_diag, decimal=3)",
"0.990456, -9.602, 3.65e-018, -11.4631, -7.55670], # *** [ 4.37040, 0.208146,",
"Dependent variable: uhat^2 coefficient std. error t-ratio p-value ------------------------------------------------------------- const",
"0.0640964 1.06719 0.06006 0.9522 ds_l_realgdp -0.0456010 0.217377 -0.2098 0.8341 realint_1",
"resid\", 22530.90), mse_resid_sqrt = (\"S.E. of regression\", 10.66735), rsquared =",
"low decimal in Gretl output, assert_almost_equal(lev['residual'], res.resid, decimal=3) assert_almost_equal(lev['DFFITS'], infl.dffits[0],",
"const -9.50990 0.990456 -9.602 3.65e-018 *** ds_l_realgdp 4.37040 0.208146 21.00",
"21.00, 2.93e-052, 3.95993, 4.78086], # *** [-0.579253, 0.268009, -2.161, 0.0319,",
"np.array([ [-9.48167, 1.17709, -8.055, 7.17e-014, -11.8029, -7.16049], # *** [4.37422,",
"assert_almost_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], decimal=6) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c = oi.reset_ramsey(res,",
"0.0232283 LM test for autocorrelation up to order 4 -",
"= 3.94837e-005: ''' #no idea what this is ''' Augmented",
"-8.062 7.44e-014 *** ds_l_realgdp 4.28893 0.229459 18.69 2.40e-045 *** realint_1",
"factor test OLS, using observations 1959:3-2009:3 (T = 201) Dependent",
"(T = 201) Dependent variable: ds_l_realinv coefficient std. error t-ratio",
"-44.018178 4.007017 -51.919841 - -36.116516 2009:2 -27.024588 -12.284842 1.427414 -15.099640",
"prediction std. error 95% interval 2008:3 -7.134492 -17.177905 2.946312 -22.987904",
"smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=1)",
"res = res_g1 #with rho from Gretl #basic assert_almost_equal(res.params, partable[:,0],",
"0.000003, 5, \"chi2\"] het_breusch_pagan = [1.302014, 0.521520, 2, \"chi2\"] #TODO:",
"Squared Error 14.785 Mean Absolute Error 12.646 Mean Percentage Error",
"#TODO c = oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(2,4)) c =",
"-0.10734 22530.9 2 -0.10814 22530.9 Model 4: Cochrane-Orcutt, using observations",
"-0.662644 0.334872 -1.979 0.0492 ** ds_l_realinv_1 -0.108892 0.0715042 -1.523 0.1294",
"with p-value = P(Chi-square(2) > 1.302014) = 0.521520 #heteroscedasticity Breusch-Pagan",
"4.77104) = 0.312 Ljung-Box Q' = 5.23587, with p-value =",
"Test statistic: F = 7.268492, with p-value = P(F(1,198) >",
"22530.9 Model 4: Cochrane-Orcutt, using observations 1959:3-2009:3 (T = 201)",
"for autocorrelation up to order 4 lm_acorr4 = [1.17928, 0.321197,",
"- infl.influence)) #just added this based on Gretl #just rough",
"assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=4) #not in gretl assert_almost_equal(res.rsquared,",
"########## forecast #forecast mean y For 95% confidence intervals, t(199,",
"-12.284842 1.427414 -15.099640 - -9.470044 2009:3 8.078897 4.483669 1.315876 1.888819",
"4) assert_almost_equal(res.bse, partable[:,1], 6) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2)",
"on Thu Feb 02 21:15:47 2012 Author: <NAME> License: BSD-3",
"oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(6,5)) linear_sq = smsdia.linear_lm(res.resid, res.model.exog) assert_almost_equal(linear_sq[0],",
"for k in [1,2]] infl = oi.OLSInfluence(res_ols) #print np.max(np.abs(lev['DFFITS'] -",
"-9.602 3.65e-018 *** ds_l_realgdp 4.37040 0.208146 21.00 2.93e-052 *** realint_1",
"OLS(endogg, exogg).fit() #print res_ols.params mod_g1 = GLSAR(endogg, exogg, rho=-0.108136) res_g1",
"def compare_ftest(contrast_res, other, decimal=(5,4)): assert_almost_equal(contrast_res.fvalue, other[0], decimal=decimal[0]) assert_almost_equal(contrast_res.pvalue, other[1], decimal=decimal[1])",
"utf-8 -*- \"\"\"Tests of GLSAR and diagnostics against Gretl Created",
"compare_ftest(c, reset_2_3, decimal=(2,4)) #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch",
"18.69 2.40e-045 *** realint_1 -0.662644 0.334872 -1.979 0.0492 ** ds_l_realinv_1",
"2, \"chi2\"] het_white = [33.503723, 0.000003, 5, \"chi2\"] het_breusch_pagan =",
"#FAIL assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=6) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) #f-value is",
"7.1087467e+008 reciprocal_condition_number = 0.013826504 vif = [1.001, 1.001] names =",
"- -36.116516 2009:2 -27.024588 -12.284842 1.427414 -15.099640 - -9.470044 2009:3",
"13.30 2.62e-029 *** realint_1 -0.613997 0.293619 -2.091 0.0378 ** Mean",
"P(F(4,195) > 1.17928) = 0.321 Alternative statistic: TR^2 = 4.771043,",
"= (\"S.E. of regression\", 10.66735), rsquared = (\"R-squared\", 0.676973), rsquared_adj",
"GLSAR(g_inv, exogg, 4) res4 = mod4.iterative_fit(10) assert_array_less(np.abs(res1.params / res4.params -",
"0.0512274 0.08019 0.9362 Explained sum of squares = 2.60403 Test",
"break at observation 1984:1 - Null hypothesis: no structural break",
"8.62e-09 *** X2_X3 2.89685 1.38571 2.091 0.0379 ** sq_realint_1 0.662135",
"F(2, 198) 221.0475 P-value(F) 3.56e-51 rho -0.003481 Durbin-Watson 1.993858 '''",
"statistic: F(2, 195) = 0.426391 with p-value = P(F(2, 195)",
"0.0837332 0.0735015 1.139 0.2560 uhat_4 -0.0636242 0.0737363 -0.8629 0.3893 Unadjusted",
"Mean Percentage Error -7.1173 Mean Absolute Percentage Error -43.867 Theil's",
"common factor restriction - Null hypothesis: restriction is acceptable Test",
"47782.7 2 23891.3 Residual 22799.7 199 114.571 Total 70582.3 201",
"Sum of squared residuals = 22432.8 Test of common factor",
"7.52477) = 0.0232283 LM test for autocorrelation up to order",
"1959:2-2009:3 (T = 202) Dependent variable: uhat coefficient std. error",
"= mod_g1.fit() #print res_g1.params mod_g2 = GLSAR(endogg, exogg, rho=-0.108136) #-0.1335859)",
"0.00619 RESET test for specification (squares only) Test statistic: F",
"reset_2_3, decimal=(6,5)) linear_sq = smsdia.linear_lm(res.resid, res.model.exog) assert_almost_equal(linear_sq[0], linear_squares[0], decimal=6) assert_almost_equal(linear_sq[1],",
"assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=6) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) #f-value is based",
"test for structural break at observation 1984:1 - Null hypothesis:",
"= 0.023619 Test statistic: LMF = 1.179281, with p-value =",
"#assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c = oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2,",
"with p-value = P(F(4,195) > 1.17928) = 0.321197 CUSUM test",
"1.993858 ''' ''' RESET test for specification (squares and cubes)",
"interval t(199, 0.025) = 1.972 partable = np.array([ [-9.48167, 1.17709,",
"R-squared\", 0.673731), fvalue = (\"F(2, 199)\", 90.79971), f_pvalue = (\"P-value(F)\",",
"#heteroscedasticity Breusch-Pagan (original) Breusch-Pagan test for heteroskedasticity OLS, using observations",
"df2 reset_2_3 = [5.219019, 0.00619, 2, 197, \"f\"] reset_2 =",
"13.1897 with p-value = 0.00424384 Test for ARCH of order",
"autolag=None) sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=4) assert_almost_equal(sm_arch[1], arch_4[1],",
"-21.480222 2009:2 -27.024588 -12.284842 10.798554 -33.579120 - 9.009436 2009:3 8.078897",
"95% interval 2008:3 -7.134492 -17.177905 2.946312 -22.987904 - -11.367905 2008:4",
"202) #Dependent variable: ds_l_realinv #HAC standard errors, bandwidth 4 (Bartlett",
"t.test_all() ''' Model 5: OLS, using observations 1959:2-2009:3 (T =",
"res_ols #for easier copying cov_hac = sw.cov_hac_simple(res, nlags=4, use_correction=False) bse_hac",
"Gretl, trying any of the HCx #assert_almost_equal(res2.fvalue, result_gretl_g1['fvalue'][1], decimal=0) #FAIL",
"on cov_hac I guess #res2 = res.get_robustcov_results(cov_type='HC1') # TODO: fvalue",
"assert_almost_equal(res.model.rho, rho, decimal=3) #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 3)",
"reset_3 = [5.248951, 0.023, 1, 198, \"f\"] #not available cond_1norm",
"DFFITS'.split() cur_dir = os.path.abspath(os.path.dirname(__file__)) fpath = os.path.join(cur_dir, 'results/leverage_influence_ols_nostars.txt') lev =",
"-70.239280 -44.018178 11.429236 -66.556135 - -21.480222 2009:2 -27.024588 -12.284842 10.798554",
"ITER RHO ESS 1 -0.10734 22530.9 2 -0.10814 22530.9 Model",
"assert_almost_equal(res.bse, partable[:,1], 6) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf,",
"using observations 1959:2-2009:3 (T = 202) #Dependent variable: ds_l_realinv #HAC",
"for structural break - Null hypothesis: no structural break Test",
"structural break - Null hypothesis: no structural break Test statistic:",
"uhat_2 -0.00898483 0.0742817 -0.1210 0.9039 uhat_3 0.0837332 0.0735015 1.139 0.2560",
"3.113973), endog_std = (\"S.D. dependent var\", 18.67447), ssr = (\"Sum",
"hypothesis: error is normally distributed Test statistic: Chi-square(2) = 20.2792",
"np.diff(d['realinv']) exogd = add_constant(np.c_[np.diff(d['realgdp'].values), d['realint'][:-1].values]) endogg = gs_l_realinv exogg =",
"= np.genfromtxt(fpath, skip_header=3, skip_footer=1, converters={0:lambda s: s}) #either numpy 1.6",
"test for autocorrelation up to order 4 lm_acorr4 = [1.17928,",
"using observations 1959:2-2009:3 (T = 202) Dependent variable: scaled uhat^2",
"linear Test statistic: LM = 7.52477 with p-value = P(Chi-square(2)",
"2001:4 (10 percent critical value = 4.09) Non-linearity test (logs)",
"assert_almost_equal(contrast_res.pvalue, other[1], decimal=decimal[1]) assert_equal(contrast_res.df_num, other[2]) assert_equal(contrast_res.df_denom, other[3]) assert_equal(\"f\", other[4]) class",
"0.015) assert_array_less(np.abs((res4.fittedvalues / res1.fittedvalues - 1).mean()), 0.015) assert_equal(len(mod4.rho), 4) if",
"based on the rho-differenced data: Mean dependent var 3.113973 S.D.",
"decimal=(5,4)): assert_almost_equal(contrast_res.fvalue, other[0], decimal=decimal[0]) assert_almost_equal(contrast_res.pvalue, other[1], decimal=decimal[1]) assert_equal(contrast_res.df_num, other[2]) assert_equal(contrast_res.df_denom,",
"p-value --------------------------------------------------------------- const -10.9481 1.35807 -8.062 7.44e-014 *** ds_l_realgdp 4.28893",
"#HAC standard errors, bandwidth 4 (Bartlett kernel) #coefficient std. error",
"2.40e-045 *** realint_1 -0.662644 0.334872 -1.979 0.0492 ** ds_l_realinv_1 -0.108892",
"(\"Log-likelihood\", -763.9752), aic = (\"Akaike criterion\", 1533.950), bic = (\"Schwarz",
"Test statistic: LM = 1.302014, with p-value = P(Chi-square(2) >",
"t-ratio p-value --------------------------------------------------------------- const -10.9481 1.35807 -8.062 7.44e-014 *** ds_l_realgdp",
"= [3.43473, 0.487871, 4, \"chi2\"] normality = [23.962, 0.00001, 2,",
"0.000003: #heteroscedasticity Breusch-Pagan (original) Breusch-Pagan test for heteroskedasticity OLS, using",
"coefficient assert_almost_equal(res.model.rho, rho, decimal=3) #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1],",
"F(2, 195) = 0.426391, with p-value = 0.653468 ''' ################",
"= smsdia.het_arch(res.resid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=5) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) vif2",
"4.12054 0.684920 6.016 8.62e-09 *** X2_X3 2.89685 1.38571 2.091 0.0379",
"het_breusch_pagan_konker = [0.709924, 0.701200, 2, \"chi2\"] reset_2_3 = [5.219019, 0.00619,",
"p-value = P(F(2, 195) > 0.426391) = 0.653468 Test for",
"0.120491, 4, \"chi2\"] #multicollinearity vif = [1.002, 1.002] cond_1norm =",
"#not in gretl assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=6) #FAIL assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=6)",
"Breusch-Pagan Koenker Breusch-Pagan test for heteroskedasticity OLS, using observations 1959:2-2009:3",
"p-value ------------------------------------------------------------- const -9.50990 0.990456 -9.602 3.65e-018 *** ds_l_realgdp 4.37040",
"\"chi2\"] #TODO: not available het_breusch_pagan_konker = [0.709924, 0.701200, 2, \"chi2\"]",
"0.0378 ** Mean dependent var 3.257395 S.D. dependent var 18.73915",
"vif2 = [oi.variance_inflation_factor(res.model.exog, k) for k in [1,2]] infl =",
"0.0725763 0.5298 0.5968 Null hypothesis: no ARCH effect is present",
"square Regression 47782.7 2 23891.3 Residual 22799.7 199 114.571 Total",
"= P(Chi-square(2) > 1.68351) = 0.430953 Non-linearity test (squares) -",
"of squared residuals = 22432.8 Test of common factor restriction",
"[7.52477, 0.0232283, 2, \"chi2\"] #Autocorrelation, Breusch-Godfrey test for autocorrelation up",
"P(F(2, 195) > 0.426391) = 0.653468 Test for normality of",
"= 1.972 partable = np.array([ [-9.48167, 1.17709, -8.055, 7.17e-014, -11.8029,",
"(T = 202) Dependent variable: scaled uhat^2 (Koenker robust variant)",
"decimal=5) #f-value is based on cov_hac I guess #res2 =",
"Percentage Error -43.867 Theil's U 0.4365 Bias proportion, UM 0.06394",
"interval 2008:3 -7.134492 -17.177905 11.101892 -39.070353 - 4.714544 2008:4 -27.665860",
"variable: ds_l_realinv #HAC standard errors, bandwidth 4 (Bartlett kernel) #coefficient",
"0.0492 ** ds_l_realinv_1 -0.108892 0.0715042 -1.523 0.1294 ds_l_realgdp_1 0.660443 0.390372",
"statistic: Harvey-Collier t(198) = 0.494432 with p-value = P(t(198) >",
"= 0.013819244 ''' ''' Test for ARCH of order 4",
"------------------------------------------------------------ const 0.0640964 1.06719 0.06006 0.9522 ds_l_realgdp -0.0456010 0.217377 -0.2098",
"198, \"f\"] #LM-statistic, p-value, df arch_4 = [7.30776, 0.120491, 4,",
"*** ds_l_realgdp 4.37422 0.328787 13.30 2.62e-029 *** realint_1 -0.613997 0.293619",
"70 linear_squares = [7.52477, 0.0232283, 2, \"chi2\"] #Autocorrelation, Breusch-Godfrey test",
"GLSAR from statsmodels.tools.tools import add_constant from statsmodels.datasets import macrodata import",
"-0.8363 0.4040 realint_1 0.00410778 0.0512274 0.08019 0.9362 Explained sum of",
"18.73915), ssr = (\"Sum squared resid\", 22799.68), mse_resid_sqrt = (\"S.E.",
"(\"Sum squared resid\", 22530.90), mse_resid_sqrt = (\"S.E. of regression\", 10.66735),",
"diagnostics against Gretl Created on Thu Feb 02 21:15:47 2012",
"endog_std = (\"S.D. dependent var\", 18.67447), ssr = (\"Sum squared",
"matrix X'X: 1-norm = 6862.0664 Determinant = 1.0296049e+009 Reciprocal condition",
"0.684920 6.016 8.62e-09 *** X2_X3 2.89685 1.38571 2.091 0.0379 **",
"k in [1,2]] infl = oi.OLSInfluence(res_ols) #print np.max(np.abs(lev['DFFITS'] - infl.dffits[0]))",
"max F(3, 196) = 3.01985 at observation 2001:4 (10 percent",
"10.6870 21.7027 0.4924 0.6230 ds_l_realgdp -3.64704 4.36075 -0.8363 0.4040 realint_1",
"* np.diff(np.log(d['realgdp'].values)) #simple diff, not growthrate, I want heteroscedasticity later",
"regression\", 10.66735), rsquared = (\"R-squared\", 0.676973), rsquared_adj = (\"Adjusted R-squared\",",
"4.28893 0.229459 18.69 2.40e-045 *** realint_1 -0.662644 0.334872 -1.979 0.0492",
"or python 3.2 changed behavior if np.isnan(lev[-1]['f1']): lev = np.genfromtxt(fpath,",
"-0.003481), dw = (\"Durbin-Watson\", 1.993858)) #fstatistic, p-value, df1, df2 reset_2_3",
"7.30776) = 0.120491 Test of common factor restriction - Null",
"effect is present Test statistic: LM = 7.30776 with p-value",
"decimal=6) vif2 = [oi.variance_inflation_factor(res.model.exog, k) for k in [1,2]] infl",
"-4.753 3.88e-06 *** realint_1 -6.93102 6.95607 -0.9964 0.3203 sq_ds_l_realg 4.12054",
"t-ratio p-value ------------------------------------------------------------- const 1.09468 0.192281 5.693 4.43e-08 *** ds_l_realgdp",
"ds_l_realinv #HAC standard errors, bandwidth 4 (Bartlett kernel) #coefficient std.",
"Residual 22799.7 199 114.571 Total 70582.3 201 351.156 R^2 =",
"198)*2 #see cusum results in files break_qlr = [3.01985, 0.1,",
"0.217377 -0.2098 0.8341 realint_1 0.0511769 0.293136 0.1746 0.8616 uhat_1 -0.104707",
"0.9362 Explained sum of squares = 2.60403 Test statistic: LM",
"-14.353928 2009:1 -70.239280 -44.018178 11.429236 -66.556135 - -21.480222 2009:2 -27.024588",
"2.213805)) linear_logs = [1.68351, 0.430953, 2, \"chi2\"] #for logs: dropping",
"dropping 70 nan or incomplete observations, T=133 #(res_ols.model.exog <=0).any(1).sum() =",
"HAC errors #Model 5: OLS, using observations 1959:2-2009:3 (T =",
"7.17e-014 *** ds_l_realgdp 4.37422 0.328787 13.30 2.62e-029 *** realint_1 -0.613997",
"1.002 realint_1 1.002 VIF(j) = 1/(1 - R(j)^2), where R(j)",
"1, 198, \"f\"] #LM-statistic, p-value, df arch_4 = [7.30776, 0.120491,",
"= add_constant(np.c_[gs_l_realgdp, d['realint'][:-1].values]) res_ols = OLS(endogg, exogg).fit() #print res_ols.params mod_g1",
"statsmodels.stats.outliers_influence as oi def compare_ftest(contrast_res, other, decimal=(5,4)): assert_almost_equal(contrast_res.fvalue, other[0], decimal=decimal[0])",
"rsquared_adj = (\"Adjusted R-squared\", 0.673731), fvalue = (\"F(2, 199)\", 90.79971),",
"import macrodata import statsmodels.stats.sandwich_covariance as sw import statsmodels.stats.diagnostic as smsdia",
"ds_l_realgdp 4.37422 0.328787 13.30 2.62e-029 *** realint_1 -0.613997 0.293619 -2.091",
"-7.134492 -17.177905 11.101892 -39.070353 - 4.714544 2008:4 -27.665860 -36.294434 11.126262",
"[0.494432, 0.621549, 198, \"t\"] #stats.t.sf(0.494432, 198)*2 #see cusum results in",
"#ANOVA Analysis of Variance: Sum of squares df Mean square",
"4.861 2.39e-06 *** ds_l_realgdp -29.7040 6.24983 -4.753 3.88e-06 *** realint_1",
"Chi-square(3) = 13.1897 with p-value = 0.00424384 Test for ARCH",
"= [5.219019, 0.00619, 2, 197, \"f\"] reset_2 = [7.268492, 0.00762,",
"12.646 Mean Percentage Error -7.1173 Mean Absolute Percentage Error -43.867",
"g.load('5-1') #growth rates gs_l_realinv = 400 * np.diff(np.log(d['realinv'].values)) gs_l_realgdp =",
"Null hypothesis: no change in parameters Test statistic: Harvey-Collier t(198)",
"fvalue differs from Gretl, trying any of the HCx #assert_almost_equal(res2.fvalue,",
"-763.9752 Akaike criterion 1533.950 Schwarz criterion 1543.875 Hannan-Quinn 1537.966 rho",
"LM = 1.302014, with p-value = P(Chi-square(2) > 1.302014) =",
"error t-ratio p-value ------------------------------------------------------------- const -9.48167 1.17709 -8.055 7.17e-014 ***",
"18.73915 Sum squared resid 22799.68 S.E. of regression 10.70380 R-squared",
"for specification (squares only) Test statistic: F = 7.268492, with",
"assert_equal(contrast_res.df_num, other[2]) assert_equal(contrast_res.df_denom, other[3]) assert_equal(\"f\", other[4]) class TestGLSARGretl: def test_all(self):",
"- Null hypothesis: relationship is linear Test statistic: LM =",
"(\"F(2, 199)\", 90.79971), f_pvalue = (\"P-value(F)\", 9.53e-29), llf = (\"Log-likelihood\",",
"1.17928 with p-value = P(F(4,195) > 1.17928) = 0.321197 CUSUM",
"-0.0323119 0.0386353 -0.8363 0.4040 realint_1 0.00410778 0.0512274 0.08019 0.9362 Explained",
"t(199, 0.025) = 1.972 Obs ds_l_realinv prediction std. error 95%",
"-17.177905 2.946312 -22.987904 - -11.367905 2008:4 -27.665860 -36.294434 3.036851 -42.282972",
"6.24983 -4.753 3.88e-06 *** realint_1 -6.93102 6.95607 -0.9964 0.3203 sq_ds_l_realg",
"Harvey-Collier t(198) = 0.494432 with p-value = P(t(198) > 0.494432)",
"exogg, rho=-0.108136) #-0.1335859) from R res_g2 = mod_g2.iterative_fit(maxiter=5) #print res_g2.params",
"- Null hypothesis: no ARCH effect is present Test statistic:",
"test for autocorrelation up to order 4 - Null hypothesis:",
"?not 70 linear_squares = [7.52477, 0.0232283, 2, \"chi2\"] #Autocorrelation, Breusch-Godfrey",
"acorr_ljungbox4 = [5.23587, 0.264, 4, \"chi2\"] #break cusum_Harvey_Collier = [0.494432,",
"*** X2_X3 2.89685 1.38571 2.091 0.0379 ** sq_realint_1 0.662135 1.10919",
"[-9.48167, 1.17709, -8.055, 7.17e-014, -11.8029, -7.16049], # *** [4.37422, 0.328787,",
"Test statistic: TR^2 = 33.503723, with p-value = P(Chi-square(5) >",
"*** [ 4.37040, 0.208146, 21.00, 2.93e-052, 3.95993, 4.78086], # ***",
"I guess #res2 = res.get_robustcov_results(cov_type='HC1') # TODO: fvalue differs from",
"oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(6,5)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c,",
"2, \"chi2\"] #Autocorrelation, Breusch-Godfrey test for autocorrelation up to order",
"decimal=7) hbpk = smsdia.het_breuschpagan(res.resid, res.model.exog) assert_almost_equal(hbpk[0], het_breusch_pagan_konker[0], decimal=6) assert_almost_equal(hbpk[1], het_breusch_pagan_konker[1],",
"p-value, df1, df2 reset_2_3 = [5.219019, 0.00619, 2, 197, \"f\"]",
"Author: <NAME> License: BSD-3 \"\"\" import os import numpy as",
"195, \"F\"] lm2_acorr4 = [4.771043, 0.312, 4, \"chi2\"] acorr_ljungbox4 =",
"# *** [4.37422, 0.328787, 13.30, 2.62e-029, 3.72587, 5.02258], #*** [-0.613997,",
"0.701200, 2, \"chi2\"] reset_2_3 = [5.219019, 0.00619, 2, 197, \"f\"]",
"add_constant from statsmodels.datasets import macrodata import statsmodels.stats.sandwich_covariance as sw import",
"exogg, 1) res1 = mod1.iterative_fit(5) mod4 = GLSAR(g_inv, exogg, 4)",
"Null hypothesis: no structural break Asymptotic test statistic: Chi-square(3) =",
"#assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=7) #not in gretl #assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=7) #FAIL",
"= (\"P-value(F)\", 3.56e-51), resid_acf1 = (\"rho\", -0.003481), dw = (\"Durbin-Watson\",",
"realint_1 0.0511769 0.293136 0.1746 0.8616 uhat_1 -0.104707 0.0719948 -1.454 0.1475",
"10.784377 -16.782652 - 25.749991 Forecast evaluation statistics Mean Error -3.7387",
"Error -43.867 Theil's U 0.4365 Bias proportion, UM 0.06394 Regression",
"#no idea what this is ''' Augmented regression for common",
"autocorrelation Breusch-Godfrey test for autocorrelation up to order 4 OLS,",
"''' ''' Test for ARCH of order 4 - Null",
"P(Chi-square(4) > 5.23587) = 0.264: RESET test for specification (squares",
"4.37040, 0.208146, 21.00, 2.93e-052, 3.95993, 4.78086], # *** [-0.579253, 0.268009,",
"RESET test for specification (cubes only) Test statistic: F =",
"0.494432 with p-value = P(t(198) > 0.494432) = 0.621549 Chow",
"Error 218.61 Root Mean Squared Error 14.785 Mean Absolute Error",
"= 2.60403 Test statistic: LM = 1.302014, with p-value =",
"RHO ESS 1 -0.10734 22530.9 2 -0.10814 22530.9 Model 4:",
"4, \"chi2\"] acorr_ljungbox4 = [5.23587, 0.264, 4, \"chi2\"] #break cusum_Harvey_Collier",
"#print np.max(np.abs(lev['DFFITS'] - infl.dffits[0])) #print np.max(np.abs(lev['leverage'] - infl.hat_matrix_diag)) #print np.max(np.abs(lev['influence']",
"1.35807 -8.062 7.44e-014 *** ds_l_realgdp 4.28893 0.229459 18.69 2.40e-045 ***",
"2009:1 -70.239280 -44.018178 4.007017 -51.919841 - -36.116516 2009:2 -27.024588 -12.284842",
"22530.90), mse_resid_sqrt = (\"S.E. of regression\", 10.66735), rsquared = (\"R-squared\",",
"c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(2,4)) #arch #sm_arch =",
"observations 1959:3-2009:3 (T = 201) Dependent variable: ds_l_realinv coefficient std.",
"4) assert_almost_equal(res.bse, partable[:,1], 3) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2)",
"partable[:,1], 5) #TODO assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=4) #not",
"hypothesis: no autocorrelation Test statistic: LMF = 1.17928 with p-value",
"= P(F(1,198) > 5.24895) = 0.023: ''' ''' Test for",
"#assert_approx_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], significant=1) #FAIL #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c =",
"LM = 1.68351 with p-value = P(Chi-square(2) > 1.68351) =",
"incomplete observations, T=133 #(res_ols.model.exog <=0).any(1).sum() = 69 ?not 70 linear_squares",
"mod_g1 = GLSAR(endogg, exogg, rho=-0.108136) res_g1 = mod_g1.fit() #print res_g1.params",
"with p-value = P(Chi-square(4) > 7.30776) = 0.120491 Test of",
"#Dependent variable: ds_l_realinv #HAC standard errors, bandwidth 4 (Bartlett kernel)",
"parameters Test statistic: Harvey-Collier t(198) = 0.494432 with p-value =",
"percent critical value = 4.09) Non-linearity test (logs) - Null",
"var\", 3.257395), endog_std = (\"S.D. dependent var\", 18.73915), ssr =",
"error t-ratio p-value ------------------------------------------------------------ const 0.0640964 1.06719 0.06006 0.9522 ds_l_realgdp",
"rtol=1e-2) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4,",
"2, \"chi2\"] reset_2_3 = [5.219019, 0.00619, 2, 197, \"f\"] reset_2",
"4.43e-08 *** ds_l_realgdp -0.0323119 0.0386353 -0.8363 0.4040 realint_1 0.00410778 0.0512274",
"normally distributed Test statistic: Chi-square(2) = 20.2792 with p-value =",
"realint_1 1.002 VIF(j) = 1/(1 - R(j)^2), where R(j) is",
"#TODO #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.wresid,",
"maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.resid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=5) assert_almost_equal(sm_arch[1],",
"autolag=None) sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=1) assert_almost_equal(sm_arch[1], arch_4[1],",
"5.219019, with p-value = P(F(2,197) > 5.21902) = 0.00619 RESET",
"#f-value is based on cov_hac I guess #res2 = res.get_robustcov_results(cov_type='HC1')",
"0.312, 4, \"chi2\"] acorr_ljungbox4 = [5.23587, 0.264, 4, \"chi2\"] #break",
"4.36075 -0.8363 0.4040 realint_1 0.463643 5.78202 0.08019 0.9362 Explained sum",
"7.30776) = 0.120491: ''' ''' Variance Inflation Factors Minimum possible",
"TR^2 = 33.503723, with p-value = P(Chi-square(5) > 33.503723) =",
"2.89685 1.38571 2.091 0.0379 ** sq_realint_1 0.662135 1.10919 0.5970 0.5512",
"195) = 0.426391, with p-value = 0.653468 ''' ################ with",
"0.426391, with p-value = 0.653468 ''' ################ with OLS, HAC",
"> 5.24895) = 0.023 #heteroscedasticity White White's test for heteroskedasticity",
"sq_realint_1 0.662135 1.10919 0.5970 0.5512 Unadjusted R-squared = 0.165860 Test",
"exogg = add_constant(np.c_[gs_l_realgdp, d['realint'][:-1].values]) res_ols = OLS(endogg, exogg).fit() #print res_ols.params",
"d['realint'][:-1].values]) endogg = gs_l_realinv exogg = add_constant(np.c_[gs_l_realgdp, d['realint'][:-1].values]) res_ols =",
"Mean Squared Error 14.785 Mean Absolute Error 12.646 Mean Percentage",
"const -10.9481 1.35807 -8.062 7.44e-014 *** ds_l_realgdp 4.28893 0.229459 18.69",
"ARCH of order 4 - Null hypothesis: no ARCH effect",
"for testing endogd = np.diff(d['realinv']) exogd = add_constant(np.c_[np.diff(d['realgdp'].values), d['realint'][:-1].values]) endogg",
"= [33.503723, 0.000003, 5, \"chi2\"] het_breusch_pagan = [1.302014, 0.521520, 2,",
"[1.17928, 0.321197, 4, 195, \"F\"] lm2_acorr4 = [4.771043, 0.312, 4,",
"Chow test for structural break at observation 1984:1 - Null",
"ds_l_realgdp -3.64704 4.36075 -0.8363 0.4040 realint_1 0.463643 5.78202 0.08019 0.9362",
"198, \"t\"] #stats.t.sf(0.494432, 198)*2 #see cusum results in files break_qlr",
"= 4.09) Non-linearity test (logs) - Null hypothesis: relationship is",
"6.016 8.62e-09 *** X2_X3 2.89685 1.38571 2.091 0.0379 ** sq_realint_1",
"License: BSD-3 \"\"\" import os import numpy as np from",
"> 7.30776) = 0.120491: ''' ''' Variance Inflation Factors Minimum",
"0.2560 uhat_4 -0.0636242 0.0737363 -0.8629 0.3893 Unadjusted R-squared = 0.023619",
"result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=4) assert_allclose(res.f_pvalue,",
"= P(Chi-square(2) > 1.302014) = 0.521520 #heteroscedasticity Breusch-Pagan Koenker Breusch-Pagan",
"proportion, UR 0.13557 Disturbance proportion, UD 0.80049 #forecast actual y",
"ESS 1 -0.10734 22530.9 2 -0.10814 22530.9 Model 4: Cochrane-Orcutt,",
"= 0.653468 Test for normality of residual - Null hypothesis:",
"g_inv = 400*np.diff(np.log(d2['realinv'].values)) exogg = add_constant(np.c_[g_gdp, d2['realint'][:-1].values], prepend=False) mod1 =",
"= (\"Sum squared resid\", 22530.90), mse_resid_sqrt = (\"S.E. of regression\",",
"vif = [1.002, 1.002] cond_1norm = 6862.0664 determinant = 1.0296049e+009",
"= GLSAR(endogg, exogg, rho=-0.108136) res_g1 = mod_g1.fit() #print res_g1.params mod_g2",
"#assert_almost_equal(res2.fvalue, result_gretl_g1['fvalue'][1], decimal=0) #FAIL #assert_approx_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], significant=1) #FAIL #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1],",
"[0.709924, 0.701200, 2, \"chi2\"] reset_2_3 = [5.219019, 0.00619, 2, 197,",
"value = 1.0 Values > 10.0 may indicate a collinearity",
"GLSAR(endogg, exogg, rho=-0.108136) #-0.1335859) from R res_g2 = mod_g2.iterative_fit(maxiter=5) #print",
"0.0511769 0.293136 0.1746 0.8616 uhat_1 -0.104707 0.0719948 -1.454 0.1475 uhat_2",
"= 6862.0664 Determinant = 1.0296049e+009 Reciprocal condition number = 0.013819244",
"\"f\"] reset_3 = [5.248951, 0.023, 1, 198, \"f\"] #LM-statistic, p-value,",
"linear_squares[1], decimal=7) hbpk = smsdia.het_breuschpagan(res.resid, res.model.exog) assert_almost_equal(hbpk[0], het_breusch_pagan_konker[0], decimal=6) assert_almost_equal(hbpk[1],",
"std. error t-ratio p-value ------------------------------------------------------------ const 10.6870 21.7027 0.4924 0.6230",
"statistic: LMF = 1.17928 with p-value = P(F(4,195) > 1.17928)",
"= [7.30776, 0.120491, 4, \"chi2\"] #multicollinearity vif = [1.002, 1.002]",
"= 5.248951, with p-value = P(F(1,198) > 5.24895) = 0.023",
"assert_almost_equal(contrast_res.fvalue, other[0], decimal=decimal[0]) assert_almost_equal(contrast_res.pvalue, other[1], decimal=decimal[1]) assert_equal(contrast_res.df_num, other[2]) assert_equal(contrast_res.df_denom, other[3])",
"is normally distributed Test statistic: Chi-square(2) = 20.2792 with p-value",
"decimal=7) #not in gretl #assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=7) #FAIL #assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1],",
"import OLS, GLSAR from statsmodels.tools.tools import add_constant from statsmodels.datasets import",
"= (\"Akaike criterion\", 1533.950), bic = (\"Schwarz criterion\", 1543.875), hqic",
"with p-value = P(Chi-square(5) > 33.503723) = 0.000003: #heteroscedasticity Breusch-Pagan",
"with p-value = P(F(2, 195) > 0.426391) = 0.653468 Test",
"assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=0) assert_almost_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], decimal=6) #assert_almost_equal(res.durbin_watson,",
"criterion\", 1533.950), bic = (\"Schwarz criterion\", 1543.875), hqic = (\"Hannan-Quinn\",",
"Created on Thu Feb 02 21:15:47 2012 Author: <NAME> License:",
"assert_almost_equal(linear_sq[0], linear_squares[0], decimal=6) assert_almost_equal(linear_sq[1], linear_squares[1], decimal=7) hbpk = smsdia.het_breuschpagan(res.resid, res.model.exog)",
"4 (Bartlett kernel) coefficient std. error t-ratio p-value ------------------------------------------------------------- const",
"-2.161, 0.0319, -1.10777, -0.0507346]]) # ** #Statistics based on the",
"0.023, 1, 198, \"f\"] #LM-statistic, p-value, df arch_4 = [7.30776,",
"''' ################ with OLS, HAC errors #Model 5: OLS, using",
"[23.962, 0.00001, 2, \"chi2\"] het_white = [33.503723, 0.000003, 5, \"chi2\"]",
"4.771043, with p-value = P(Chi-square(4) > 4.77104) = 0.312 Ljung-Box",
"-0.613997 0.293619 -2.091 0.0378 ** Mean dependent var 3.257395 S.D.",
"= GLSAR(endogg, exogg, rho=-0.108136) #-0.1335859) from R res_g2 = mod_g2.iterative_fit(maxiter=5)",
"(squares) - Null hypothesis: relationship is linear Test statistic: LM",
"#print res_g1.params mod_g2 = GLSAR(endogg, exogg, rho=-0.108136) #-0.1335859) from R",
"0.013826504 vif = [1.001, 1.001] names = 'date residual leverage",
"-0.1210 0.9039 uhat_3 0.0837332 0.0735015 1.139 0.2560 uhat_4 -0.0636242 0.0737363",
"is acceptable Test statistic: F(2, 195) = 0.426391 with p-value",
"0.0737363 -0.8629 0.3893 Unadjusted R-squared = 0.023619 Test statistic: LMF",
"for autocorrelation up to order 4 - Null hypothesis: no",
"1.001] names = 'date residual leverage influence DFFITS'.split() cur_dir =",
"is based on cov_hac I guess #res2 = res.get_robustcov_results(cov_type='HC1') #",
"Breusch-Godfrey test for autocorrelation up to order 4 OLS, using",
"BSD-3 \"\"\" import os import numpy as np from numpy.testing",
"for specification (cubes only) Test statistic: F = 5.248951, with",
"> 5.24895) = 0.023: ''' ''' Test for ARCH of",
"= 4.771043, with p-value = P(Chi-square(4) > 4.77104) = 0.312",
"y For 95% confidence intervals, t(199, 0.025) = 1.972 Obs",
"bic = (\"Schwarz criterion\", 1543.875), hqic = (\"Hannan-Quinn\", 1537.966), resid_acf1",
"at 2001:4 break_chow = [13.1897, 0.00424384, 3, \"chi2\"] # break",
"-36.116516 2009:2 -27.024588 -12.284842 1.427414 -15.099640 - -9.470044 2009:3 8.078897",
"0.293136 0.1746 0.8616 uhat_1 -0.104707 0.0719948 -1.454 0.1475 uhat_2 -0.00898483",
"<=0).any(1).sum() = 69 ?not 70 linear_squares = [7.52477, 0.0232283, 2,",
"order 4 - Null hypothesis: no autocorrelation Test statistic: LMF",
"check this, max at 2001:4 break_chow = [13.1897, 0.00424384, 3,",
"- Null hypothesis: no change in parameters Test statistic: Harvey-Collier",
"0.990456 -9.602 3.65e-018 *** ds_l_realgdp 4.37040 0.208146 21.00 2.93e-052 ***",
"squares = 33174.2 Test statistic: LM = 0.709924, with p-value",
"compare_ftest(c, reset_2_3, decimal=(6,5)) linear_sq = smsdia.linear_lm(res.resid, res.model.exog) assert_almost_equal(linear_sq[0], linear_squares[0], decimal=6)",
"realint_1 0.463643 5.78202 0.08019 0.9362 Explained sum of squares =",
"#arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.wresid, nlags=4)",
"assert_almost_equal(sm_arch[0], arch_4[0], decimal=4) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) #tests res = res_g2",
"0.521520, 2, \"chi2\"] #TODO: not available het_breusch_pagan_konker = [0.709924, 0.701200,",
"(\"S.D. dependent var\", 18.67447), ssr = (\"Sum squared resid\", 22530.90),",
"Regression 47782.7 2 23891.3 Residual 22799.7 199 114.571 Total 70582.3",
"from statsmodels.regression.linear_model import OLS, GLSAR from statsmodels.tools.tools import add_constant from",
"result_gretl_g1['llf'][1], decimal=4) #not in gretl assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=6) #FAIL assert_almost_equal(res.rsquared_adj,",
"= add_constant(np.c_[np.diff(d['realgdp'].values), d['realint'][:-1].values]) endogg = gs_l_realinv exogg = add_constant(np.c_[gs_l_realgdp, d['realint'][:-1].values])",
"= 400 * np.diff(np.log(d['realinv'].values)) gs_l_realgdp = 400 * np.diff(np.log(d['realgdp'].values)) #simple",
"Sum squared resid 22530.90 S.E. of regression 10.66735 R-squared 0.676973",
"decimal=(2,4)) #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.wresid,",
"7.17e-014, -11.8029, -7.16049], # *** [4.37422, 0.328787, 13.30, 2.62e-029, 3.72587,",
"#heteroscedasticity Breusch-Pagan Koenker Breusch-Pagan test for heteroskedasticity OLS, using observations",
"[1.002, 1.002] cond_1norm = 6862.0664 determinant = 1.0296049e+009 reciprocal_condition_number =",
"0.08019 0.9362 Explained sum of squares = 33174.2 Test statistic:",
"= 1/(1 - R(j)^2), where R(j) is the multiple correlation",
"of GLSAR and diagnostics against Gretl Created on Thu Feb",
"1) res1 = mod1.iterative_fit(5) mod4 = GLSAR(g_inv, exogg, 4) res4",
"196, \"maxF\"] #TODO check this, max at 2001:4 break_chow =",
"res.model.exog) assert_almost_equal(hbpk[0], het_breusch_pagan_konker[0], decimal=6) assert_almost_equal(hbpk[1], het_breusch_pagan_konker[1], decimal=6) hw = smsdia.het_white(res.resid,",
"#break cusum_Harvey_Collier = [0.494432, 0.621549, 198, \"t\"] #stats.t.sf(0.494432, 198)*2 #see",
"influence DFFITS'.split() cur_dir = os.path.abspath(os.path.dirname(__file__)) fpath = os.path.join(cur_dir, 'results/leverage_influence_ols_nostars.txt') lev",
"normality of residual - Null hypothesis: error is normally distributed",
"-0.107341 Durbin-Watson 2.213805 QLR test for structural break - Null",
"only) Test statistic: F = 5.248951, with p-value = P(F(1,198)",
"- 7.078520 Forecast evaluation statistics Mean Error -3.7387 Mean Squared",
"res_g1 = mod_g1.fit() #print res_g1.params mod_g2 = GLSAR(endogg, exogg, rho=-0.108136)",
"= dict( endog_mean = (\"Mean dependent var\", 3.113973), endog_std =",
"s}) lev.dtype.names = names res = res_ols #for easier copying",
"var\", 18.73915), ssr = (\"Sum squared resid\", 22799.68), mse_resid_sqrt =",
"acceptable Test statistic: F(2, 195) = 0.426391 with p-value =",
"-7.134492 -17.177905 2.946312 -22.987904 - -11.367905 2008:4 -27.665860 -36.294434 3.036851",
"scaled uhat^2 coefficient std. error t-ratio p-value ------------------------------------------------------------- const 1.09468",
"''' RESET test for specification (squares and cubes) Test statistic:",
"RESET test for specification (squares only) Test statistic: F =",
"Dependent variable: ds_l_realinv coefficient std. error t-ratio p-value --------------------------------------------------------------- const",
"for heteroskedasticity OLS, using observations 1959:2-2009:3 (T = 202) Dependent",
"TODO: fvalue differs from Gretl, trying any of the HCx",
"= 202) Dependent variable: uhat^2 coefficient std. error t-ratio p-value",
"error t-ratio p-value ------------------------------------------------------------ const 10.6870 21.7027 0.4924 0.6230 ds_l_realgdp",
"10.798554 -33.579120 - 9.009436 2009:3 8.078897 4.483669 10.784377 -16.782652 -",
"res1.bse) - 1, 0.015) assert_array_less(np.abs((res4.fittedvalues / res1.fittedvalues - 1).mean()), 0.015)",
"= OLS(endogg, exogg).fit() #print res_ols.params mod_g1 = GLSAR(endogg, exogg, rho=-0.108136)",
"3, \"chi2\"] # break at 1984:1 arch_4 = [3.43473, 0.487871,",
"F(2, 199) = 23891.3 / 114.571 = 208.528 [p-value 1.47e-049]",
"assert_array_less(np.abs(res4.bse / res1.bse) - 1, 0.015) assert_array_less(np.abs((res4.fittedvalues / res1.fittedvalues -",
"is ''' Augmented regression for common factor test OLS, using",
"7.30776 with p-value = P(Chi-square(4) > 7.30776) = 0.120491 Test",
"decimal=6) hw = smsdia.het_white(res.resid, res.model.exog) assert_almost_equal(hw[:2], het_white[:2], 6) #arch #sm_arch",
"3.01985 at observation 2001:4 (10 percent critical value = 4.09)",
"(\"R-squared\", 0.676973), rsquared_adj = (\"Adjusted R-squared\", 0.673710), fvalue = (\"F(2,",
"t-ratio p-value ------------------------------------------------------------- const -9.50990 0.990456 -9.602 3.65e-018 *** ds_l_realgdp",
"hypothesis: restriction is acceptable Test statistic: F(2, 195) = 0.426391",
"restriction is acceptable Test statistic: F(2, 195) = 0.426391 with",
"criterion\", 1543.875), hqic = (\"Hannan-Quinn\", 1537.966), resid_acf1 = (\"rho\", -0.107341),",
"(\"S.E. of regression\", 10.70380), rsquared = (\"R-squared\", 0.676978), rsquared_adj =",
"= 201) Dependent variable: ds_l_realinv coefficient std. error t-ratio p-value",
"for autocorrelation up to order 4 OLS, using observations 1959:2-2009:3",
"partable = np.array([ [-9.48167, 1.17709, -8.055, 7.17e-014, -11.8029, -7.16049], #",
"(\"Adjusted R-squared\", 0.673710), fvalue = (\"F(2, 198)\", 221.0475), f_pvalue =",
"= np.array([ [-9.50990, 0.990456, -9.602, 3.65e-018, -11.4631, -7.55670], # ***",
"mod_g2 = GLSAR(endogg, exogg, rho=-0.108136) #-0.1335859) from R res_g2 =",
"is linear Test statistic: LM = 1.68351 with p-value =",
"partable = np.array([ [-9.50990, 0.990456, -9.602, 3.65e-018, -11.4631, -7.55670], #",
"restriction Test statistic: F(2, 195) = 0.426391, with p-value =",
"mse_resid_sqrt = (\"S.E. of regression\", 10.66735), rsquared = (\"R-squared\", 0.676973),",
"decimal=0) assert_almost_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], decimal=6) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c =",
"#assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None)",
"/ res1.fittedvalues - 1).mean()), 0.015) assert_equal(len(mod4.rho), 4) if __name__ ==",
"observations 1959:2-2009:3 (T = 202) Dependent variable: uhat coefficient std.",
"other independent variables Properties of matrix X'X: 1-norm = 6862.0664",
"= g.load('5-1') #growth rates gs_l_realinv = 400 * np.diff(np.log(d['realinv'].values)) gs_l_realgdp",
"[3.43473, 0.487871, 4, \"chi2\"] normality = [23.962, 0.00001, 2, \"chi2\"]",
"0.023 #heteroscedasticity White White's test for heteroskedasticity OLS, using observations",
"p-value = P(Chi-square(4) > 7.30776) = 0.120491 Test of common",
"0.3203 sq_ds_l_realg 4.12054 0.684920 6.016 8.62e-09 *** X2_X3 2.89685 1.38571",
"for specification (squares and cubes) Test statistic: F = 5.219019,",
"based on cov_hac I guess #res2 = res.get_robustcov_results(cov_type='HC1') # TODO:",
"#FAIL #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c = oi.reset_ramsey(res, degree=2) compare_ftest(c,",
"heteroscedasticity later for testing endogd = np.diff(d['realinv']) exogd = add_constant(np.c_[np.diff(d['realgdp'].values),",
"relationship is linear Test statistic: LM = 7.52477 with p-value",
"endog_mean = (\"Mean dependent var\", 3.113973), endog_std = (\"S.D. dependent",
"result_gretl_g1['ssr'][1], decimal=2) assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=4) #not in gretl assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1],",
"critical value = 4.09) Non-linearity test (logs) - Null hypothesis:",
"#either numpy 1.6 or python 3.2 changed behavior if np.isnan(lev[-1]['f1']):",
"0.0319, -1.10777, -0.0507346]]) # ** #Statistics based on the rho-differenced",
"1-norm = 6862.0664 Determinant = 1.0296049e+009 Reciprocal condition number =",
"= 1.972 Obs ds_l_realinv prediction std. error 95% interval 2008:3",
"resid 22799.68 S.E. of regression 10.70380 R-squared 0.676978 Adjusted R-squared",
"const -9.48167 1.17709 -8.055 7.17e-014 *** ds_l_realgdp 4.37422 0.328787 13.30",
"statsmodels.stats.sandwich_covariance as sw import statsmodels.stats.diagnostic as smsdia import statsmodels.stats.outliers_influence as",
"p-value = 3.94837e-005: ''' #no idea what this is '''",
"Gretl #just rough test, low decimal in Gretl output, assert_almost_equal(lev['residual'],",
"numpy 1.6 or python 3.2 changed behavior if np.isnan(lev[-1]['f1']): lev",
"Regression proportion, UR 0.13557 Disturbance proportion, UD 0.80049 #forecast actual",
"1, 198, \"f\"] #not available cond_1norm = 5984.0525 determinant =",
"-2.091 0.0378 ** Mean dependent var 3.257395 S.D. dependent var",
"= 202) #Dependent variable: ds_l_realinv #HAC standard errors, bandwidth 4",
"0.0146 ** alpha(2) -0.0488339 0.0724981 -0.6736 0.5014 alpha(3) -0.0705413 0.0737058",
"f_pvalue = (\"P-value(F)\", 9.53e-29), llf = (\"Log-likelihood\", -763.9752), aic =",
"- 25.749991 Forecast evaluation statistics Mean Error -3.7387 Mean Squared",
"os.path.join(cur_dir, 'results/leverage_influence_ols_nostars.txt') lev = np.genfromtxt(fpath, skip_header=3, skip_footer=1, converters={0:lambda s: s})",
"0.312 Ljung-Box Q' = 5.23587, with p-value = P(Chi-square(4) >",
"#Autocorrelation, Breusch-Godfrey test for autocorrelation up to order 4 lm_acorr4",
"= [1.68351, 0.430953, 2, \"chi2\"] #for logs: dropping 70 nan",
"Disturbance proportion, UD 0.80049 #forecast actual y For 95% confidence",
"0.00762 RESET test for specification (cubes only) Test statistic: F",
"os.path.abspath(os.path.dirname(__file__)) fpath = os.path.join(cur_dir, 'results/leverage_influence_ols_nostars.txt') lev = np.genfromtxt(fpath, skip_header=3, skip_footer=1,",
"= 3.01985 at observation 2001:4 (10 percent critical value =",
"Non-linearity test (logs) - Null hypothesis: relationship is linear Test",
"oi def compare_ftest(contrast_res, other, decimal=(5,4)): assert_almost_equal(contrast_res.fvalue, other[0], decimal=decimal[0]) assert_almost_equal(contrast_res.pvalue, other[1],",
"4 coefficient std. error t-ratio p-value -------------------------------------------------------- alpha(0) 97.0386 20.3234",
"7.26849) = 0.00762 RESET test for specification (cubes only) Test",
"endog_mean = (\"Mean dependent var\", 3.257395), endog_std = (\"S.D. dependent",
"var 18.73915 Sum squared resid 22799.68 S.E. of regression 10.70380",
"-9.48167 1.17709 -8.055 7.17e-014 *** ds_l_realgdp 4.37422 0.328787 13.30 2.62e-029",
"behavior if np.isnan(lev[-1]['f1']): lev = np.genfromtxt(fpath, skip_header=3, skip_footer=2, converters={0:lambda s:",
"195) > 0.426391) = 0.653468 Test for normality of residual",
"1.47e-049] #LM-test autocorrelation Breusch-Godfrey test for autocorrelation up to order",
"Schwarz criterion 1543.875 Hannan-Quinn 1537.966 rho -0.107341 Durbin-Watson 2.213805 QLR",
"decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=4) assert_allclose(res.f_pvalue, result_gretl_g1['f_pvalue'][1],",
"= 69 ?not 70 linear_squares = [7.52477, 0.0232283, 2, \"chi2\"]",
"- 9.009436 2009:3 8.078897 4.483669 10.784377 -16.782652 - 25.749991 Forecast",
"** alpha(2) -0.0488339 0.0724981 -0.6736 0.5014 alpha(3) -0.0705413 0.0737058 -0.9571",
"= np.diff(d['realinv']) exogd = add_constant(np.c_[np.diff(d['realgdp'].values), d['realint'][:-1].values]) endogg = gs_l_realinv exogg",
"= P(t(198) > 0.494432) = 0.621549 Chow test for structural",
"LM = 3.43473 with p-value = P(Chi-square(4) > 3.43473) =",
"4.775 3.56e-06 *** alpha(1) 0.176114 0.0714698 2.464 0.0146 ** alpha(2)",
"import numpy as np from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose,",
"of rho... ITER RHO ESS 1 -0.10734 22530.9 2 -0.10814",
"arch_4[1], decimal=2) ''' Performing iterative calculation of rho... ITER RHO",
"= res_g1 #with rho from Gretl #basic assert_almost_equal(res.params, partable[:,0], 4)",
"= 7.52477 with p-value = P(Chi-square(2) > 7.52477) = 0.0232283",
"with p-value = P(F(2,197) > 5.21902) = 0.00619 RESET test",
"0.293619, -2.091, 0.0378, -1.19300, -0.0349939]]) # ** result_gretl_g1 = dict(",
"= 23891.3 / 114.571 = 208.528 [p-value 1.47e-049] #LM-test autocorrelation",
"*** realint_1 -0.662644 0.334872 -1.979 0.0492 ** ds_l_realinv_1 -0.108892 0.0715042",
"198, \"f\"] reset_3 = [5.248951, 0.023, 1, 198, \"f\"] #not",
"guess #res2 = res.get_robustcov_results(cov_type='HC1') # TODO: fvalue differs from Gretl,",
"Non-linearity test (squares) - Null hypothesis: relationship is linear Test",
"CUSUM test for parameter stability - Null hypothesis: no change",
"t-ratio p-value ------------------------------------------------------------- const -9.48167 1.17709 -8.055 7.17e-014 *** ds_l_realgdp",
"#stats.t.sf(0.494432, 198)*2 #see cusum results in files break_qlr = [3.01985,",
"= 3.43473 with p-value = P(Chi-square(4) > 3.43473) = 0.487871:",
"ARCH effect is present Test statistic: LM = 3.43473 with",
"res_g2 #with estimated rho #estimated lag coefficient assert_almost_equal(res.model.rho, rho, decimal=3)",
"dependent var 3.257395 S.D. dependent var 18.73915 Sum squared resid",
"0.9362 Explained sum of squares = 33174.2 Test statistic: LM",
"0.208146 21.00 2.93e-052 *** realint_1 -0.579253 0.268009 -2.161 0.0319 **",
"result_gretl_g1['dw'][1], decimal=7) #TODO c = oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(2,4))",
"assert_array_less(np.abs((res4.fittedvalues / res1.fittedvalues - 1).mean()), 0.015) assert_equal(len(mod4.rho), 4) if __name__",
"Inflation Factors Minimum possible value = 1.0 Values > 10.0",
"ds_l_realinv_1 -0.108892 0.0715042 -1.523 0.1294 ds_l_realgdp_1 0.660443 0.390372 1.692 0.0923",
"#TODO c = oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(6,5)) c =",
"P(Chi-square(2) > 0.709924) = 0.701200 ########## forecast #forecast mean y",
"smsdia.linear_lm(res.resid, res.model.exog) assert_almost_equal(linear_sq[0], linear_squares[0], decimal=6) assert_almost_equal(linear_sq[1], linear_squares[1], decimal=7) hbpk =",
"autocorrelation Test statistic: LMF = 1.17928 with p-value = P(F(4,195)",
"= [20.2792, 3.94837e-005, 2] #tests res = res_g1 #with rho",
"d['realint'][:-1].values]) res_ols = OLS(endogg, exogg).fit() #print res_ols.params mod_g1 = GLSAR(endogg,",
"= 22432.8 Test of common factor restriction Test statistic: F(2,",
"infl.influence)) #just added this based on Gretl #just rough test,",
"= 1.179281, with p-value = P(F(4,195) > 1.17928) = 0.321",
"-3.7387 Mean Squared Error 218.61 Root Mean Squared Error 14.785",
"\"chi2\"] #multicollinearity vif = [1.002, 1.002] cond_1norm = 6862.0664 determinant",
"= P(F(2,197) > 5.21902) = 0.00619 RESET test for specification",
"sm_arch = smsdia.het_arch(res.resid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=5) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6)",
"0.0715042 -1.523 0.1294 ds_l_realgdp_1 0.660443 0.390372 1.692 0.0923 * realint_2",
"1.315876 1.888819 - 7.078520 Forecast evaluation statistics Mean Error -3.7387",
"3.43473) = 0.487871: #ANOVA Analysis of Variance: Sum of squares",
"idea what this is ''' Augmented regression for common factor",
"P(F(1,198) > 7.26849) = 0.00762 RESET test for specification (cubes",
"#for confidence interval t(199, 0.025) = 1.972 partable = np.array([",
"-11.8029, -7.16049], # *** [4.37422, 0.328787, 13.30, 2.62e-029, 3.72587, 5.02258],",
"Test statistic: Chi-square(2) = 20.2792 with p-value = 3.94837e-005: '''",
"p-value ------------------------------------------------------------ const 10.6870 21.7027 0.4924 0.6230 ds_l_realgdp -3.64704 4.36075",
"(Koenker robust variant) coefficient std. error t-ratio p-value ------------------------------------------------------------ const",
"ds_l_realgdp 4.37040 0.208146 21.00 2.93e-052 *** realint_1 -0.579253 0.268009 -2.161",
"(T = 202) #Dependent variable: ds_l_realinv #HAC standard errors, bandwidth",
"0.00619, 2, 197, \"f\"] reset_2 = [7.268492, 0.00762, 1, 198,",
"0.1746 0.8616 uhat_1 -0.104707 0.0719948 -1.454 0.1475 uhat_2 -0.00898483 0.0742817",
"Dependent variable: scaled uhat^2 (Koenker robust variant) coefficient std. error",
"assert_allclose(res.f_pvalue, result_gretl_g1['f_pvalue'][1], rtol=1e-2) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO #arch #sm_arch =",
"0.5970 0.5512 Unadjusted R-squared = 0.165860 Test statistic: TR^2 =",
"= smsdia.acorr_lm(res.resid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.resid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0],",
"201) Dependent variable: ds_l_realinv rho = -0.108136 coefficient std. error",
"fvalue = (\"F(2, 198)\", 221.0475), f_pvalue = (\"P-value(F)\", 3.56e-51), resid_acf1",
"hqic = (\"Hannan-Quinn\", 1537.966), resid_acf1 = (\"rho\", -0.107341), dw =",
"0.0386353 -0.8363 0.4040 realint_1 0.00410778 0.0512274 0.08019 0.9362 Explained sum",
"what this is ''' Augmented regression for common factor test",
"of common factor restriction - Null hypothesis: restriction is acceptable",
"or incomplete observations, T=133 #(res_ols.model.exog <=0).any(1).sum() = 69 ?not 70",
"var 3.113973 S.D. dependent var 18.67447 Sum squared resid 22530.90",
"other[0], decimal=decimal[0]) assert_almost_equal(contrast_res.pvalue, other[1], decimal=decimal[1]) assert_equal(contrast_res.df_num, other[2]) assert_equal(contrast_res.df_denom, other[3]) assert_equal(\"f\",",
"Ljung-Box Q' = 5.23587, with p-value = P(Chi-square(4) > 5.23587)",
"*** [-0.579253, 0.268009, -2.161, 0.0319, -1.10777, -0.0507346]]) # ** #Statistics",
"I want heteroscedasticity later for testing endogd = np.diff(d['realinv']) exogd",
"0.0714698 2.464 0.0146 ** alpha(2) -0.0488339 0.0724981 -0.6736 0.5014 alpha(3)",
"test for structural break - Null hypothesis: no structural break",
"= mod1.iterative_fit(5) mod4 = GLSAR(g_inv, exogg, 4) res4 = mod4.iterative_fit(10)",
"3.56e-06 *** alpha(1) 0.176114 0.0714698 2.464 0.0146 ** alpha(2) -0.0488339",
"p-value = P(F(2,197) > 5.21902) = 0.00619 RESET test for",
"#FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) #f-value is based on cov_hac I",
"structural break Asymptotic test statistic: Chi-square(3) = 13.1897 with p-value",
"0.676978), rsquared_adj = (\"Adjusted R-squared\", 0.673731), fvalue = (\"F(2, 199)\",",
"error t-ratio p-value 95% CONFIDENCE INTERVAL #for confidence interval t(199,",
"p-value = P(Chi-square(4) > 4.77104) = 0.312 Ljung-Box Q' =",
"2.93e-052 *** realint_1 -0.579253 0.268009 -2.161 0.0319 ** Statistics based",
"97.0386 20.3234 4.775 3.56e-06 *** alpha(1) 0.176114 0.0714698 2.464 0.0146",
"0.4040 realint_1 0.463643 5.78202 0.08019 0.9362 Explained sum of squares",
"3.257395), endog_std = (\"S.D. dependent var\", 18.73915), ssr = (\"Sum",
"t-ratio p-value ------------------------------------------------------------- const 104.920 21.5848 4.861 2.39e-06 *** ds_l_realgdp",
"result_gretl_g1['fvalue'][1], decimal=4) assert_allclose(res.f_pvalue, result_gretl_g1['f_pvalue'][1], rtol=1e-2) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO #arch",
"(\"Mean dependent var\", 3.257395), endog_std = (\"S.D. dependent var\", 18.73915),",
"1.0 Values > 10.0 may indicate a collinearity problem ds_l_realgdp",
"test OLS, using observations 1959:3-2009:3 (T = 201) Dependent variable:",
"Forecast evaluation statistics Mean Error -3.7387 Mean Squared Error 218.61",
"of regression 10.66735 R-squared 0.676973 Adjusted R-squared 0.673710 F(2, 198)",
"res = res_ols #for easier copying cov_hac = sw.cov_hac_simple(res, nlags=4,",
"(original) Breusch-Pagan test for heteroskedasticity OLS, using observations 1959:2-2009:3 (T",
"observations 1959:2-2009:3 (T = 202) Dependent variable: scaled uhat^2 (Koenker",
"0.426391 with p-value = P(F(2, 195) > 0.426391) = 0.653468",
"#TODO check this, max at 2001:4 break_chow = [13.1897, 0.00424384,",
"6) #arch #sm_arch = smsdia.acorr_lm(res.resid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.resid,",
"Squared Error 218.61 Root Mean Squared Error 14.785 Mean Absolute",
"import os import numpy as np from numpy.testing import (assert_almost_equal,",
"res.resid, decimal=3) assert_almost_equal(lev['DFFITS'], infl.dffits[0], decimal=3) assert_almost_equal(lev['leverage'], infl.hat_matrix_diag, decimal=3) assert_almost_equal(lev['influence'], infl.influence,",
"RESET test for specification (squares and cubes) Test statistic: F",
"of order 4 - Null hypothesis: no ARCH effect is",
"is close to lag=1, and smaller ssr from statsmodels.datasets import",
"0.0735015 1.139 0.2560 uhat_4 -0.0636242 0.0737363 -0.8629 0.3893 Unadjusted R-squared",
"#assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=7) #FAIL #assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1],",
"0.264, 4, \"chi2\"] #break cusum_Harvey_Collier = [0.494432, 0.621549, 198, \"t\"]",
"as np from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose, assert_array_less) from",
"regression 10.70380 R-squared 0.676978 Adjusted R-squared 0.673731 F(2, 199) 90.79971",
"observations 1959:3-2009:3 (T = 201) Dependent variable: ds_l_realinv rho =",
"of order 4 coefficient std. error t-ratio p-value -------------------------------------------------------- alpha(0)",
"#d = g.load('5-1') #growth rates gs_l_realinv = 400 * np.diff(np.log(d['realinv'].values))",
"arch_4 = [7.30776, 0.120491, 4, \"chi2\"] #multicollinearity vif = [1.002,",
"linear_squares = [7.52477, 0.0232283, 2, \"chi2\"] #Autocorrelation, Breusch-Godfrey test for",
"uhat_1 -0.104707 0.0719948 -1.454 0.1475 uhat_2 -0.00898483 0.0742817 -0.1210 0.9039",
"''' Performing iterative calculation of rho... ITER RHO ESS 1",
"0.1294 ds_l_realgdp_1 0.660443 0.390372 1.692 0.0923 * realint_2 0.0769695 0.341527",
"residuals = 22432.8 Test of common factor restriction Test statistic:",
"and diagnostics against Gretl Created on Thu Feb 02 21:15:47",
"> 7.26849) = 0.00762 RESET test for specification (cubes only)",
"1.17709 -8.055 7.17e-014 *** ds_l_realgdp 4.37422 0.328787 13.30 2.62e-029 ***",
"smsdia.het_arch(res.resid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=5) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) vif2 =",
"4, \"chi2\"] #break cusum_Harvey_Collier = [0.494432, 0.621549, 198, \"t\"] #stats.t.sf(0.494432,",
"= os.path.abspath(os.path.dirname(__file__)) fpath = os.path.join(cur_dir, 'results/leverage_influence_ols_nostars.txt') lev = np.genfromtxt(fpath, skip_header=3,",
"= smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=1) assert_almost_equal(sm_arch[1], arch_4[1], decimal=2) '''",
"condition number = 0.013819244 ''' ''' Test for ARCH of",
"nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=5) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) vif2 = [oi.variance_inflation_factor(res.model.exog,",
"based on the rho-differenced data: result_gretl_g1 = dict( endog_mean =",
"assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=4) #not in gretl assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=6) #FAIL",
"= (\"Mean dependent var\", 3.113973), endog_std = (\"S.D. dependent var\",",
"cubes) Test statistic: F = 5.219019, with p-value = P(F(2,197)",
"= -0.108136 # coefficient std. error t-ratio p-value 95% CONFIDENCE",
"variable: uhat^2 coefficient std. error t-ratio p-value ------------------------------------------------------------- const 104.920",
"18.67447), ssr = (\"Sum squared resid\", 22530.90), mse_resid_sqrt = (\"S.E.",
"21.7027 0.4924 0.6230 ds_l_realgdp -3.64704 4.36075 -0.8363 0.4040 realint_1 0.463643",
"\"chi2\"] #for logs: dropping 70 nan or incomplete observations, T=133",
"linear_squares[0], decimal=6) assert_almost_equal(linear_sq[1], linear_squares[1], decimal=7) hbpk = smsdia.het_breuschpagan(res.resid, res.model.exog) assert_almost_equal(hbpk[0],",
"other[4]) class TestGLSARGretl: def test_all(self): d = macrodata.load_pandas().data #import datasetswsm.greene",
"[-0.579253, 0.268009, -2.161, 0.0319, -1.10777, -0.0507346]]) # ** #Statistics based",
"with p-value = P(Chi-square(2) > 1.68351) = 0.430953 Non-linearity test",
"[4.37422, 0.328787, 13.30, 2.62e-029, 3.72587, 5.02258], #*** [-0.613997, 0.293619, -2.091,",
"- Null hypothesis: error is normally distributed Test statistic: Chi-square(2)",
"if np.isnan(lev[-1]['f1']): lev = np.genfromtxt(fpath, skip_header=3, skip_footer=2, converters={0:lambda s: s})",
"Test statistic: F = 5.219019, with p-value = P(F(2,197) >",
"HAC standard errors, bandwidth 4 (Bartlett kernel) coefficient std. error",
"= 0.487871: #ANOVA Analysis of Variance: Sum of squares df",
"-44.018178 11.429236 -66.556135 - -21.480222 2009:2 -27.024588 -12.284842 10.798554 -33.579120",
"alpha(4) 0.0384531 0.0725763 0.5298 0.5968 Null hypothesis: no ARCH effect",
"= 7.30776 with p-value = P(Chi-square(4) > 7.30776) = 0.120491",
"202) Dependent variable: uhat^2 coefficient std. error t-ratio p-value -------------------------------------------------------------",
"= (\"S.D. dependent var\", 18.73915), ssr = (\"Sum squared resid\",",
"of squares = 2.60403 Test statistic: LM = 1.302014, with",
"the multiple correlation coefficient between variable j and the other",
"S.E. of regression 10.70380 R-squared 0.676978 Adjusted R-squared 0.673731 F(2,",
"2.213805 QLR test for structural break - Null hypothesis: no",
"> 1.68351) = 0.430953 Non-linearity test (squares) - Null hypothesis:",
"0.328787 13.30 2.62e-029 *** realint_1 -0.613997 0.293619 -2.091 0.0378 **",
"-58.234939 - -14.353928 2009:1 -70.239280 -44.018178 11.429236 -66.556135 - -21.480222",
"P(Chi-square(5) > 33.503723) = 0.000003: #heteroscedasticity Breusch-Pagan (original) Breusch-Pagan test",
"22799.68 S.E. of regression 10.70380 R-squared 0.676978 Adjusted R-squared 0.673731",
"variant) coefficient std. error t-ratio p-value ------------------------------------------------------------ const 10.6870 21.7027",
"for normality of residual - Null hypothesis: error is normally",
"70582.3 201 351.156 R^2 = 47782.7 / 70582.3 = 0.676978",
"up to order 4 lm_acorr4 = [1.17928, 0.321197, 4, 195,",
"''' Test for ARCH of order 4 coefficient std. error",
"[ 4.37040, 0.208146, 21.00, 2.93e-052, 3.95993, 4.78086], # *** [-0.579253,",
"(squares only) Test statistic: F = 7.268492, with p-value =",
"[-9.50990, 0.990456, -9.602, 3.65e-018, -11.4631, -7.55670], # *** [ 4.37040,",
"Durbin-Watson 2.213805 QLR test for structural break - Null hypothesis:",
"0.709924) = 0.701200 ########## forecast #forecast mean y For 95%",
"Unadjusted R-squared = 0.023619 Test statistic: LMF = 1.179281, with",
"independent variables Properties of matrix X'X: 1-norm = 6862.0664 Determinant",
"CONFIDENCE INTERVAL #for confidence interval t(199, 0.025) = 1.972 partable",
"= GLSAR(g_inv, exogg, 1) res1 = mod1.iterative_fit(5) mod4 = GLSAR(g_inv,",
"= smsdia.het_breuschpagan(res.resid, res.model.exog) assert_almost_equal(hbpk[0], het_breusch_pagan_konker[0], decimal=6) assert_almost_equal(hbpk[1], het_breusch_pagan_konker[1], decimal=6) hw",
"Dependent variable: uhat coefficient std. error t-ratio p-value ------------------------------------------------------------ const",
"Dependent variable: scaled uhat^2 coefficient std. error t-ratio p-value -------------------------------------------------------------",
"LM = 7.52477 with p-value = P(Chi-square(2) > 7.52477) =",
"= 1.68351 with p-value = P(Chi-square(2) > 1.68351) = 0.430953",
"-0.2098 0.8341 realint_1 0.0511769 0.293136 0.1746 0.8616 uhat_1 -0.104707 0.0719948",
"= 202) Dependent variable: scaled uhat^2 (Koenker robust variant) coefficient",
"2, 197, \"f\"] reset_2 = [7.268492, 0.00762, 1, 198, \"f\"]",
"with p-value = 0.653468 ''' ################ with OLS, HAC errors",
"rsquared = (\"R-squared\", 0.676973), rsquared_adj = (\"Adjusted R-squared\", 0.673710), fvalue",
"p-value = P(F(1,198) > 5.24895) = 0.023 #heteroscedasticity White White's",
"-*- \"\"\"Tests of GLSAR and diagnostics against Gretl Created on",
"assert_array_less) from statsmodels.regression.linear_model import OLS, GLSAR from statsmodels.tools.tools import add_constant",
"> 1.302014) = 0.521520 #heteroscedasticity Breusch-Pagan Koenker Breusch-Pagan test for",
"198, \"f\"] #not available cond_1norm = 5984.0525 determinant = 7.1087467e+008",
"= [oi.variance_inflation_factor(res.model.exog, k) for k in [1,2]] infl = oi.OLSInfluence(res_ols)",
"as sw import statsmodels.stats.diagnostic as smsdia import statsmodels.stats.outliers_influence as oi",
"- -14.353928 2009:1 -70.239280 -44.018178 11.429236 -66.556135 - -21.480222 2009:2",
"of Variance: Sum of squares df Mean square Regression 47782.7",
"/ 70582.3 = 0.676978 F(2, 199) = 23891.3 / 114.571",
"221.0475 P-value(F) 3.56e-51 rho -0.003481 Durbin-Watson 1.993858 ''' ''' RESET",
"201) Dependent variable: ds_l_realinv coefficient std. error t-ratio p-value ---------------------------------------------------------------",
"t-ratio p-value 95% CONFIDENCE INTERVAL #for confidence interval t(199, 0.025)",
"-0.0349939]]) # ** result_gretl_g1 = dict( endog_mean = (\"Mean dependent",
"skip_header=3, skip_footer=1, converters={0:lambda s: s}) #either numpy 1.6 or python",
"GLSAR(g_inv, exogg, 1) res1 = mod1.iterative_fit(5) mod4 = GLSAR(g_inv, exogg,",
"interval 2008:3 -7.134492 -17.177905 2.946312 -22.987904 - -11.367905 2008:4 -27.665860",
"0.321197 CUSUM test for parameter stability - Null hypothesis: no",
"0.023: ''' ''' Test for ARCH of order 4 coefficient",
"OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable: ds_l_realinv",
"4, \"chi2\"] #multicollinearity vif = [1.002, 1.002] cond_1norm = 6862.0664",
"d = macrodata.load_pandas().data #import datasetswsm.greene as g #d = g.load('5-1')",
"[1,2]] infl = oi.OLSInfluence(res_ols) #print np.max(np.abs(lev['DFFITS'] - infl.dffits[0])) #print np.max(np.abs(lev['leverage']",
"(Bartlett kernel) coefficient std. error t-ratio p-value ------------------------------------------------------------- const -9.48167",
"= np.genfromtxt(fpath, skip_header=3, skip_footer=2, converters={0:lambda s: s}) lev.dtype.names = names",
"#tests res = res_g1 #with rho from Gretl #basic assert_almost_equal(res.params,",
"\"\"\" import os import numpy as np from numpy.testing import",
"hypothesis: no structural break Asymptotic test statistic: Chi-square(3) = 13.1897",
"t-ratio p-value 95% CONFIDENCE INTERVAL partable = np.array([ [-9.50990, 0.990456,",
"statistic: F = 5.248951, with p-value = P(F(1,198) > 5.24895)",
"of squares df Mean square Regression 47782.7 2 23891.3 Residual",
"= [7.52477, 0.0232283, 2, \"chi2\"] #Autocorrelation, Breusch-Godfrey test for autocorrelation",
"statistic: Chi-square(2) = 20.2792 with p-value = 3.94837e-005: ''' #no",
"Error -3.7387 Mean Squared Error 218.61 Root Mean Squared Error",
"partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=7) #not in",
"decimal=6) assert_almost_equal(hbpk[1], het_breusch_pagan_konker[1], decimal=6) hw = smsdia.het_white(res.resid, res.model.exog) assert_almost_equal(hw[:2], het_white[:2],",
"decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=4) assert_allclose(res.f_pvalue, result_gretl_g1['f_pvalue'][1], rtol=1e-2) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7)",
"decimal=1) assert_almost_equal(sm_arch[1], arch_4[1], decimal=2) ''' Performing iterative calculation of rho...",
"1/(1 - R(j)^2), where R(j) is the multiple correlation coefficient",
"[1.001, 1.001] names = 'date residual leverage influence DFFITS'.split() cur_dir",
"ds_l_realinv prediction std. error 95% interval 2008:3 -7.134492 -17.177905 11.101892",
"statistic: LM = 1.302014, with p-value = P(Chi-square(2) > 1.302014)",
"P(Chi-square(2) > 7.52477) = 0.0232283 LM test for autocorrelation up",
"= sw.cov_hac_simple(res, nlags=4, use_correction=False) bse_hac = sw.se_cov(cov_hac) assert_almost_equal(res.params, partable[:,0], 5)",
"0.8219 Sum of squared residuals = 22432.8 Test of common",
"1), 0.03) assert_array_less(res4.ssr, res1.ssr) assert_array_less(np.abs(res4.bse / res1.bse) - 1, 0.015)",
"infl = oi.OLSInfluence(res_ols) #print np.max(np.abs(lev['DFFITS'] - infl.dffits[0])) #print np.max(np.abs(lev['leverage'] -",
"not growthrate, I want heteroscedasticity later for testing endogd =",
"1984:1 - Null hypothesis: no structural break Asymptotic test statistic:",
"test_all(self): d = macrodata.load_pandas().data #import datasetswsm.greene as g #d =",
"(\"S.E. of regression\", 10.66735), rsquared = (\"R-squared\", 0.676973), rsquared_adj =",
"#FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=0) assert_almost_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], decimal=6)",
"decimal=6) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c = oi.reset_ramsey(res, degree=2) compare_ftest(c,",
"prediction std. error 95% interval 2008:3 -7.134492 -17.177905 11.101892 -39.070353",
"c = oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(2,4)) c = oi.reset_ramsey(res,",
"no structural break Asymptotic test statistic: Chi-square(3) = 13.1897 with",
"1.972 partable = np.array([ [-9.48167, 1.17709, -8.055, 7.17e-014, -11.8029, -7.16049],",
"only) Test statistic: F = 7.268492, with p-value = P(F(1,198)",
"decimal=4) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) #tests res = res_g2 #with estimated",
"(T = 201) Dependent variable: ds_l_realinv rho = -0.108136 coefficient",
"Dependent variable: ds_l_realinv HAC standard errors, bandwidth 4 (Bartlett kernel)",
"reset_2_3, decimal=(2,4)) #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch =",
"Hannan-Quinn 1537.966 rho -0.107341 Durbin-Watson 2.213805 QLR test for structural",
"1.10919 0.5970 0.5512 Unadjusted R-squared = 0.165860 Test statistic: TR^2",
"P(Chi-square(4) > 3.43473) = 0.487871: #ANOVA Analysis of Variance: Sum",
"error t-ratio p-value 95% CONFIDENCE INTERVAL partable = np.array([ [-9.50990,",
"residual - Null hypothesis: error is normally distributed Test statistic:",
"5, \"chi2\"] het_breusch_pagan = [1.302014, 0.521520, 2, \"chi2\"] #TODO: not",
"with p-value = P(Chi-square(4) > 3.43473) = 0.487871: #ANOVA Analysis",
"9.53e-29), llf = (\"Log-likelihood\", -763.9752), aic = (\"Akaike criterion\", 1533.950),",
"[5.248951, 0.023, 1, 198, \"f\"] #LM-statistic, p-value, df arch_4 =",
"statistic: F = 5.219019, with p-value = P(F(2,197) > 5.21902)",
"3.72587, 5.02258], #*** [-0.613997, 0.293619, -2.091, 0.0378, -1.19300, -0.0349939]]) #",
"-3.64704 4.36075 -0.8363 0.4040 realint_1 0.463643 5.78202 0.08019 0.9362 Explained",
"cusum_Harvey_Collier = [0.494432, 0.621549, 198, \"t\"] #stats.t.sf(0.494432, 198)*2 #see cusum",
"400*np.diff(np.log(d2['realgdp'].values)) g_inv = 400*np.diff(np.log(d2['realinv'].values)) exogg = add_constant(np.c_[g_gdp, d2['realint'][:-1].values], prepend=False) mod1",
"rho=-0.108136) #-0.1335859) from R res_g2 = mod_g2.iterative_fit(maxiter=5) #print res_g2.params rho",
"other[3]) assert_equal(\"f\", other[4]) class TestGLSARGretl: def test_all(self): d = macrodata.load_pandas().data",
"degree=3) compare_ftest(c, reset_2_3, decimal=(2,4)) #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None)",
"= 7.1087467e+008 reciprocal_condition_number = 0.013826504 vif = [1.001, 1.001] names",
"22530.90 S.E. of regression 10.66735 R-squared 0.676973 Adjusted R-squared 0.673710",
"0.426391) = 0.653468 Test for normality of residual - Null",
"dependent var 3.113973 S.D. dependent var 18.67447 Sum squared resid",
"\"chi2\"] normality = [23.962, 0.00001, 2, \"chi2\"] het_white = [33.503723,",
"c = oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(6,5)) c = oi.reset_ramsey(res,",
"4.483669 1.315876 1.888819 - 7.078520 Forecast evaluation statistics Mean Error",
"P(Chi-square(2) > 1.302014) = 0.521520 #heteroscedasticity Breusch-Pagan Koenker Breusch-Pagan test",
"Thu Feb 02 21:15:47 2012 Author: <NAME> License: BSD-3 \"\"\"",
"-------------------------------------------------------- alpha(0) 97.0386 20.3234 4.775 3.56e-06 *** alpha(1) 0.176114 0.0714698",
"coefficient between variable j and the other independent variables Properties",
"hypothesis: no ARCH effect is present Test statistic: LM =",
"dict( endog_mean = (\"Mean dependent var\", 3.113973), endog_std = (\"S.D.",
"1.179281, with p-value = P(F(4,195) > 1.17928) = 0.321 Alternative",
"statistic: Chi-square(3) = 13.1897 with p-value = 0.00424384 Test for",
"0.4365 Bias proportion, UM 0.06394 Regression proportion, UR 0.13557 Disturbance",
"'results/leverage_influence_ols_nostars.txt') lev = np.genfromtxt(fpath, skip_header=3, skip_footer=1, converters={0:lambda s: s}) #either",
"- 1).mean()), 0.015) assert_equal(len(mod4.rho), 4) if __name__ == '__main__': t",
"maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=4) assert_almost_equal(sm_arch[1],",
"realint_1 -0.662644 0.334872 -1.979 0.0492 ** ds_l_realinv_1 -0.108892 0.0715042 -1.523",
"use_correction=False) bse_hac = sw.se_cov(cov_hac) assert_almost_equal(res.params, partable[:,0], 5) assert_almost_equal(bse_hac, partable[:,1], 5)",
"------------------------------------------------------------- const -9.48167 1.17709 -8.055 7.17e-014 *** ds_l_realgdp 4.37422 0.328787",
"degree=2) compare_ftest(c, reset_2, decimal=(6,5)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3,",
"- 1), 0.03) assert_array_less(res4.ssr, res1.ssr) assert_array_less(np.abs(res4.bse / res1.bse) - 1,",
"(T = 202) Dependent variable: scaled uhat^2 coefficient std. error",
"= [5.23587, 0.264, 4, \"chi2\"] #break cusum_Harvey_Collier = [0.494432, 0.621549,",
"p-value = P(Chi-square(4) > 5.23587) = 0.264: RESET test for",
"bandwidth 4 (Bartlett kernel) coefficient std. error t-ratio p-value -------------------------------------------------------------",
"Unadjusted R-squared = 0.165860 Test statistic: TR^2 = 33.503723, with",
"= 33174.2 Test statistic: LM = 0.709924, with p-value =",
"(cubes only) Test statistic: F = 5.248951, with p-value =",
"Breusch-Pagan test for heteroskedasticity OLS, using observations 1959:2-2009:3 (T =",
"mod4 = GLSAR(g_inv, exogg, 4) res4 = mod4.iterative_fit(10) assert_array_less(np.abs(res1.params /",
"other[2]) assert_equal(contrast_res.df_denom, other[3]) assert_equal(\"f\", other[4]) class TestGLSARGretl: def test_all(self): d",
"decimal=6) assert_almost_equal(linear_sq[1], linear_squares[1], decimal=7) hbpk = smsdia.het_breuschpagan(res.resid, res.model.exog) assert_almost_equal(hbpk[0], het_breusch_pagan_konker[0],",
"-0.003481 Durbin-Watson 1.993858 ''' ''' RESET test for specification (squares",
"no structural break Test statistic: max F(3, 196) = 3.01985",
"Null hypothesis: error is normally distributed Test statistic: Chi-square(2) =",
"> 5.23587) = 0.264: RESET test for specification (squares and",
"this, max at 2001:4 break_chow = [13.1897, 0.00424384, 3, \"chi2\"]",
"distributed Test statistic: Chi-square(2) = 20.2792 with p-value = 3.94837e-005:",
"R(j) is the multiple correlation coefficient between variable j and",
"p-value = P(Chi-square(2) > 1.68351) = 0.430953 Non-linearity test (squares)",
"-0.0507346]]) # ** #Statistics based on the rho-differenced data: result_gretl_g1",
"Adjusted R-squared 0.673731 F(2, 199) 90.79971 P-value(F) 9.53e-29 Log-likelihood -763.9752",
"= 0.023 #heteroscedasticity White White's test for heteroskedasticity OLS, using",
"squares df Mean square Regression 47782.7 2 23891.3 Residual 22799.7",
"201 351.156 R^2 = 47782.7 / 70582.3 = 0.676978 F(2,",
"smaller ssr from statsmodels.datasets import macrodata d2 = macrodata.load_pandas().data g_gdp",
"p-value ------------------------------------------------------------- const -9.48167 1.17709 -8.055 7.17e-014 *** ds_l_realgdp 4.37422",
"1.888819 - 7.078520 Forecast evaluation statistics Mean Error -3.7387 Mean",
"21:15:47 2012 Author: <NAME> License: BSD-3 \"\"\" import os import",
"infl.dffits[0])) #print np.max(np.abs(lev['leverage'] - infl.hat_matrix_diag)) #print np.max(np.abs(lev['influence'] - infl.influence)) #just",
"0.494432) = 0.621549 Chow test for structural break at observation",
"4.007017 -51.919841 - -36.116516 2009:2 -27.024588 -12.284842 1.427414 -15.099640 -",
"P(Chi-square(2) > 1.68351) = 0.430953 Non-linearity test (squares) - Null",
"Gretl Created on Thu Feb 02 21:15:47 2012 Author: <NAME>",
"------------------------------------------------------------- const 1.09468 0.192281 5.693 4.43e-08 *** ds_l_realgdp -0.0323119 0.0386353",
"ARCH effect is present Test statistic: LM = 7.30776 with",
"6) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=7)",
"White White's test for heteroskedasticity OLS, using observations 1959:2-2009:3 (T",
"4.714544 2008:4 -27.665860 -36.294434 11.126262 -58.234939 - -14.353928 2009:1 -70.239280",
"other, decimal=(5,4)): assert_almost_equal(contrast_res.fvalue, other[0], decimal=decimal[0]) assert_almost_equal(contrast_res.pvalue, other[1], decimal=decimal[1]) assert_equal(contrast_res.df_num, other[2])",
"assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=0) assert_almost_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], decimal=6) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO",
"-1.523 0.1294 ds_l_realgdp_1 0.660443 0.390372 1.692 0.0923 * realint_2 0.0769695",
"res_ols = OLS(endogg, exogg).fit() #print res_ols.params mod_g1 = GLSAR(endogg, exogg,",
"the other independent variables Properties of matrix X'X: 1-norm =",
"autocorrelation up to order 4 lm_acorr4 = [1.17928, 0.321197, 4,",
"test-statistic, pvalue, df normality = [20.2792, 3.94837e-005, 2] #tests res",
"= 33.503723, with p-value = P(Chi-square(5) > 33.503723) = 0.000003:",
"correlation coefficient between variable j and the other independent variables",
"test (logs) - Null hypothesis: relationship is linear Test statistic:",
"#estimated lag coefficient assert_almost_equal(res.model.rho, rho, decimal=3) #basic assert_almost_equal(res.params, partable[:,0], 4)",
"nlags=4, use_correction=False) bse_hac = sw.se_cov(cov_hac) assert_almost_equal(res.params, partable[:,0], 5) assert_almost_equal(bse_hac, partable[:,1],",
"statistics Mean Error -3.7387 Mean Squared Error 218.61 Root Mean",
"errors #Model 5: OLS, using observations 1959:2-2009:3 (T = 202)",
"decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=0) assert_almost_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1],",
"sq_ds_l_realg 4.12054 0.684920 6.016 8.62e-09 *** X2_X3 2.89685 1.38571 2.091",
"= smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0],",
"0.390372 1.692 0.0923 * realint_2 0.0769695 0.341527 0.2254 0.8219 Sum",
"exogg, rho=-0.108136) res_g1 = mod_g1.fit() #print res_g1.params mod_g2 = GLSAR(endogg,",
"0.264: RESET test for specification (squares and cubes) Test statistic:",
"assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=4) assert_allclose(res.f_pvalue, result_gretl_g1['f_pvalue'][1], rtol=1e-2) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO",
"= 400 * np.diff(np.log(d['realgdp'].values)) #simple diff, not growthrate, I want",
"of residual - Null hypothesis: error is normally distributed Test",
"diff, not growthrate, I want heteroscedasticity later for testing endogd",
"realint_1 -6.93102 6.95607 -0.9964 0.3203 sq_ds_l_realg 4.12054 0.684920 6.016 8.62e-09",
"-33.579120 - 9.009436 2009:3 8.078897 4.483669 10.784377 -16.782652 - 25.749991",
"fvalue = (\"F(2, 199)\", 90.79971), f_pvalue = (\"P-value(F)\", 9.53e-29), llf",
"5.24895) = 0.023: ''' ''' Test for ARCH of order",
"import statsmodels.stats.diagnostic as smsdia import statsmodels.stats.outliers_influence as oi def compare_ftest(contrast_res,",
"Null hypothesis: relationship is linear Test statistic: LM = 7.52477",
"= 0.00424384 Test for ARCH of order 4 - Null",
"= (\"R-squared\", 0.676973), rsquared_adj = (\"Adjusted R-squared\", 0.673710), fvalue =",
"Cochrane-Orcutt, using observations 1959:3-2009:3 (T = 201) Dependent variable: ds_l_realinv",
"(logs) - Null hypothesis: relationship is linear Test statistic: LM",
"''' ''' Variance Inflation Factors Minimum possible value = 1.0",
"[oi.variance_inflation_factor(res.model.exog, k) for k in [1,2]] infl = oi.OLSInfluence(res_ols) #print",
"1.38571 2.091 0.0379 ** sq_realint_1 0.662135 1.10919 0.5970 0.5512 Unadjusted",
"oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(2,4)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c,",
"sw.se_cov(cov_hac) assert_almost_equal(res.params, partable[:,0], 5) assert_almost_equal(bse_hac, partable[:,1], 5) #TODO assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1],",
"(\"Mean dependent var\", 3.113973), endog_std = (\"S.D. dependent var\", 18.67447),",
"Properties of matrix X'X: 1-norm = 6862.0664 Determinant = 1.0296049e+009",
"rough test, low decimal in Gretl output, assert_almost_equal(lev['residual'], res.resid, decimal=3)",
"- infl.hat_matrix_diag)) #print np.max(np.abs(lev['influence'] - infl.influence)) #just added this based",
"Error 12.646 Mean Percentage Error -7.1173 Mean Absolute Percentage Error",
"leverage influence DFFITS'.split() cur_dir = os.path.abspath(os.path.dirname(__file__)) fpath = os.path.join(cur_dir, 'results/leverage_influence_ols_nostars.txt')",
"error t-ratio p-value -------------------------------------------------------- alpha(0) 97.0386 20.3234 4.775 3.56e-06 ***",
"2.62e-029 *** realint_1 -0.613997 0.293619 -2.091 0.0378 ** Mean dependent",
"= 0.120491 Test of common factor restriction - Null hypothesis:",
"Test of common factor restriction - Null hypothesis: restriction is",
"actual y For 95% confidence intervals, t(199, 0.025) = 1.972",
"no autocorrelation Test statistic: LMF = 1.17928 with p-value =",
"and cubes) Test statistic: F = 5.219019, with p-value =",
"= res_g2 #with estimated rho #estimated lag coefficient assert_almost_equal(res.model.rho, rho,",
"0.015) assert_equal(len(mod4.rho), 4) if __name__ == '__main__': t = TestGLSARGretl()",
"with p-value = P(F(4,195) > 1.17928) = 0.321 Alternative statistic:",
"decimal=0) #FAIL #assert_approx_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], significant=1) #FAIL #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO",
"0.06394 Regression proportion, UR 0.13557 Disturbance proportion, UD 0.80049 '''",
"numpy.testing import (assert_almost_equal, assert_equal, assert_allclose, assert_array_less) from statsmodels.regression.linear_model import OLS,",
"decimal=3) assert_almost_equal(lev['influence'], infl.influence, decimal=4) def test_GLSARlag(): #test that results for",
"VIF(j) = 1/(1 - R(j)^2), where R(j) is the multiple",
"02 21:15:47 2012 Author: <NAME> License: BSD-3 \"\"\" import os",
"-70.239280 -44.018178 4.007017 -51.919841 - -36.116516 2009:2 -27.024588 -12.284842 1.427414",
"10.0 may indicate a collinearity problem ds_l_realgdp 1.002 realint_1 1.002",
"coefficient std. error t-ratio p-value ------------------------------------------------------------- const -9.48167 1.17709 -8.055",
"0.0719948 -1.454 0.1475 uhat_2 -0.00898483 0.0742817 -0.1210 0.9039 uhat_3 0.0837332",
"Test statistic: max F(3, 196) = 3.01985 at observation 2001:4",
"> 3.43473) = 0.487871: #ANOVA Analysis of Variance: Sum of",
"S.E. of regression 10.66735 R-squared 0.676973 Adjusted R-squared 0.673710 F(2,",
"for ARCH of order 4 - Null hypothesis: no ARCH",
"from statsmodels.datasets import macrodata d2 = macrodata.load_pandas().data g_gdp = 400*np.diff(np.log(d2['realgdp'].values))",
"5.248951, with p-value = P(F(1,198) > 5.24895) = 0.023 #heteroscedasticity",
"decimal=6) #FAIL assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=6) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) #f-value",
"0.3893 Unadjusted R-squared = 0.023619 Test statistic: LMF = 1.179281,",
"resid 22530.90 S.E. of regression 10.66735 R-squared 0.676973 Adjusted R-squared",
"= (\"R-squared\", 0.676978), rsquared_adj = (\"Adjusted R-squared\", 0.673731), fvalue =",
"0.0724981 -0.6736 0.5014 alpha(3) -0.0705413 0.0737058 -0.9571 0.3397 alpha(4) 0.0384531",
"= oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(6,5)) c = oi.reset_ramsey(res, degree=3)",
"Test statistic: LMF = 1.17928 with p-value = P(F(4,195) >",
"import statsmodels.stats.sandwich_covariance as sw import statsmodels.stats.diagnostic as smsdia import statsmodels.stats.outliers_influence",
"df arch_4 = [7.30776, 0.120491, 4, \"chi2\"] #multicollinearity vif =",
"= P(Chi-square(4) > 7.30776) = 0.120491: ''' ''' Variance Inflation",
"Asymptotic test statistic: Chi-square(3) = 13.1897 with p-value = 0.00424384",
"aic = (\"Akaike criterion\", 1533.950), bic = (\"Schwarz criterion\", 1543.875),",
"variable: scaled uhat^2 (Koenker robust variant) coefficient std. error t-ratio",
"variable: ds_l_realinv coefficient std. error t-ratio p-value --------------------------------------------------------------- const -10.9481",
"> 5.21902) = 0.00619 RESET test for specification (squares only)",
"------------------------------------------------------------ const 10.6870 21.7027 0.4924 0.6230 ds_l_realgdp -3.64704 4.36075 -0.8363",
"0.676978 Adjusted R-squared 0.673731 F(2, 199) 90.79971 P-value(F) 9.53e-29 Log-likelihood",
"0.00424384, 3, \"chi2\"] # break at 1984:1 arch_4 = [3.43473,",
"decimal=6) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) #f-value is based on cov_hac",
"400 * np.diff(np.log(d['realgdp'].values)) #simple diff, not growthrate, I want heteroscedasticity",
"0.013819244 ''' ''' Test for ARCH of order 4 -",
"#print res_ols.params mod_g1 = GLSAR(endogg, exogg, rho=-0.108136) res_g1 = mod_g1.fit()",
"reciprocal_condition_number = 0.013819244 #Chi-square(2): test-statistic, pvalue, df normality = [20.2792,",
"std. error 95% interval 2008:3 -7.134492 -17.177905 11.101892 -39.070353 -",
"# *** [-0.579253, 0.268009, -2.161, 0.0319, -1.10777, -0.0507346]]) # **",
"import add_constant from statsmodels.datasets import macrodata import statsmodels.stats.sandwich_covariance as sw",
"def test_all(self): d = macrodata.load_pandas().data #import datasetswsm.greene as g #d",
"is the multiple correlation coefficient between variable j and the",
"= oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(2,4)) c = oi.reset_ramsey(res, degree=3)",
"Factors Minimum possible value = 1.0 Values > 10.0 may",
"variable: ds_l_realinv HAC standard errors, bandwidth 4 (Bartlett kernel) coefficient",
"33174.2 Test statistic: LM = 0.709924, with p-value = P(Chi-square(2)",
"> 1.17928) = 0.321 Alternative statistic: TR^2 = 4.771043, with",
"95% CONFIDENCE INTERVAL partable = np.array([ [-9.50990, 0.990456, -9.602, 3.65e-018,",
"with p-value = P(F(1,198) > 5.24895) = 0.023: ''' '''",
"decimal=3) #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 3) assert_almost_equal(res.tvalues, partable[:,2],",
"= 400*np.diff(np.log(d2['realgdp'].values)) g_inv = 400*np.diff(np.log(d2['realinv'].values)) exogg = add_constant(np.c_[g_gdp, d2['realint'][:-1].values], prepend=False)",
"> 0.494432) = 0.621549 Chow test for structural break at",
"47782.7 / 70582.3 = 0.676978 F(2, 199) = 23891.3 /",
"Mean Squared Error 218.61 Root Mean Squared Error 14.785 Mean",
"s: s}) #either numpy 1.6 or python 3.2 changed behavior",
"70 nan or incomplete observations, T=133 #(res_ols.model.exog <=0).any(1).sum() = 69",
"common factor restriction Test statistic: F(2, 195) = 0.426391, with",
"0.621549 Chow test for structural break at observation 1984:1 -",
"400*np.diff(np.log(d2['realinv'].values)) exogg = add_constant(np.c_[g_gdp, d2['realint'][:-1].values], prepend=False) mod1 = GLSAR(g_inv, exogg,",
"= oi.OLSInfluence(res_ols) #print np.max(np.abs(lev['DFFITS'] - infl.dffits[0])) #print np.max(np.abs(lev['leverage'] - infl.hat_matrix_diag))",
"198, \"f\"] reset_3 = [5.248951, 0.023, 1, 198, \"f\"] #LM-statistic,",
"1.0296049e+009 Reciprocal condition number = 0.013819244 ''' ''' Test for",
"#test that results for lag>1 is close to lag=1, and",
"using observations 1959:3-2009:3 (T = 201) Dependent variable: ds_l_realinv coefficient",
"(\"rho\", -0.107341), dw = (\"Durbin-Watson\", 2.213805)) linear_logs = [1.68351, 0.430953,",
"Durbin-Watson 1.993858 ''' ''' RESET test for specification (squares and",
"squared resid 22799.68 S.E. of regression 10.70380 R-squared 0.676978 Adjusted",
"UD 0.80049 #forecast actual y For 95% confidence intervals, t(199,",
"7.30776 with p-value = P(Chi-square(4) > 7.30776) = 0.120491: '''",
"0.229459 18.69 2.40e-045 *** realint_1 -0.662644 0.334872 -1.979 0.0492 **",
"0.0384531 0.0725763 0.5298 0.5968 Null hypothesis: no ARCH effect is",
"#Statistics based on the rho-differenced data: result_gretl_g1 = dict( endog_mean",
"6862.0664 Determinant = 1.0296049e+009 Reciprocal condition number = 0.013819244 '''",
"22530.9 2 -0.10814 22530.9 Model 4: Cochrane-Orcutt, using observations 1959:3-2009:3",
"#FAIL #assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1],",
"0.653468 Test for normality of residual - Null hypothesis: error",
"2] #tests res = res_g1 #with rho from Gretl #basic",
"22432.8 Test of common factor restriction Test statistic: F(2, 195)",
"growthrate, I want heteroscedasticity later for testing endogd = np.diff(d['realinv'])",
"np from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose, assert_array_less) from statsmodels.regression.linear_model",
"-36.294434 3.036851 -42.282972 - -30.305896 2009:1 -70.239280 -44.018178 4.007017 -51.919841",
"= [1.001, 1.001] names = 'date residual leverage influence DFFITS'.split()",
"218.61 Root Mean Squared Error 14.785 Mean Absolute Error 12.646",
"assert_almost_equal(lev['DFFITS'], infl.dffits[0], decimal=3) assert_almost_equal(lev['leverage'], infl.hat_matrix_diag, decimal=3) assert_almost_equal(lev['influence'], infl.influence, decimal=4) def",
"2 -0.10814 22530.9 Model 4: Cochrane-Orcutt, using observations 1959:3-2009:3 (T",
"decimal=2) ''' Performing iterative calculation of rho... ITER RHO ESS",
"res.model.exog) assert_almost_equal(hw[:2], het_white[:2], 6) #arch #sm_arch = smsdia.acorr_lm(res.resid**2, maxlag=4, autolag=None)",
"up to order 4 - Null hypothesis: no autocorrelation Test",
"res_g1.params mod_g2 = GLSAR(endogg, exogg, rho=-0.108136) #-0.1335859) from R res_g2",
"1543.875), hqic = (\"Hannan-Quinn\", 1537.966), resid_acf1 = (\"rho\", -0.107341), dw",
"- Null hypothesis: no structural break Test statistic: max F(3,",
"break Test statistic: max F(3, 196) = 3.01985 at observation",
"P(t(198) > 0.494432) = 0.621549 Chow test for structural break",
"coefficient std. error t-ratio p-value ------------------------------------------------------------ const 10.6870 21.7027 0.4924",
"std. error t-ratio p-value ------------------------------------------------------------ const 0.0640964 1.06719 0.06006 0.9522",
"squared resid 22530.90 S.E. of regression 10.66735 R-squared 0.676973 Adjusted",
"= dict( endog_mean = (\"Mean dependent var\", 3.257395), endog_std =",
"common factor test OLS, using observations 1959:3-2009:3 (T = 201)",
"hypothesis: relationship is linear Test statistic: LM = 7.52477 with",
"specification (squares only) Test statistic: F = 7.268492, with p-value",
"TestGLSARGretl: def test_all(self): d = macrodata.load_pandas().data #import datasetswsm.greene as g",
"[4.771043, 0.312, 4, \"chi2\"] acorr_ljungbox4 = [5.23587, 0.264, 4, \"chi2\"]",
"at observation 2001:4 (10 percent critical value = 4.09) Non-linearity",
"res.get_robustcov_results(cov_type='HC1') # TODO: fvalue differs from Gretl, trying any of",
"partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 3) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1],",
"20.2792 with p-value = 3.94837e-005: ''' #no idea what this",
"U 0.4365 Bias proportion, UM 0.06394 Regression proportion, UR 0.13557",
"#assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=0)",
"numpy as np from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose, assert_array_less)",
"\"chi2\"] reset_2_3 = [5.219019, 0.00619, 2, 197, \"f\"] reset_2 =",
"------------------------------------------------------------- const 104.920 21.5848 4.861 2.39e-06 *** ds_l_realgdp -29.7040 6.24983",
"ssr = (\"Sum squared resid\", 22530.90), mse_resid_sqrt = (\"S.E. of",
"2.464 0.0146 ** alpha(2) -0.0488339 0.0724981 -0.6736 0.5014 alpha(3) -0.0705413",
"5.23587, with p-value = P(Chi-square(4) > 5.23587) = 0.264: RESET",
"OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable: uhat",
"P(F(1,198) > 5.24895) = 0.023: ''' ''' Test for ARCH",
"arch_4[0], decimal=1) assert_almost_equal(sm_arch[1], arch_4[1], decimal=2) ''' Performing iterative calculation of",
"R(j)^2), where R(j) is the multiple correlation coefficient between variable",
"test_GLSARlag(): #test that results for lag>1 is close to lag=1,",
"t-ratio p-value ------------------------------------------------------------ const 0.0640964 1.06719 0.06006 0.9522 ds_l_realgdp -0.0456010",
"ds_l_realinv prediction std. error 95% interval 2008:3 -7.134492 -17.177905 2.946312",
"proportion, UM 0.06394 Regression proportion, UR 0.13557 Disturbance proportion, UD",
"208.528 [p-value 1.47e-049] #LM-test autocorrelation Breusch-Godfrey test for autocorrelation up",
"22799.7 199 114.571 Total 70582.3 201 351.156 R^2 = 47782.7",
"d2 = macrodata.load_pandas().data g_gdp = 400*np.diff(np.log(d2['realgdp'].values)) g_inv = 400*np.diff(np.log(d2['realinv'].values)) exogg",
"Augmented regression for common factor test OLS, using observations 1959:3-2009:3",
"of squares = 33174.2 Test statistic: LM = 0.709924, with",
"(assert_almost_equal, assert_equal, assert_allclose, assert_array_less) from statsmodels.regression.linear_model import OLS, GLSAR from",
"#with estimated rho #estimated lag coefficient assert_almost_equal(res.model.rho, rho, decimal=3) #basic",
"1959:2-2009:3 (T = 202) Dependent variable: ds_l_realinv HAC standard errors,",
"from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose, assert_array_less) from statsmodels.regression.linear_model import",
"cov_hac = sw.cov_hac_simple(res, nlags=4, use_correction=False) bse_hac = sw.se_cov(cov_hac) assert_almost_equal(res.params, partable[:,0],",
"sw import statsmodels.stats.diagnostic as smsdia import statsmodels.stats.outliers_influence as oi def",
"= (\"S.E. of regression\", 10.70380), rsquared = (\"R-squared\", 0.676978), rsquared_adj",
"of matrix X'X: 1-norm = 6862.0664 Determinant = 1.0296049e+009 Reciprocal",
"= (\"Durbin-Watson\", 1.993858)) #fstatistic, p-value, df1, df2 reset_2_3 = [5.219019,",
"Test for ARCH of order 4 - Null hypothesis: no",
"= 0.0232283 LM test for autocorrelation up to order 4",
"\"chi2\"] #Autocorrelation, Breusch-Godfrey test for autocorrelation up to order 4",
"observations 1959:2-2009:3 (T = 202) Dependent variable: uhat^2 coefficient std.",
"confidence intervals, t(199, 0.025) = 1.972 Obs ds_l_realinv prediction std.",
"1.002 VIF(j) = 1/(1 - R(j)^2), where R(j) is the",
"error is normally distributed Test statistic: Chi-square(2) = 20.2792 with",
"1533.950 Schwarz criterion 1543.875 Hannan-Quinn 1537.966 rho -0.107341 Durbin-Watson 2.213805",
"0.9522 ds_l_realgdp -0.0456010 0.217377 -0.2098 0.8341 realint_1 0.0511769 0.293136 0.1746",
"-51.919841 - -36.116516 2009:2 -27.024588 -12.284842 1.427414 -15.099640 - -9.470044",
"0.208146, 21.00, 2.93e-052, 3.95993, 4.78086], # *** [-0.579253, 0.268009, -2.161,",
"Mean Absolute Percentage Error -43.867 Theil's U 0.4365 Bias proportion,",
"2.39e-06 *** ds_l_realgdp -29.7040 6.24983 -4.753 3.88e-06 *** realint_1 -6.93102",
"error 95% interval 2008:3 -7.134492 -17.177905 2.946312 -22.987904 - -11.367905",
"rho -0.003481 Durbin-Watson 1.993858 ''' ''' RESET test for specification",
"linear Test statistic: LM = 1.68351 with p-value = P(Chi-square(2)",
"converters={0:lambda s: s}) lev.dtype.names = names res = res_ols #for",
"- 1, 0.015) assert_array_less(np.abs((res4.fittedvalues / res1.fittedvalues - 1).mean()), 0.015) assert_equal(len(mod4.rho),",
"results for lag>1 is close to lag=1, and smaller ssr",
"the HCx #assert_almost_equal(res2.fvalue, result_gretl_g1['fvalue'][1], decimal=0) #FAIL #assert_approx_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], significant=1) #FAIL",
"#import datasetswsm.greene as g #d = g.load('5-1') #growth rates gs_l_realinv",
"uhat coefficient std. error t-ratio p-value ------------------------------------------------------------ const 0.0640964 1.06719",
"dependent var\", 3.113973), endog_std = (\"S.D. dependent var\", 18.67447), ssr",
"F = 5.248951, with p-value = P(F(1,198) > 5.24895) =",
"statistic: TR^2 = 4.771043, with p-value = P(Chi-square(4) > 4.77104)",
"33.503723, with p-value = P(Chi-square(5) > 33.503723) = 0.000003: #heteroscedasticity",
"OLS, HAC errors #Model 5: OLS, using observations 1959:2-2009:3 (T",
"#not in gretl #assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=7) #FAIL #assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=7)",
"0.268009, -2.161, 0.0319, -1.10777, -0.0507346]]) # ** #Statistics based on",
"-39.070353 - 4.714544 2008:4 -27.665860 -36.294434 11.126262 -58.234939 - -14.353928",
"specification (cubes only) Test statistic: F = 5.248951, with p-value",
"OLS, using observations 1959:3-2009:3 (T = 201) Dependent variable: ds_l_realinv",
"assert_array_less(res4.ssr, res1.ssr) assert_array_less(np.abs(res4.bse / res1.bse) - 1, 0.015) assert_array_less(np.abs((res4.fittedvalues /",
"5: OLS, using observations 1959:2-2009:3 (T = 202) #Dependent variable:",
"with p-value = P(Chi-square(4) > 4.77104) = 0.312 Ljung-Box Q'",
"21.00 2.93e-052 *** realint_1 -0.579253 0.268009 -2.161 0.0319 ** Statistics",
"ds_l_realgdp -0.0456010 0.217377 -0.2098 0.8341 realint_1 0.0511769 0.293136 0.1746 0.8616",
"ssr = (\"Sum squared resid\", 22799.68), mse_resid_sqrt = (\"S.E. of",
"= smsdia.linear_lm(res.resid, res.model.exog) assert_almost_equal(linear_sq[0], linear_squares[0], decimal=6) assert_almost_equal(linear_sq[1], linear_squares[1], decimal=7) hbpk",
"sw.cov_hac_simple(res, nlags=4, use_correction=False) bse_hac = sw.se_cov(cov_hac) assert_almost_equal(res.params, partable[:,0], 5) assert_almost_equal(bse_hac,",
"-0.10814 22530.9 Model 4: Cochrane-Orcutt, using observations 1959:3-2009:3 (T =",
"\"chi2\"] # break at 1984:1 arch_4 = [3.43473, 0.487871, 4,",
"= (\"Adjusted R-squared\", 0.673731), fvalue = (\"F(2, 199)\", 90.79971), f_pvalue",
"rsquared_adj = (\"Adjusted R-squared\", 0.673710), fvalue = (\"F(2, 198)\", 221.0475),",
"8.078897 4.483669 10.784377 -16.782652 - 25.749991 Forecast evaluation statistics Mean",
"18.67447 Sum squared resid 22530.90 S.E. of regression 10.66735 R-squared",
"Explained sum of squares = 2.60403 Test statistic: LM =",
"rho #estimated lag coefficient assert_almost_equal(res.model.rho, rho, decimal=3) #basic assert_almost_equal(res.params, partable[:,0],",
"het_white[:2], 6) #arch #sm_arch = smsdia.acorr_lm(res.resid**2, maxlag=4, autolag=None) sm_arch =",
"= sw.se_cov(cov_hac) assert_almost_equal(res.params, partable[:,0], 5) assert_almost_equal(bse_hac, partable[:,1], 5) #TODO assert_almost_equal(res.ssr,",
"196) = 3.01985 at observation 2001:4 (10 percent critical value",
"from statsmodels.tools.tools import add_constant from statsmodels.datasets import macrodata import statsmodels.stats.sandwich_covariance",
"0.06394 Regression proportion, UR 0.13557 Disturbance proportion, UD 0.80049 #forecast",
"-36.294434 11.126262 -58.234939 - -14.353928 2009:1 -70.239280 -44.018178 11.429236 -66.556135",
"later for testing endogd = np.diff(d['realinv']) exogd = add_constant(np.c_[np.diff(d['realgdp'].values), d['realint'][:-1].values])",
"rho-differenced data: result_gretl_g1 = dict( endog_mean = (\"Mean dependent var\",",
"hypothesis: no change in parameters Test statistic: Harvey-Collier t(198) =",
"# ** #Statistics based on the rho-differenced data: result_gretl_g1 =",
"estimated rho #estimated lag coefficient assert_almost_equal(res.model.rho, rho, decimal=3) #basic assert_almost_equal(res.params,",
"= mod_g2.iterative_fit(maxiter=5) #print res_g2.params rho = -0.108136 # coefficient std.",
"#forecast actual y For 95% confidence intervals, t(199, 0.025) =",
"order 4 OLS, using observations 1959:2-2009:3 (T = 202) Dependent",
"decimal=4) def test_GLSARlag(): #test that results for lag>1 is close",
"this is ''' Augmented regression for common factor test OLS,",
"''' ''' RESET test for specification (squares and cubes) Test",
"# TODO: fvalue differs from Gretl, trying any of the",
"0.673731 F(2, 199) 90.79971 P-value(F) 9.53e-29 Log-likelihood -763.9752 Akaike criterion",
"= [0.709924, 0.701200, 2, \"chi2\"] reset_2_3 = [5.219019, 0.00619, 2,",
"decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=7) #not in gretl #assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=7)",
"assert_almost_equal(lev['residual'], res.resid, decimal=3) assert_almost_equal(lev['DFFITS'], infl.dffits[0], decimal=3) assert_almost_equal(lev['leverage'], infl.hat_matrix_diag, decimal=3) assert_almost_equal(lev['influence'],",
"maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=1) assert_almost_equal(sm_arch[1],",
"def test_GLSARlag(): #test that results for lag>1 is close to",
"statistic: LM = 7.52477 with p-value = P(Chi-square(2) > 7.52477)",
"on the rho-differenced data: Mean dependent var 3.113973 S.D. dependent",
"normality = [23.962, 0.00001, 2, \"chi2\"] het_white = [33.503723, 0.000003,",
"\"\"\"Tests of GLSAR and diagnostics against Gretl Created on Thu",
"p-value = P(F(1,198) > 5.24895) = 0.023: ''' ''' Test",
"1543.875 Hannan-Quinn 1537.966 rho -0.107341 Durbin-Watson 2.213805 QLR test for",
"multiple correlation coefficient between variable j and the other independent",
"smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=4) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) #tests res",
"structural break at observation 1984:1 - Null hypothesis: no structural",
"gs_l_realinv exogg = add_constant(np.c_[gs_l_realgdp, d['realint'][:-1].values]) res_ols = OLS(endogg, exogg).fit() #print",
"-2.161 0.0319 ** Statistics based on the rho-differenced data: Mean",
"0.13557 Disturbance proportion, UD 0.80049 #forecast actual y For 95%",
"on Gretl #just rough test, low decimal in Gretl output,",
"Variance: Sum of squares df Mean square Regression 47782.7 2",
"Breusch-Pagan (original) Breusch-Pagan test for heteroskedasticity OLS, using observations 1959:2-2009:3",
"mean y For 95% confidence intervals, t(199, 0.025) = 1.972",
"[p-value 1.47e-049] #LM-test autocorrelation Breusch-Godfrey test for autocorrelation up to",
"= P(Chi-square(5) > 33.503723) = 0.000003: #heteroscedasticity Breusch-Pagan (original) Breusch-Pagan",
"Theil's U 0.4365 Bias proportion, UM 0.06394 Regression proportion, UR",
"cusum results in files break_qlr = [3.01985, 0.1, 3, 196,",
"add_constant(np.c_[g_gdp, d2['realint'][:-1].values], prepend=False) mod1 = GLSAR(g_inv, exogg, 1) res1 =",
"1959:2-2009:3 (T = 202) #Dependent variable: ds_l_realinv #HAC standard errors,",
"= 20.2792 with p-value = 3.94837e-005: ''' #no idea what",
"1959:3-2009:3 (T = 201) Dependent variable: ds_l_realinv coefficient std. error",
"1).mean()), 0.015) assert_equal(len(mod4.rho), 4) if __name__ == '__main__': t =",
"rho-differenced data: Mean dependent var 3.113973 S.D. dependent var 18.67447",
"assert_equal, assert_allclose, assert_array_less) from statsmodels.regression.linear_model import OLS, GLSAR from statsmodels.tools.tools",
"robust variant) coefficient std. error t-ratio p-value ------------------------------------------------------------ const 10.6870",
"0.025) = 1.972 partable = np.array([ [-9.48167, 1.17709, -8.055, 7.17e-014,",
"(\"F(2, 198)\", 221.0475), f_pvalue = (\"P-value(F)\", 3.56e-51), resid_acf1 = (\"rho\",",
"assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 3) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr,",
"(squares and cubes) Test statistic: F = 5.219019, with p-value",
"= 202) Dependent variable: scaled uhat^2 coefficient std. error t-ratio",
"0.023619 Test statistic: LMF = 1.179281, with p-value = P(F(4,195)",
"oi.OLSInfluence(res_ols) #print np.max(np.abs(lev['DFFITS'] - infl.dffits[0])) #print np.max(np.abs(lev['leverage'] - infl.hat_matrix_diag)) #print",
"as oi def compare_ftest(contrast_res, other, decimal=(5,4)): assert_almost_equal(contrast_res.fvalue, other[0], decimal=decimal[0]) assert_almost_equal(contrast_res.pvalue,",
"statistic: LMF = 1.179281, with p-value = P(F(4,195) > 1.17928)",
"import macrodata d2 = macrodata.load_pandas().data g_gdp = 400*np.diff(np.log(d2['realgdp'].values)) g_inv =",
"F(3, 196) = 3.01985 at observation 2001:4 (10 percent critical",
"to order 4 OLS, using observations 1959:2-2009:3 (T = 202)",
"= [13.1897, 0.00424384, 3, \"chi2\"] # break at 1984:1 arch_4",
"infl.influence, decimal=4) def test_GLSARlag(): #test that results for lag>1 is",
"resid\", 22799.68), mse_resid_sqrt = (\"S.E. of regression\", 10.70380), rsquared =",
"dict( endog_mean = (\"Mean dependent var\", 3.257395), endog_std = (\"S.D.",
"= 201) Dependent variable: ds_l_realinv rho = -0.108136 coefficient std.",
"copying cov_hac = sw.cov_hac_simple(res, nlags=4, use_correction=False) bse_hac = sw.se_cov(cov_hac) assert_almost_equal(res.params,",
"gs_l_realinv = 400 * np.diff(np.log(d['realinv'].values)) gs_l_realgdp = 400 * np.diff(np.log(d['realgdp'].values))",
"for common factor test OLS, using observations 1959:3-2009:3 (T =",
"c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(6,5)) linear_sq = smsdia.linear_lm(res.resid,",
"1, 0.015) assert_array_less(np.abs((res4.fittedvalues / res1.fittedvalues - 1).mean()), 0.015) assert_equal(len(mod4.rho), 4)",
"= 0.426391 with p-value = P(F(2, 195) > 0.426391) =",
"variables Properties of matrix X'X: 1-norm = 6862.0664 Determinant =",
"5) assert_almost_equal(bse_hac, partable[:,1], 5) #TODO assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) assert_almost_equal(res.llf, result_gretl_g1['llf'][1],",
"normality = [20.2792, 3.94837e-005, 2] #tests res = res_g1 #with",
"Error 14.785 Mean Absolute Error 12.646 Mean Percentage Error -7.1173",
"at 1984:1 arch_4 = [3.43473, 0.487871, 4, \"chi2\"] normality =",
"= 1.0296049e+009 Reciprocal condition number = 0.013819244 ''' ''' Test",
"White's test for heteroskedasticity OLS, using observations 1959:2-2009:3 (T =",
"result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=0) assert_almost_equal(res.f_pvalue,",
"-0.108136 coefficient std. error t-ratio p-value ------------------------------------------------------------- const -9.50990 0.990456",
"0.341527 0.2254 0.8219 Sum of squared residuals = 22432.8 Test",
"rho = -0.108136 # coefficient std. error t-ratio p-value 95%",
"= macrodata.load_pandas().data g_gdp = 400*np.diff(np.log(d2['realgdp'].values)) g_inv = 400*np.diff(np.log(d2['realinv'].values)) exogg =",
"p-value = P(Chi-square(2) > 1.302014) = 0.521520 #heteroscedasticity Breusch-Pagan Koenker",
"\"f\"] reset_2 = [7.268492, 0.00762, 1, 198, \"f\"] reset_3 =",
"Model 5: OLS, using observations 1959:2-2009:3 (T = 202) Dependent",
"1.06719 0.06006 0.9522 ds_l_realgdp -0.0456010 0.217377 -0.2098 0.8341 realint_1 0.0511769",
"= (\"F(2, 198)\", 221.0475), f_pvalue = (\"P-value(F)\", 3.56e-51), resid_acf1 =",
"= P(F(1,198) > 5.24895) = 0.023 #heteroscedasticity White White's test",
"coefficient std. error t-ratio p-value ------------------------------------------------------------- const 1.09468 0.192281 5.693",
"assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) #f-value is based on cov_hac I guess",
"#(res_ols.model.exog <=0).any(1).sum() = 69 ?not 70 linear_squares = [7.52477, 0.0232283,",
"rho=-0.108136) res_g1 = mod_g1.fit() #print res_g1.params mod_g2 = GLSAR(endogg, exogg,",
"(\"Sum squared resid\", 22799.68), mse_resid_sqrt = (\"S.E. of regression\", 10.70380),",
"decimal=(2,4)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(2,4)) #arch #sm_arch",
"bandwidth 4 (Bartlett kernel) #coefficient std. error t-ratio p-value 95%",
"Mean Absolute Error 12.646 Mean Percentage Error -7.1173 Mean Absolute",
"*** realint_1 -0.579253 0.268009 -2.161 0.0319 ** Statistics based on",
"result_gretl_g1['rsquared_adj'][1], decimal=6) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) #f-value is based on",
"observation 1984:1 - Null hypothesis: no structural break Asymptotic test",
"OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable: scaled",
"# ** result_gretl_g1 = dict( endog_mean = (\"Mean dependent var\",",
"-0.0705413 0.0737058 -0.9571 0.3397 alpha(4) 0.0384531 0.0725763 0.5298 0.5968 Null",
"0.487871: #ANOVA Analysis of Variance: Sum of squares df Mean",
"> 1.17928) = 0.321197 CUSUM test for parameter stability -",
"0.1, 3, 196, \"maxF\"] #TODO check this, max at 2001:4",
"macrodata import statsmodels.stats.sandwich_covariance as sw import statsmodels.stats.diagnostic as smsdia import",
"with p-value = 0.00424384 Test for ARCH of order 4",
"0.80049 #forecast actual y For 95% confidence intervals, t(199, 0.025)",
"mod1 = GLSAR(g_inv, exogg, 1) res1 = mod1.iterative_fit(5) mod4 =",
"\"f\"] reset_3 = [5.248951, 0.023, 1, 198, \"f\"] #not available",
"import (assert_almost_equal, assert_equal, assert_allclose, assert_array_less) from statsmodels.regression.linear_model import OLS, GLSAR",
"rho = -0.108136 coefficient std. error t-ratio p-value ------------------------------------------------------------- const",
"23891.3 Residual 22799.7 199 114.571 Total 70582.3 201 351.156 R^2",
"reset_2, decimal=(2,4)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(2,4)) #arch",
"p-value 95% CONFIDENCE INTERVAL #for confidence interval t(199, 0.025) =",
"TR^2 = 4.771043, with p-value = P(Chi-square(4) > 4.77104) =",
"5.23587) = 0.264: RESET test for specification (squares and cubes)",
"F = 5.219019, with p-value = P(F(2,197) > 5.21902) =",
"0.487871, 4, \"chi2\"] normality = [23.962, 0.00001, 2, \"chi2\"] het_white",
"iterative calculation of rho... ITER RHO ESS 1 -0.10734 22530.9",
"\"f\"] #not available cond_1norm = 5984.0525 determinant = 7.1087467e+008 reciprocal_condition_number",
"oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(2,4)) #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4,",
"np.max(np.abs(lev['influence'] - infl.influence)) #just added this based on Gretl #just",
"alpha(2) -0.0488339 0.0724981 -0.6736 0.5014 alpha(3) -0.0705413 0.0737058 -0.9571 0.3397",
"dw = (\"Durbin-Watson\", 1.993858)) #fstatistic, p-value, df1, df2 reset_2_3 =",
"0.293619 -2.091 0.0378 ** Mean dependent var 3.257395 S.D. dependent",
"-30.305896 2009:1 -70.239280 -44.018178 4.007017 -51.919841 - -36.116516 2009:2 -27.024588",
"0.5512 Unadjusted R-squared = 0.165860 Test statistic: TR^2 = 33.503723,",
"squared resid\", 22799.68), mse_resid_sqrt = (\"S.E. of regression\", 10.70380), rsquared",
"residual leverage influence DFFITS'.split() cur_dir = os.path.abspath(os.path.dirname(__file__)) fpath = os.path.join(cur_dir,",
"result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=4) assert_allclose(res.f_pvalue, result_gretl_g1['f_pvalue'][1], rtol=1e-2) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1],",
"Log-likelihood -763.9752 Akaike criterion 1533.950 Schwarz criterion 1543.875 Hannan-Quinn 1537.966",
"5.24895) = 0.023 #heteroscedasticity White White's test for heteroskedasticity OLS,",
"het_white = [33.503723, 0.000003, 5, \"chi2\"] het_breusch_pagan = [1.302014, 0.521520,",
"may indicate a collinearity problem ds_l_realgdp 1.002 realint_1 1.002 VIF(j)",
"0.6230 ds_l_realgdp -3.64704 4.36075 -0.8363 0.4040 realint_1 0.463643 5.78202 0.08019",
"degree=3) compare_ftest(c, reset_2_3, decimal=(6,5)) linear_sq = smsdia.linear_lm(res.resid, res.model.exog) assert_almost_equal(linear_sq[0], linear_squares[0],",
"[5.219019, 0.00619, 2, 197, \"f\"] reset_2 = [7.268492, 0.00762, 1,",
"variable j and the other independent variables Properties of matrix",
"*** ds_l_realgdp 4.37040 0.208146 21.00 2.93e-052 *** realint_1 -0.579253 0.268009",
"7.268492, with p-value = P(F(1,198) > 7.26849) = 0.00762 RESET",
"np.diff(np.log(d['realinv'].values)) gs_l_realgdp = 400 * np.diff(np.log(d['realgdp'].values)) #simple diff, not growthrate,",
"= 0.000003: #heteroscedasticity Breusch-Pagan (original) Breusch-Pagan test for heteroskedasticity OLS,",
"error t-ratio p-value ------------------------------------------------------------- const 1.09468 0.192281 5.693 4.43e-08 ***",
"4 (Bartlett kernel) #coefficient std. error t-ratio p-value 95% CONFIDENCE",
"__name__ == '__main__': t = TestGLSARGretl() t.test_all() ''' Model 5:",
"result_gretl_g1['f_pvalue'][1], decimal=6) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c = oi.reset_ramsey(res, degree=2)",
"Alternative statistic: TR^2 = 4.771043, with p-value = P(Chi-square(4) >",
"const 0.0640964 1.06719 0.06006 0.9522 ds_l_realgdp -0.0456010 0.217377 -0.2098 0.8341",
"1.0296049e+009 reciprocal_condition_number = 0.013819244 #Chi-square(2): test-statistic, pvalue, df normality =",
"90.79971 P-value(F) 9.53e-29 Log-likelihood -763.9752 Akaike criterion 1533.950 Schwarz criterion",
"-0.108136 # coefficient std. error t-ratio p-value 95% CONFIDENCE INTERVAL",
"3.94837e-005: ''' #no idea what this is ''' Augmented regression",
"= 0.709924, with p-value = P(Chi-square(2) > 0.709924) = 0.701200",
"Model 4: Cochrane-Orcutt, using observations 1959:3-2009:3 (T = 201) Dependent",
"1.17928) = 0.321197 CUSUM test for parameter stability - Null",
"#-0.1335859) from R res_g2 = mod_g2.iterative_fit(maxiter=5) #print res_g2.params rho =",
"= 5.219019, with p-value = P(F(2,197) > 5.21902) = 0.00619",
"#LM-statistic, p-value, df arch_4 = [7.30776, 0.120491, 4, \"chi2\"] #multicollinearity",
"res_ols.params mod_g1 = GLSAR(endogg, exogg, rho=-0.108136) res_g1 = mod_g1.fit() #print",
"2001:4 break_chow = [13.1897, 0.00424384, 3, \"chi2\"] # break at",
"5: OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable:",
"test for autocorrelation up to order 4 OLS, using observations",
"#with rho from Gretl #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1],",
"''' Variance Inflation Factors Minimum possible value = 1.0 Values",
"3.257395 S.D. dependent var 18.73915 Sum squared resid 22799.68 S.E.",
"#just added this based on Gretl #just rough test, low",
"Null hypothesis: no structural break Test statistic: max F(3, 196)",
"indicate a collinearity problem ds_l_realgdp 1.002 realint_1 1.002 VIF(j) =",
"= oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(6,5)) linear_sq = smsdia.linear_lm(res.resid, res.model.exog)",
"vif = [1.001, 1.001] names = 'date residual leverage influence",
"(\"Hannan-Quinn\", 1537.966), resid_acf1 = (\"rho\", -0.107341), dw = (\"Durbin-Watson\", 2.213805))",
"= 5.23587, with p-value = P(Chi-square(4) > 5.23587) = 0.264:",
"''' #no idea what this is ''' Augmented regression for",
"linear_sq = smsdia.linear_lm(res.resid, res.model.exog) assert_almost_equal(linear_sq[0], linear_squares[0], decimal=6) assert_almost_equal(linear_sq[1], linear_squares[1], decimal=7)",
"partable[:,1], 6) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1],",
"Gretl output, assert_almost_equal(lev['residual'], res.resid, decimal=3) assert_almost_equal(lev['DFFITS'], infl.dffits[0], decimal=3) assert_almost_equal(lev['leverage'], infl.hat_matrix_diag,",
"uhat^2 coefficient std. error t-ratio p-value ------------------------------------------------------------- const 104.920 21.5848",
"-1.19300, -0.0349939]]) # ** result_gretl_g1 = dict( endog_mean = (\"Mean",
"arch_4[0], decimal=5) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) vif2 = [oi.variance_inflation_factor(res.model.exog, k) for",
"std. error t-ratio p-value --------------------------------------------------------------- const -10.9481 1.35807 -8.062 7.44e-014",
"mod_g1.fit() #print res_g1.params mod_g2 = GLSAR(endogg, exogg, rho=-0.108136) #-0.1335859) from",
"0.676973), rsquared_adj = (\"Adjusted R-squared\", 0.673710), fvalue = (\"F(2, 198)\",",
"using observations 1959:3-2009:3 (T = 201) Dependent variable: ds_l_realinv rho",
"statistic: LM = 1.68351 with p-value = P(Chi-square(2) > 1.68351)",
"alpha(3) -0.0705413 0.0737058 -0.9571 0.3397 alpha(4) 0.0384531 0.0725763 0.5298 0.5968",
"TestGLSARGretl() t.test_all() ''' Model 5: OLS, using observations 1959:2-2009:3 (T",
"= os.path.join(cur_dir, 'results/leverage_influence_ols_nostars.txt') lev = np.genfromtxt(fpath, skip_header=3, skip_footer=1, converters={0:lambda s:",
"order 4 - Null hypothesis: no ARCH effect is present",
"0.2254 0.8219 Sum of squared residuals = 22432.8 Test of",
"-12.284842 10.798554 -33.579120 - 9.009436 2009:3 8.078897 4.483669 10.784377 -16.782652",
"2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=7) #not in gretl",
"= add_constant(np.c_[g_gdp, d2['realint'][:-1].values], prepend=False) mod1 = GLSAR(g_inv, exogg, 1) res1",
"202) Dependent variable: ds_l_realinv HAC standard errors, bandwidth 4 (Bartlett",
"ds_l_realgdp 1.002 realint_1 1.002 VIF(j) = 1/(1 - R(j)^2), where",
"assert_array_less(np.abs(res1.params / res4.params - 1), 0.03) assert_array_less(res4.ssr, res1.ssr) assert_array_less(np.abs(res4.bse /",
"this based on Gretl #just rough test, low decimal in",
"#res2 = res.get_robustcov_results(cov_type='HC1') # TODO: fvalue differs from Gretl, trying",
"files break_qlr = [3.01985, 0.1, 3, 196, \"maxF\"] #TODO check",
"p-value ------------------------------------------------------------- const 1.09468 0.192281 5.693 4.43e-08 *** ds_l_realgdp -0.0323119",
"0.321 Alternative statistic: TR^2 = 4.771043, with p-value = P(Chi-square(4)",
"= 0.120491: ''' ''' Variance Inflation Factors Minimum possible value",
"#Model 5: OLS, using observations 1959:2-2009:3 (T = 202) #Dependent",
"assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) #tests res = res_g2 #with estimated rho",
"coefficient std. error t-ratio p-value ------------------------------------------------------------ const 0.0640964 1.06719 0.06006",
"realint_1 0.00410778 0.0512274 0.08019 0.9362 Explained sum of squares =",
"0.5298 0.5968 Null hypothesis: no ARCH effect is present Test",
"-0.108892 0.0715042 -1.523 0.1294 ds_l_realgdp_1 0.660443 0.390372 1.692 0.0923 *",
"assert_almost_equal(hw[:2], het_white[:2], 6) #arch #sm_arch = smsdia.acorr_lm(res.resid**2, maxlag=4, autolag=None) sm_arch",
"lm_acorr4 = [1.17928, 0.321197, 4, 195, \"F\"] lm2_acorr4 = [4.771043,",
"test for specification (squares and cubes) Test statistic: F =",
"-0.9964 0.3203 sq_ds_l_realg 4.12054 0.684920 6.016 8.62e-09 *** X2_X3 2.89685",
"0.709924, with p-value = P(Chi-square(2) > 0.709924) = 0.701200 ##########",
"#basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 6) assert_almost_equal(res.tvalues, partable[:,2], 2)",
"13.30, 2.62e-029, 3.72587, 5.02258], #*** [-0.613997, 0.293619, -2.091, 0.0378, -1.19300,",
"10.70380 R-squared 0.676978 Adjusted R-squared 0.673731 F(2, 199) 90.79971 P-value(F)",
"from R res_g2 = mod_g2.iterative_fit(maxiter=5) #print res_g2.params rho = -0.108136",
"6862.0664 determinant = 1.0296049e+009 reciprocal_condition_number = 0.013819244 #Chi-square(2): test-statistic, pvalue,",
"195) = 0.426391 with p-value = P(F(2, 195) > 0.426391)",
"coefficient std. error t-ratio p-value --------------------------------------------------------------- const -10.9481 1.35807 -8.062",
"-11.367905 2008:4 -27.665860 -36.294434 3.036851 -42.282972 - -30.305896 2009:1 -70.239280",
"- R(j)^2), where R(j) is the multiple correlation coefficient between",
"with OLS, HAC errors #Model 5: OLS, using observations 1959:2-2009:3",
"decimal=7) #TODO #arch #sm_arch = smsdia.acorr_lm(res.wresid**2, maxlag=4, autolag=None) sm_arch =",
"Explained sum of squares = 33174.2 Test statistic: LM =",
"0.025) = 1.972 Obs ds_l_realinv prediction std. error 95% interval",
"smsdia.acorr_lm(res.resid**2, maxlag=4, autolag=None) sm_arch = smsdia.het_arch(res.resid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=5)",
"= 0.00619 RESET test for specification (squares only) Test statistic:",
"1.09468 0.192281 5.693 4.43e-08 *** ds_l_realgdp -0.0323119 0.0386353 -0.8363 0.4040",
"199) 90.79971 P-value(F) 9.53e-29 Log-likelihood -763.9752 Akaike criterion 1533.950 Schwarz",
"GLSAR and diagnostics against Gretl Created on Thu Feb 02",
"criterion 1533.950 Schwarz criterion 1543.875 Hannan-Quinn 1537.966 rho -0.107341 Durbin-Watson",
"Adjusted R-squared 0.673710 F(2, 198) 221.0475 P-value(F) 3.56e-51 rho -0.003481",
"infl.dffits[0], decimal=3) assert_almost_equal(lev['leverage'], infl.hat_matrix_diag, decimal=3) assert_almost_equal(lev['influence'], infl.influence, decimal=4) def test_GLSARlag():",
"* np.diff(np.log(d['realinv'].values)) gs_l_realgdp = 400 * np.diff(np.log(d['realgdp'].values)) #simple diff, not",
"test statistic: Chi-square(3) = 13.1897 with p-value = 0.00424384 Test",
"p-value = P(Chi-square(2) > 0.709924) = 0.701200 ########## forecast #forecast",
"(T = 202) Dependent variable: uhat^2 coefficient std. error t-ratio",
"QLR test for structural break - Null hypothesis: no structural",
"result_gretl_g1 = dict( endog_mean = (\"Mean dependent var\", 3.113973), endog_std",
"= 7.268492, with p-value = P(F(1,198) > 7.26849) = 0.00762",
"reset_3 = [5.248951, 0.023, 1, 198, \"f\"] #LM-statistic, p-value, df",
"p-value -------------------------------------------------------- alpha(0) 97.0386 20.3234 4.775 3.56e-06 *** alpha(1) 0.176114",
"coding: utf-8 -*- \"\"\"Tests of GLSAR and diagnostics against Gretl",
"= 208.528 [p-value 1.47e-049] #LM-test autocorrelation Breusch-Godfrey test for autocorrelation",
"2009:2 -27.024588 -12.284842 1.427414 -15.099640 - -9.470044 2009:3 8.078897 4.483669",
"lm2_acorr4 = [4.771043, 0.312, 4, \"chi2\"] acorr_ljungbox4 = [5.23587, 0.264,",
"statsmodels.datasets import macrodata d2 = macrodata.load_pandas().data g_gdp = 400*np.diff(np.log(d2['realgdp'].values)) g_inv",
"assert_allclose, assert_array_less) from statsmodels.regression.linear_model import OLS, GLSAR from statsmodels.tools.tools import",
"assert_almost_equal(sm_arch[1], arch_4[1], decimal=2) ''' Performing iterative calculation of rho... ITER",
"> 0.426391) = 0.653468 Test for normality of residual -",
"break at 1984:1 arch_4 = [3.43473, 0.487871, 4, \"chi2\"] normality",
"#see cusum results in files break_qlr = [3.01985, 0.1, 3,",
"max at 2001:4 break_chow = [13.1897, 0.00424384, 3, \"chi2\"] #",
"= (\"Durbin-Watson\", 2.213805)) linear_logs = [1.68351, 0.430953, 2, \"chi2\"] #for",
"statistic: max F(3, 196) = 3.01985 at observation 2001:4 (10",
"statistic: F = 7.268492, with p-value = P(F(1,198) > 7.26849)",
"0.03) assert_array_less(res4.ssr, res1.ssr) assert_array_less(np.abs(res4.bse / res1.bse) - 1, 0.015) assert_array_less(np.abs((res4.fittedvalues",
"dependent var 18.73915 Sum squared resid 22799.68 S.E. of regression",
"skip_header=3, skip_footer=2, converters={0:lambda s: s}) lev.dtype.names = names res =",
"R-squared = 0.023619 Test statistic: LMF = 1.179281, with p-value",
"\"chi2\"] het_white = [33.503723, 0.000003, 5, \"chi2\"] het_breusch_pagan = [1.302014,",
"(10 percent critical value = 4.09) Non-linearity test (logs) -",
"result_gretl_g1['rsquared'][1], decimal=7) #FAIL #assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5)",
"= P(Chi-square(4) > 5.23587) = 0.264: RESET test for specification",
"[5.23587, 0.264, 4, \"chi2\"] #break cusum_Harvey_Collier = [0.494432, 0.621549, 198,",
"-10.9481 1.35807 -8.062 7.44e-014 *** ds_l_realgdp 4.28893 0.229459 18.69 2.40e-045",
"degree=2) compare_ftest(c, reset_2, decimal=(2,4)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3,",
"F(2, 199) 90.79971 P-value(F) 9.53e-29 Log-likelihood -763.9752 Akaike criterion 1533.950",
"ds_l_realgdp_1 0.660443 0.390372 1.692 0.0923 * realint_2 0.0769695 0.341527 0.2254",
"= 1.17928 with p-value = P(F(4,195) > 1.17928) = 0.321197",
"0.673710), fvalue = (\"F(2, 198)\", 221.0475), f_pvalue = (\"P-value(F)\", 3.56e-51),",
"[7.268492, 0.00762, 1, 198, \"f\"] reset_3 = [5.248951, 0.023, 1,",
"= 0.521520 #heteroscedasticity Breusch-Pagan Koenker Breusch-Pagan test for heteroskedasticity OLS,",
"#for easier copying cov_hac = sw.cov_hac_simple(res, nlags=4, use_correction=False) bse_hac =",
"*** ds_l_realgdp 4.28893 0.229459 18.69 2.40e-045 *** realint_1 -0.662644 0.334872",
"OLS, using observations 1959:2-2009:3 (T = 202) Dependent variable: uhat^2",
"reciprocal_condition_number = 0.013826504 vif = [1.001, 1.001] names = 'date",
"-1.10777, -0.0507346]]) # ** #Statistics based on the rho-differenced data:",
"f_pvalue = (\"P-value(F)\", 3.56e-51), resid_acf1 = (\"rho\", -0.003481), dw =",
"macrodata d2 = macrodata.load_pandas().data g_gdp = 400*np.diff(np.log(d2['realgdp'].values)) g_inv = 400*np.diff(np.log(d2['realinv'].values))",
"-9.470044 2009:3 8.078897 4.483669 1.315876 1.888819 - 7.078520 Forecast evaluation",
"order 4 coefficient std. error t-ratio p-value -------------------------------------------------------- alpha(0) 97.0386",
"= P(Chi-square(2) > 7.52477) = 0.0232283 LM test for autocorrelation",
"assert_almost_equal(lev['influence'], infl.influence, decimal=4) def test_GLSARlag(): #test that results for lag>1",
"compare_ftest(c, reset_2, decimal=(2,4)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(2,4))",
"assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=7) #not",
"7.44e-014 *** ds_l_realgdp 4.28893 0.229459 18.69 2.40e-045 *** realint_1 -0.662644",
"that results for lag>1 is close to lag=1, and smaller",
"p-value = P(Chi-square(2) > 7.52477) = 0.0232283 LM test for",
"5.02258], #*** [-0.613997, 0.293619, -2.091, 0.0378, -1.19300, -0.0349939]]) # **",
"gretl assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=6) #FAIL assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=6) #FAIL assert_almost_equal(np.sqrt(res.mse_resid),",
"assert_almost_equal(sm_arch[0], arch_4[0], decimal=5) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) vif2 = [oi.variance_inflation_factor(res.model.exog, k)",
"rho from Gretl #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 6)",
"arch_4[1], decimal=6) vif2 = [oi.variance_inflation_factor(res.model.exog, k) for k in [1,2]]",
"np.diff(np.log(d['realgdp'].values)) #simple diff, not growthrate, I want heteroscedasticity later for",
"Obs ds_l_realinv prediction std. error 95% interval 2008:3 -7.134492 -17.177905",
"0.3397 alpha(4) 0.0384531 0.0725763 0.5298 0.5968 Null hypothesis: no ARCH",
"is present Test statistic: LM = 3.43473 with p-value =",
"observations, T=133 #(res_ols.model.exog <=0).any(1).sum() = 69 ?not 70 linear_squares =",
"in gretl #assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=7) #FAIL #assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL",
"Sum squared resid 22799.68 S.E. of regression 10.70380 R-squared 0.676978",
"Test for ARCH of order 4 coefficient std. error t-ratio",
"[3.01985, 0.1, 3, 196, \"maxF\"] #TODO check this, max at",
"res4 = mod4.iterative_fit(10) assert_array_less(np.abs(res1.params / res4.params - 1), 0.03) assert_array_less(res4.ssr,",
"in parameters Test statistic: Harvey-Collier t(198) = 0.494432 with p-value",
"** sq_realint_1 0.662135 1.10919 0.5970 0.5512 Unadjusted R-squared = 0.165860",
"Mean dependent var 3.113973 S.D. dependent var 18.67447 Sum squared",
"7.078520 Forecast evaluation statistics Mean Error -3.7387 Mean Squared Error",
"= 5984.0525 determinant = 7.1087467e+008 reciprocal_condition_number = 0.013826504 vif =",
"to order 4 - Null hypothesis: no autocorrelation Test statistic:",
"endog_std = (\"S.D. dependent var\", 18.73915), ssr = (\"Sum squared",
"Test statistic: Harvey-Collier t(198) = 0.494432 with p-value = P(t(198)",
"significant=1) #FAIL #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c = oi.reset_ramsey(res, degree=2)",
"resid_acf1 = (\"rho\", -0.107341), dw = (\"Durbin-Watson\", 2.213805)) linear_logs =",
"structural break Test statistic: max F(3, 196) = 3.01985 at",
"#coefficient std. error t-ratio p-value 95% CONFIDENCE INTERVAL #for confidence",
"0.0742817 -0.1210 0.9039 uhat_3 0.0837332 0.0735015 1.139 0.2560 uhat_4 -0.0636242",
"other[1], decimal=decimal[1]) assert_equal(contrast_res.df_num, other[2]) assert_equal(contrast_res.df_denom, other[3]) assert_equal(\"f\", other[4]) class TestGLSARGretl:",
"0.0923 * realint_2 0.0769695 0.341527 0.2254 0.8219 Sum of squared",
"var 3.257395 S.D. dependent var 18.73915 Sum squared resid 22799.68",
"decimal=4) #not in gretl assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=6) #FAIL assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1],",
"-8.055, 7.17e-014, -11.8029, -7.16049], # *** [4.37422, 0.328787, 13.30, 2.62e-029,",
"23891.3 / 114.571 = 208.528 [p-value 1.47e-049] #LM-test autocorrelation Breusch-Godfrey",
"result_gretl_g1['f_pvalue'][1], rtol=1e-2) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO #arch #sm_arch = smsdia.acorr_lm(res.wresid**2,",
"25.749991 Forecast evaluation statistics Mean Error -3.7387 Mean Squared Error",
"5.21902) = 0.00619 RESET test for specification (squares only) Test",
"2009:3 8.078897 4.483669 1.315876 1.888819 - 7.078520 Forecast evaluation statistics",
"llf = (\"Log-likelihood\", -763.9752), aic = (\"Akaike criterion\", 1533.950), bic",
"= P(Chi-square(2) > 0.709924) = 0.701200 ########## forecast #forecast mean",
"criterion 1543.875 Hannan-Quinn 1537.966 rho -0.107341 Durbin-Watson 2.213805 QLR test",
"df1, df2 reset_2_3 = [5.219019, 0.00619, 2, 197, \"f\"] reset_2",
"easier copying cov_hac = sw.cov_hac_simple(res, nlags=4, use_correction=False) bse_hac = sw.se_cov(cov_hac)",
"variable: ds_l_realinv rho = -0.108136 coefficient std. error t-ratio p-value",
"#forecast mean y For 95% confidence intervals, t(199, 0.025) =",
"results in files break_qlr = [3.01985, 0.1, 3, 196, \"maxF\"]",
"res_g2 = mod_g2.iterative_fit(maxiter=5) #print res_g2.params rho = -0.108136 # coefficient",
"\"maxF\"] #TODO check this, max at 2001:4 break_chow = [13.1897,",
"cond_1norm = 5984.0525 determinant = 7.1087467e+008 reciprocal_condition_number = 0.013826504 vif",
"variable: scaled uhat^2 coefficient std. error t-ratio p-value ------------------------------------------------------------- const",
"assert_almost_equal(lev['leverage'], infl.hat_matrix_diag, decimal=3) assert_almost_equal(lev['influence'], infl.influence, decimal=4) def test_GLSARlag(): #test that",
"scaled uhat^2 (Koenker robust variant) coefficient std. error t-ratio p-value",
"to lag=1, and smaller ssr from statsmodels.datasets import macrodata d2",
"sm_arch = smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=1) assert_almost_equal(sm_arch[1], arch_4[1], decimal=2)",
"with p-value = P(Chi-square(2) > 0.709924) = 0.701200 ########## forecast",
"# *** [ 4.37040, 0.208146, 21.00, 2.93e-052, 3.95993, 4.78086], #",
"order 4 lm_acorr4 = [1.17928, 0.321197, 4, 195, \"F\"] lm2_acorr4",
"at observation 1984:1 - Null hypothesis: no structural break Asymptotic",
"R-squared 0.676973 Adjusted R-squared 0.673710 F(2, 198) 221.0475 P-value(F) 3.56e-51",
"R-squared 0.676978 Adjusted R-squared 0.673731 F(2, 199) 90.79971 P-value(F) 9.53e-29",
"exogg).fit() #print res_ols.params mod_g1 = GLSAR(endogg, exogg, rho=-0.108136) res_g1 =",
"decimal=7) #FAIL #assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue,",
"squares = 2.60403 Test statistic: LM = 1.302014, with p-value",
"= TestGLSARGretl() t.test_all() ''' Model 5: OLS, using observations 1959:2-2009:3",
"decimal=3) assert_almost_equal(lev['DFFITS'], infl.dffits[0], decimal=3) assert_almost_equal(lev['leverage'], infl.hat_matrix_diag, decimal=3) assert_almost_equal(lev['influence'], infl.influence, decimal=4)",
"#print np.max(np.abs(lev['influence'] - infl.influence)) #just added this based on Gretl",
"for structural break at observation 1984:1 - Null hypothesis: no",
"data: Mean dependent var 3.113973 S.D. dependent var 18.67447 Sum",
"-0.9571 0.3397 alpha(4) 0.0384531 0.0725763 0.5298 0.5968 Null hypothesis: no",
"np.max(np.abs(lev['DFFITS'] - infl.dffits[0])) #print np.max(np.abs(lev['leverage'] - infl.hat_matrix_diag)) #print np.max(np.abs(lev['influence'] -",
"= 0.023: ''' ''' Test for ARCH of order 4",
"Null hypothesis: restriction is acceptable Test statistic: F(2, 195) =",
"= 'date residual leverage influence DFFITS'.split() cur_dir = os.path.abspath(os.path.dirname(__file__)) fpath",
"class TestGLSARGretl: def test_all(self): d = macrodata.load_pandas().data #import datasetswsm.greene as",
"0.00001, 2, \"chi2\"] het_white = [33.503723, 0.000003, 5, \"chi2\"] het_breusch_pagan",
"relationship is linear Test statistic: LM = 1.68351 with p-value",
"std. error t-ratio p-value ------------------------------------------------------------- const 104.920 21.5848 4.861 2.39e-06",
"coefficient std. error t-ratio p-value 95% CONFIDENCE INTERVAL partable =",
"for ARCH of order 4 coefficient std. error t-ratio p-value",
"Gretl #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 6) assert_almost_equal(res.tvalues, partable[:,2],",
"= 0.013819244 #Chi-square(2): test-statistic, pvalue, df normality = [20.2792, 3.94837e-005,",
"p-value = 0.00424384 Test for ARCH of order 4 -",
"assert_almost_equal(linear_sq[1], linear_squares[1], decimal=7) hbpk = smsdia.het_breuschpagan(res.resid, res.model.exog) assert_almost_equal(hbpk[0], het_breusch_pagan_konker[0], decimal=6)",
"5.248951, with p-value = P(F(1,198) > 5.24895) = 0.023: '''",
"of regression 10.70380 R-squared 0.676978 Adjusted R-squared 0.673731 F(2, 199)",
"decimal=decimal[0]) assert_almost_equal(contrast_res.pvalue, other[1], decimal=decimal[1]) assert_equal(contrast_res.df_num, other[2]) assert_equal(contrast_res.df_denom, other[3]) assert_equal(\"f\", other[4])",
"confidence interval t(199, 0.025) = 1.972 partable = np.array([ [-9.48167,",
"(\"Durbin-Watson\", 1.993858)) #fstatistic, p-value, df1, df2 reset_2_3 = [5.219019, 0.00619,",
"specification (squares and cubes) Test statistic: F = 5.219019, with",
"2.62e-029, 3.72587, 5.02258], #*** [-0.613997, 0.293619, -2.091, 0.0378, -1.19300, -0.0349939]])",
"202) Dependent variable: scaled uhat^2 (Koenker robust variant) coefficient std.",
"res.model.exog) assert_almost_equal(linear_sq[0], linear_squares[0], decimal=6) assert_almost_equal(linear_sq[1], linear_squares[1], decimal=7) hbpk = smsdia.het_breuschpagan(res.resid,",
"10.66735), rsquared = (\"R-squared\", 0.676973), rsquared_adj = (\"Adjusted R-squared\", 0.673710),",
"[13.1897, 0.00424384, 3, \"chi2\"] # break at 1984:1 arch_4 =",
"-8.055 7.17e-014 *** ds_l_realgdp 4.37422 0.328787 13.30 2.62e-029 *** realint_1",
"2009:2 -27.024588 -12.284842 10.798554 -33.579120 - 9.009436 2009:3 8.078897 4.483669",
"using observations 1959:2-2009:3 (T = 202) Dependent variable: uhat^2 coefficient",
"statistic: LM = 0.709924, with p-value = P(Chi-square(2) > 0.709924)",
"= smsdia.het_white(res.resid, res.model.exog) assert_almost_equal(hw[:2], het_white[:2], 6) #arch #sm_arch = smsdia.acorr_lm(res.resid**2,",
"= smsdia.het_arch(res.wresid, nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=4) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) #tests",
"= 0.013826504 vif = [1.001, 1.001] names = 'date residual",
"using observations 1959:2-2009:3 (T = 202) Dependent variable: ds_l_realinv HAC",
"decimal=3) assert_almost_equal(lev['leverage'], infl.hat_matrix_diag, decimal=3) assert_almost_equal(lev['influence'], infl.influence, decimal=4) def test_GLSARlag(): #test",
"t(198) = 0.494432 with p-value = P(t(198) > 0.494432) =",
"Percentage Error -7.1173 Mean Absolute Percentage Error -43.867 Theil's U",
"-0.104707 0.0719948 -1.454 0.1475 uhat_2 -0.00898483 0.0742817 -0.1210 0.9039 uhat_3",
"#growth rates gs_l_realinv = 400 * np.diff(np.log(d['realinv'].values)) gs_l_realgdp = 400",
"np.isnan(lev[-1]['f1']): lev = np.genfromtxt(fpath, skip_header=3, skip_footer=2, converters={0:lambda s: s}) lev.dtype.names",
"-9.602, 3.65e-018, -11.4631, -7.55670], # *** [ 4.37040, 0.208146, 21.00,",
"decimal=2) assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=4) #not in gretl assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=6)",
"t = TestGLSARGretl() t.test_all() ''' Model 5: OLS, using observations",
"-42.282972 - -30.305896 2009:1 -70.239280 -44.018178 4.007017 -51.919841 - -36.116516",
"statistic: LM = 3.43473 with p-value = P(Chi-square(4) > 3.43473)",
"statsmodels.regression.linear_model import OLS, GLSAR from statsmodels.tools.tools import add_constant from statsmodels.datasets",
"0.192281 5.693 4.43e-08 *** ds_l_realgdp -0.0323119 0.0386353 -0.8363 0.4040 realint_1",
"differs from Gretl, trying any of the HCx #assert_almost_equal(res2.fvalue, result_gretl_g1['fvalue'][1],",
"partable[:,0], 4) assert_almost_equal(res.bse, partable[:,1], 6) assert_almost_equal(res.tvalues, partable[:,2], 2) assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1],",
"p-value ------------------------------------------------------------ const 0.0640964 1.06719 0.06006 0.9522 ds_l_realgdp -0.0456010 0.217377",
"199) = 23891.3 / 114.571 = 208.528 [p-value 1.47e-049] #LM-test",
"> 33.503723) = 0.000003: #heteroscedasticity Breusch-Pagan (original) Breusch-Pagan test for",
"compare_ftest(c, reset_2, decimal=(6,5)) c = oi.reset_ramsey(res, degree=3) compare_ftest(c, reset_2_3, decimal=(6,5))",
"macrodata.load_pandas().data #import datasetswsm.greene as g #d = g.load('5-1') #growth rates",
"std. error 95% interval 2008:3 -7.134492 -17.177905 2.946312 -22.987904 -",
"smsdia.het_white(res.resid, res.model.exog) assert_almost_equal(hw[:2], het_white[:2], 6) #arch #sm_arch = smsdia.acorr_lm(res.resid**2, maxlag=4,",
"decimal=6) #tests res = res_g2 #with estimated rho #estimated lag",
"<NAME> License: BSD-3 \"\"\" import os import numpy as np",
"decimal=4) assert_allclose(res.f_pvalue, result_gretl_g1['f_pvalue'][1], rtol=1e-2) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO #arch #sm_arch",
"7.52477 with p-value = P(Chi-square(2) > 7.52477) = 0.0232283 LM",
"-0.00898483 0.0742817 -0.1210 0.9039 uhat_3 0.0837332 0.0735015 1.139 0.2560 uhat_4",
"*** [4.37422, 0.328787, 13.30, 2.62e-029, 3.72587, 5.02258], #*** [-0.613997, 0.293619,",
"P-value(F) 9.53e-29 Log-likelihood -763.9752 Akaike criterion 1533.950 Schwarz criterion 1543.875",
"For 95% confidence intervals, t(199, 0.025) = 1.972 Obs ds_l_realinv",
"autocorrelation up to order 4 - Null hypothesis: no autocorrelation",
"> 7.30776) = 0.120491 Test of common factor restriction -",
"= GLSAR(g_inv, exogg, 4) res4 = mod4.iterative_fit(10) assert_array_less(np.abs(res1.params / res4.params",
"res_g1 #with rho from Gretl #basic assert_almost_equal(res.params, partable[:,0], 4) assert_almost_equal(res.bse,",
"from Gretl, trying any of the HCx #assert_almost_equal(res2.fvalue, result_gretl_g1['fvalue'][1], decimal=0)",
"dependent var 18.67447 Sum squared resid 22530.90 S.E. of regression",
"4 - Null hypothesis: no ARCH effect is present Test",
"-7.16049], # *** [4.37422, 0.328787, 13.30, 2.62e-029, 3.72587, 5.02258], #***",
"ds_l_realgdp -29.7040 6.24983 -4.753 3.88e-06 *** realint_1 -6.93102 6.95607 -0.9964",
"4, 195, \"F\"] lm2_acorr4 = [4.771043, 0.312, 4, \"chi2\"] acorr_ljungbox4",
"- -11.367905 2008:4 -27.665860 -36.294434 3.036851 -42.282972 - -30.305896 2009:1",
"collinearity problem ds_l_realgdp 1.002 realint_1 1.002 VIF(j) = 1/(1 -",
"break_qlr = [3.01985, 0.1, 3, 196, \"maxF\"] #TODO check this,",
"LMF = 1.179281, with p-value = P(F(4,195) > 1.17928) =",
"R-squared\", 0.673710), fvalue = (\"F(2, 198)\", 221.0475), f_pvalue = (\"P-value(F)\",",
"add_constant(np.c_[gs_l_realgdp, d['realint'][:-1].values]) res_ols = OLS(endogg, exogg).fit() #print res_ols.params mod_g1 =",
"-16.782652 - 25.749991 Forecast evaluation statistics Mean Error -3.7387 Mean",
"lev.dtype.names = names res = res_ols #for easier copying cov_hac",
"nlags=4) assert_almost_equal(sm_arch[0], arch_4[0], decimal=4) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) #tests res =",
"= 0.264: RESET test for specification (squares and cubes) Test",
"standard errors, bandwidth 4 (Bartlett kernel) #coefficient std. error t-ratio",
"1.993858)) #fstatistic, p-value, df1, df2 reset_2_3 = [5.219019, 0.00619, 2,",
"21.5848 4.861 2.39e-06 *** ds_l_realgdp -29.7040 6.24983 -4.753 3.88e-06 ***",
"20.3234 4.775 3.56e-06 *** alpha(1) 0.176114 0.0714698 2.464 0.0146 **",
"based on Gretl #just rough test, low decimal in Gretl",
"1533.950), bic = (\"Schwarz criterion\", 1543.875), hqic = (\"Hannan-Quinn\", 1537.966),",
"const 10.6870 21.7027 0.4924 0.6230 ds_l_realgdp -3.64704 4.36075 -0.8363 0.4040",
"#assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=7) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=4)",
"and the other independent variables Properties of matrix X'X: 1-norm",
"reset_2 = [7.268492, 0.00762, 1, 198, \"f\"] reset_3 = [5.248951,",
"-9.50990 0.990456 -9.602 3.65e-018 *** ds_l_realgdp 4.37040 0.208146 21.00 2.93e-052",
"1.302014) = 0.521520 #heteroscedasticity Breusch-Pagan Koenker Breusch-Pagan test for heteroskedasticity",
"intervals, t(199, 0.025) = 1.972 Obs ds_l_realinv prediction std. error",
"= 1.0 Values > 10.0 may indicate a collinearity problem",
"GLSAR(endogg, exogg, rho=-0.108136) res_g1 = mod_g1.fit() #print res_g1.params mod_g2 =",
"= P(Chi-square(4) > 3.43473) = 0.487871: #ANOVA Analysis of Variance:",
"Absolute Error 12.646 Mean Percentage Error -7.1173 Mean Absolute Percentage",
"3.88e-06 *** realint_1 -6.93102 6.95607 -0.9964 0.3203 sq_ds_l_realg 4.12054 0.684920",
"# break at 1984:1 arch_4 = [3.43473, 0.487871, 4, \"chi2\"]",
"p-value = P(F(4,195) > 1.17928) = 0.321 Alternative statistic: TR^2",
"assert_almost_equal(hbpk[0], het_breusch_pagan_konker[0], decimal=6) assert_almost_equal(hbpk[1], het_breusch_pagan_konker[1], decimal=6) hw = smsdia.het_white(res.resid, res.model.exog)",
"0.8341 realint_1 0.0511769 0.293136 0.1746 0.8616 uhat_1 -0.104707 0.0719948 -1.454",
"- Null hypothesis: no structural break Asymptotic test statistic: Chi-square(3)",
"= (\"F(2, 199)\", 90.79971), f_pvalue = (\"P-value(F)\", 9.53e-29), llf =",
"3.56e-51 rho -0.003481 Durbin-Watson 1.993858 ''' ''' RESET test for",
"LMF = 1.17928 with p-value = P(F(4,195) > 1.17928) =",
"202) Dependent variable: scaled uhat^2 coefficient std. error t-ratio p-value",
"df normality = [20.2792, 3.94837e-005, 2] #tests res = res_g1",
"decimal=(6,5)) linear_sq = smsdia.linear_lm(res.resid, res.model.exog) assert_almost_equal(linear_sq[0], linear_squares[0], decimal=6) assert_almost_equal(linear_sq[1], linear_squares[1],",
"70582.3 = 0.676978 F(2, 199) = 23891.3 / 114.571 =",
"t-ratio p-value -------------------------------------------------------- alpha(0) 97.0386 20.3234 4.775 3.56e-06 *** alpha(1)",
"2008:3 -7.134492 -17.177905 2.946312 -22.987904 - -11.367905 2008:4 -27.665860 -36.294434",
"smsdia.het_breuschpagan(res.resid, res.model.exog) assert_almost_equal(hbpk[0], het_breusch_pagan_konker[0], decimal=6) assert_almost_equal(hbpk[1], het_breusch_pagan_konker[1], decimal=6) hw =",
"cov_hac I guess #res2 = res.get_robustcov_results(cov_type='HC1') # TODO: fvalue differs",
"= res_ols #for easier copying cov_hac = sw.cov_hac_simple(res, nlags=4, use_correction=False)",
"proportion, UD 0.80049 #forecast actual y For 95% confidence intervals,",
"-0.0636242 0.0737363 -0.8629 0.3893 Unadjusted R-squared = 0.023619 Test statistic:",
"1.692 0.0923 * realint_2 0.0769695 0.341527 0.2254 0.8219 Sum of",
"> 7.52477) = 0.0232283 LM test for autocorrelation up to",
"the rho-differenced data: Mean dependent var 3.113973 S.D. dependent var",
"F(2, 195) = 0.426391 with p-value = P(F(2, 195) >",
"Test statistic: LMF = 1.179281, with p-value = P(F(4,195) >",
"Test statistic: F(2, 195) = 0.426391, with p-value = 0.653468",
"std. error t-ratio p-value 95% CONFIDENCE INTERVAL partable = np.array([",
"ds_l_realinv coefficient std. error t-ratio p-value --------------------------------------------------------------- const -10.9481 1.35807",
"Feb 02 21:15:47 2012 Author: <NAME> License: BSD-3 \"\"\" import",
"exogg, 4) res4 = mod4.iterative_fit(10) assert_array_less(np.abs(res1.params / res4.params - 1),",
"#heteroscedasticity White White's test for heteroskedasticity OLS, using observations 1959:2-2009:3",
"np.max(np.abs(lev['leverage'] - infl.hat_matrix_diag)) #print np.max(np.abs(lev['influence'] - infl.influence)) #just added this",
"break_chow = [13.1897, 0.00424384, 3, \"chi2\"] # break at 1984:1",
"> 10.0 may indicate a collinearity problem ds_l_realgdp 1.002 realint_1",
"Absolute Percentage Error -43.867 Theil's U 0.4365 Bias proportion, UM",
"errors, bandwidth 4 (Bartlett kernel) #coefficient std. error t-ratio p-value",
"with p-value = P(Chi-square(4) > 5.23587) = 0.264: RESET test",
"(\"Adjusted R-squared\", 0.673731), fvalue = (\"F(2, 199)\", 90.79971), f_pvalue =",
"UM 0.06394 Regression proportion, UR 0.13557 Disturbance proportion, UD 0.80049",
"= [1.17928, 0.321197, 4, 195, \"F\"] lm2_acorr4 = [4.771043, 0.312,",
"cond_1norm = 6862.0664 determinant = 1.0296049e+009 reciprocal_condition_number = 0.013819244 #Chi-square(2):",
"0.120491 Test of common factor restriction - Null hypothesis: restriction",
"s}) #either numpy 1.6 or python 3.2 changed behavior if",
"4, \"chi2\"] normality = [23.962, 0.00001, 2, \"chi2\"] het_white =",
"Breusch-Godfrey test for autocorrelation up to order 4 lm_acorr4 =",
"- 4.714544 2008:4 -27.665860 -36.294434 11.126262 -58.234939 - -14.353928 2009:1",
"break Asymptotic test statistic: Chi-square(3) = 13.1897 with p-value =",
"9.009436 2009:3 8.078897 4.483669 10.784377 -16.782652 - 25.749991 Forecast evaluation",
"= (\"Mean dependent var\", 3.257395), endog_std = (\"S.D. dependent var\",",
"3.036851 -42.282972 - -30.305896 2009:1 -70.239280 -44.018178 4.007017 -51.919841 -",
"np.genfromtxt(fpath, skip_header=3, skip_footer=1, converters={0:lambda s: s}) #either numpy 1.6 or",
"assert_almost_equal(sm_arch[0], arch_4[0], decimal=1) assert_almost_equal(sm_arch[1], arch_4[1], decimal=2) ''' Performing iterative calculation",
"names res = res_ols #for easier copying cov_hac = sw.cov_hac_simple(res,",
"assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1], decimal=6) #FAIL assert_almost_equal(res.rsquared_adj, result_gretl_g1['rsquared_adj'][1], decimal=6) #FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1],",
"test for specification (squares only) Test statistic: F = 7.268492,",
"= (\"rho\", -0.003481), dw = (\"Durbin-Watson\", 1.993858)) #fstatistic, p-value, df1,",
"(Bartlett kernel) #coefficient std. error t-ratio p-value 95% CONFIDENCE INTERVAL",
"result_gretl_g1['f_pvalue'][1], significant=1) #FAIL #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1], decimal=7) #TODO c = oi.reset_ramsey(res,",
"33.503723) = 0.000003: #heteroscedasticity Breusch-Pagan (original) Breusch-Pagan test for heteroskedasticity",
"uhat_4 -0.0636242 0.0737363 -0.8629 0.3893 Unadjusted R-squared = 0.023619 Test",
"2, \"chi2\"] #for logs: dropping 70 nan or incomplete observations,",
"-7.55670], # *** [ 4.37040, 0.208146, 21.00, 2.93e-052, 3.95993, 4.78086],",
"= mod4.iterative_fit(10) assert_array_less(np.abs(res1.params / res4.params - 1), 0.03) assert_array_less(res4.ssr, res1.ssr)",
"to order 4 lm_acorr4 = [1.17928, 0.321197, 4, 195, \"F\"]",
"not available het_breusch_pagan_konker = [0.709924, 0.701200, 2, \"chi2\"] reset_2_3 =",
"3.56e-51), resid_acf1 = (\"rho\", -0.003481), dw = (\"Durbin-Watson\", 1.993858)) #fstatistic,",
"2.091 0.0379 ** sq_realint_1 0.662135 1.10919 0.5970 0.5512 Unadjusted R-squared",
"0.0769695 0.341527 0.2254 0.8219 Sum of squared residuals = 22432.8",
"= res.get_robustcov_results(cov_type='HC1') # TODO: fvalue differs from Gretl, trying any",
"het_breusch_pagan_konker[0], decimal=6) assert_almost_equal(hbpk[1], het_breusch_pagan_konker[1], decimal=6) hw = smsdia.het_white(res.resid, res.model.exog) assert_almost_equal(hw[:2],",
"#FAIL assert_almost_equal(np.sqrt(res.mse_resid), result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=4) assert_allclose(res.f_pvalue, result_gretl_g1['f_pvalue'][1], rtol=1e-2)",
"kernel) coefficient std. error t-ratio p-value ------------------------------------------------------------- const -9.48167 1.17709",
"p-value = P(t(198) > 0.494432) = 0.621549 Chow test for",
"Test statistic: LM = 0.709924, with p-value = P(Chi-square(2) >",
"infl.hat_matrix_diag, decimal=3) assert_almost_equal(lev['influence'], infl.influence, decimal=4) def test_GLSARlag(): #test that results",
"= P(F(4,195) > 1.17928) = 0.321197 CUSUM test for parameter",
"95% interval 2008:3 -7.134492 -17.177905 11.101892 -39.070353 - 4.714544 2008:4",
"bse_hac = sw.se_cov(cov_hac) assert_almost_equal(res.params, partable[:,0], 5) assert_almost_equal(bse_hac, partable[:,1], 5) #TODO",
"2008:3 -7.134492 -17.177905 11.101892 -39.070353 - 4.714544 2008:4 -27.665860 -36.294434",
"0.0737058 -0.9571 0.3397 alpha(4) 0.0384531 0.0725763 0.5298 0.5968 Null hypothesis:",
"= (\"Log-likelihood\", -763.9752), aic = (\"Akaike criterion\", 1533.950), bic =",
"prepend=False) mod1 = GLSAR(g_inv, exogg, 1) res1 = mod1.iterative_fit(5) mod4",
"-0.0488339 0.0724981 -0.6736 0.5014 alpha(3) -0.0705413 0.0737058 -0.9571 0.3397 alpha(4)",
"197, \"f\"] reset_2 = [7.268492, 0.00762, 1, 198, \"f\"] reset_3",
"error t-ratio p-value ------------------------------------------------------------- const -9.50990 0.990456 -9.602 3.65e-018 ***",
"assert_almost_equal(hbpk[1], het_breusch_pagan_konker[1], decimal=6) hw = smsdia.het_white(res.resid, res.model.exog) assert_almost_equal(hw[:2], het_white[:2], 6)",
"#*** [-0.613997, 0.293619, -2.091, 0.0378, -1.19300, -0.0349939]]) # ** result_gretl_g1",
"- -21.480222 2009:2 -27.024588 -12.284842 10.798554 -33.579120 - 9.009436 2009:3",
"statistic: LM = 7.30776 with p-value = P(Chi-square(4) > 7.30776)",
"observations 1959:2-2009:3 (T = 202) Dependent variable: ds_l_realinv HAC standard",
"arch_4[0], decimal=4) assert_almost_equal(sm_arch[1], arch_4[1], decimal=6) #tests res = res_g2 #with",
"Akaike criterion 1533.950 Schwarz criterion 1543.875 Hannan-Quinn 1537.966 rho -0.107341",
"p-value = P(F(1,198) > 7.26849) = 0.00762 RESET test for",
"= 202) Dependent variable: ds_l_realinv HAC standard errors, bandwidth 4",
"X2_X3 2.89685 1.38571 2.091 0.0379 ** sq_realint_1 0.662135 1.10919 0.5970",
"9.53e-29 Log-likelihood -763.9752 Akaike criterion 1533.950 Schwarz criterion 1543.875 Hannan-Quinn",
"const 104.920 21.5848 4.861 2.39e-06 *** ds_l_realgdp -29.7040 6.24983 -4.753",
"0.662135 1.10919 0.5970 0.5512 Unadjusted R-squared = 0.165860 Test statistic:",
"factor restriction Test statistic: F(2, 195) = 0.426391, with p-value",
"Values > 10.0 may indicate a collinearity problem ds_l_realgdp 1.002",
"result_gretl_g1['mse_resid_sqrt'][1], decimal=5) assert_almost_equal(res.fvalue, result_gretl_g1['fvalue'][1], decimal=0) assert_almost_equal(res.f_pvalue, result_gretl_g1['f_pvalue'][1], decimal=6) #assert_almost_equal(res.durbin_watson, result_gretl_g1['dw'][1],",
"0.660443 0.390372 1.692 0.0923 * realint_2 0.0769695 0.341527 0.2254 0.8219",
"result_gretl_g1['dw'][1], decimal=7) #TODO c = oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(6,5))",
"result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=7) #not in gretl #assert_almost_equal(res.rsquared, result_gretl_g1['rsquared'][1],",
"11.126262 -58.234939 - -14.353928 2009:1 -70.239280 -44.018178 11.429236 -66.556135 -",
"evaluation statistics Mean Error -3.7387 Mean Squared Error 218.61 Root",
"- Null hypothesis: restriction is acceptable Test statistic: F(2, 195)",
"[5.248951, 0.023, 1, 198, \"f\"] #not available cond_1norm = 5984.0525",
"'__main__': t = TestGLSARGretl() t.test_all() ''' Model 5: OLS, using",
"-0.6736 0.5014 alpha(3) -0.0705413 0.0737058 -0.9571 0.3397 alpha(4) 0.0384531 0.0725763",
"[1.302014, 0.521520, 2, \"chi2\"] #TODO: not available het_breusch_pagan_konker = [0.709924,",
"Reciprocal condition number = 0.013819244 ''' ''' Test for ARCH",
"testing endogd = np.diff(d['realinv']) exogd = add_constant(np.c_[np.diff(d['realgdp'].values), d['realint'][:-1].values]) endogg =",
"python 3.2 changed behavior if np.isnan(lev[-1]['f1']): lev = np.genfromtxt(fpath, skip_header=3,",
"= 0.494432 with p-value = P(t(198) > 0.494432) = 0.621549",
"0.8616 uhat_1 -0.104707 0.0719948 -1.454 0.1475 uhat_2 -0.00898483 0.0742817 -0.1210",
"4.483669 10.784377 -16.782652 - 25.749991 Forecast evaluation statistics Mean Error",
"P(Chi-square(4) > 7.30776) = 0.120491: ''' ''' Variance Inflation Factors",
"*** realint_1 -0.613997 0.293619 -2.091 0.0378 ** Mean dependent var",
"lag=1, and smaller ssr from statsmodels.datasets import macrodata d2 =",
"#fstatistic, p-value, df1, df2 reset_2_3 = [5.219019, 0.00619, 2, 197,",
"0.00410778 0.0512274 0.08019 0.9362 Explained sum of squares = 2.60403",
"#multicollinearity vif = [1.002, 1.002] cond_1norm = 6862.0664 determinant =",
"0.621549, 198, \"t\"] #stats.t.sf(0.494432, 198)*2 #see cusum results in files",
"datasetswsm.greene as g #d = g.load('5-1') #growth rates gs_l_realinv =",
"10.70380), rsquared = (\"R-squared\", 0.676978), rsquared_adj = (\"Adjusted R-squared\", 0.673731),",
"added this based on Gretl #just rough test, low decimal",
"forecast #forecast mean y For 95% confidence intervals, t(199, 0.025)",
"- Null hypothesis: no autocorrelation Test statistic: LMF = 1.17928",
"= (\"Schwarz criterion\", 1543.875), hqic = (\"Hannan-Quinn\", 1537.966), resid_acf1 =",
"0.5968 Null hypothesis: no ARCH effect is present Test statistic:",
"= 0.653468 ''' ################ with OLS, HAC errors #Model 5:",
"= [4.771043, 0.312, 4, \"chi2\"] acorr_ljungbox4 = [5.23587, 0.264, 4,",
"decimal=7) #TODO c = oi.reset_ramsey(res, degree=2) compare_ftest(c, reset_2, decimal=(6,5)) c",
"= [23.962, 0.00001, 2, \"chi2\"] het_white = [33.503723, 0.000003, 5,",
"1 -0.10734 22530.9 2 -0.10814 22530.9 Model 4: Cochrane-Orcutt, using",
"ds_l_realinv rho = -0.108136 coefficient std. error t-ratio p-value -------------------------------------------------------------",
"P(Chi-square(4) > 7.30776) = 0.120491 Test of common factor restriction",
"3.113973 S.D. dependent var 18.67447 Sum squared resid 22530.90 S.E.",
"R^2 = 47782.7 / 70582.3 = 0.676978 F(2, 199) =",
"coefficient std. error t-ratio p-value -------------------------------------------------------- alpha(0) 97.0386 20.3234 4.775",
"where R(j) is the multiple correlation coefficient between variable j",
"Test statistic: F = 5.248951, with p-value = P(F(1,198) >",
"0.0379 ** sq_realint_1 0.662135 1.10919 0.5970 0.5512 Unadjusted R-squared =",
"no ARCH effect is present Test statistic: LM = 7.30776",
"-2.091, 0.0378, -1.19300, -0.0349939]]) # ** result_gretl_g1 = dict( endog_mean",
"regression for common factor test OLS, using observations 1959:3-2009:3 (T",
"(T = 202) Dependent variable: ds_l_realinv HAC standard errors, bandwidth",
"3.65e-018 *** ds_l_realgdp 4.37040 0.208146 21.00 2.93e-052 *** realint_1 -0.579253",
"possible value = 1.0 Values > 10.0 may indicate a",
"69 ?not 70 linear_squares = [7.52477, 0.0232283, 2, \"chi2\"] #Autocorrelation,",
"2 23891.3 Residual 22799.7 199 114.571 Total 70582.3 201 351.156",
"= (\"Adjusted R-squared\", 0.673710), fvalue = (\"F(2, 198)\", 221.0475), f_pvalue",
"assert_almost_equal(res.ssr, result_gretl_g1['ssr'][1], decimal=2) #assert_almost_equal(res.llf, result_gretl_g1['llf'][1], decimal=7) #not in gretl #assert_almost_equal(res.rsquared,",
"[-0.613997, 0.293619, -2.091, 0.0378, -1.19300, -0.0349939]]) # ** result_gretl_g1 =",
"= [3.01985, 0.1, 3, 196, \"maxF\"] #TODO check this, max",
"= [1.302014, 0.521520, 2, \"chi2\"] #TODO: not available het_breusch_pagan_konker ="
] |
[
"django.http import HttpResponse, JsonResponse, Http404 from django.contrib.auth.decorators import login_required from",
"from core.serializers import * from core.models import * from core.secrets",
"return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_popular(request): if request.method == 'GET': tweeprints",
"* from core.secrets import API_TOKEN, STRIPE_API_KEY import json from django.views.decorators.csrf",
"tweeprints = serialize('json', Tweeprint.objects.all(), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score',",
"return JsonResponse(categories, safe=False) def get_used_categories(request): used_categories = {t.category_slug: {'category': t.category,",
"'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_recent(request): if request.method ==",
"= {t.category_slug: {'category': t.category, 'slug': t.category_slug} for t in Tweeprint.objects.all()}.values()",
"'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-date_added'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json',",
"json_data = json.loads(request.body) try: tweeprint = Tweeprint.objects.create(link=str(json_data['link']), category=json_data['category']) except Exception",
"JsonResponse, Http404 from django.contrib.auth.decorators import login_required from django.core.serializers import serialize",
"t.category, 'slug': t.category_slug} for t in Tweeprint.objects.all()}.values() if request.method ==",
"'GET': return JsonResponse(list(used_categories), safe=False) def get_tweeprints(request): if request.method == 'GET':",
"django.core.serializers import serialize from core.serializers import * from core.models import",
"core.serializers import * from core.models import * from core.secrets import",
"from django.http import HttpResponse, JsonResponse, Http404 from django.contrib.auth.decorators import login_required",
"request.method == 'POST': form = request.body json_data = json.loads(request.body) try:",
"import json from django.views.decorators.csrf import csrf_exempt from django.shortcuts import get_object_or_404",
"= serialize('json', Tweeprint.objects.all(), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category',",
"get_categories(request): categories = [t[0] for t in Tweeprint.CHOICES] if request.method",
"HttpResponse, JsonResponse, Http404 from django.contrib.auth.decorators import login_required from django.core.serializers import",
"{t.category_slug: {'category': t.category, 'slug': t.category_slug} for t in Tweeprint.objects.all()}.values() if",
"'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") @csrf_exempt def submit(request): if",
"= serialize('json', Tweeprint.objects.filter(category_slug=category), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category',",
"content_type=\"application/json\") @csrf_exempt def submit(request): if request.method == 'POST': form =",
"Tweeprint.CHOICES] if request.method == 'GET': return JsonResponse(categories, safe=False) def get_used_categories(request):",
"serialize('json', Tweeprint.objects.all(), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug'))",
"fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(category,",
"request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-score'), fields=('id', 'date_added', 'link',",
"'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") @csrf_exempt",
"Tweeprint.objects.all()}.values() if request.method == 'GET': return JsonResponse(list(used_categories), safe=False) def get_tweeprints(request):",
"'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_recent(request): if request.method == 'GET':",
"login_required from django.core.serializers import serialize from core.serializers import * from",
"content_type=\"application/json\") def get_most_popular(request): if request.method == 'GET': tweeprints = serialize('json',",
"JsonResponse(list(used_categories), safe=False) def get_tweeprints(request): if request.method == 'GET': tweeprints =",
"'POST': form = request.body json_data = json.loads(request.body) try: tweeprint =",
"import HttpResponse, JsonResponse, Http404 from django.contrib.auth.decorators import login_required from django.core.serializers",
"import get_object_or_404 def get_category(request, category): category = serialize('json', Tweeprint.objects.filter(category_slug=category), fields=('id',",
"safe=False) def get_used_categories(request): used_categories = {t.category_slug: {'category': t.category, 'slug': t.category_slug}",
"from core.secrets import API_TOKEN, STRIPE_API_KEY import json from django.views.decorators.csrf import",
"from django.contrib.auth.decorators import login_required from django.core.serializers import serialize from core.serializers",
"'category_slug')) return HttpResponse(category, content_type=\"application/json\") def get_categories(request): categories = [t[0] for",
"submit(request): if request.method == 'POST': form = request.body json_data =",
"tweeprints = serialize('json', Tweeprint.objects.all().order_by('-score'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score',",
"json from django.views.decorators.csrf import csrf_exempt from django.shortcuts import get_object_or_404 def",
"django.contrib.auth.decorators import login_required from django.core.serializers import serialize from core.serializers import",
"Tweeprint.objects.all(), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return",
"if request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all(), fields=('id', 'date_added',",
"'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(category, content_type=\"application/json\") def",
"'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_recent(request): if request.method",
"'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(category, content_type=\"application/json\") def get_categories(request): categories",
"= serialize('json', Tweeprint.objects.all().order_by('-score'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category',",
"django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, JsonResponse,",
"'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") @csrf_exempt def",
"@csrf_exempt def submit(request): if request.method == 'POST': form = request.body",
"auth from django.shortcuts import render, redirect, get_object_or_404 from django.http import",
"serialize('json', Tweeprint.objects.filter(category_slug=category), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug'))",
"serialize from core.serializers import * from core.models import * from",
"'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_popular(request): if request.method == 'GET':",
"= [t[0] for t in Tweeprint.CHOICES] if request.method == 'GET':",
"== 'GET': return JsonResponse(list(used_categories), safe=False) def get_tweeprints(request): if request.method ==",
"return HttpResponse(tweeprints, content_type=\"application/json\") @csrf_exempt def submit(request): if request.method == 'POST':",
"HttpResponse(tweeprints, content_type=\"application/json\") @csrf_exempt def submit(request): if request.method == 'POST': form",
"import * from core.secrets import API_TOKEN, STRIPE_API_KEY import json from",
"get_tweeprints(request): if request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all(), fields=('id',",
"csrf_exempt from django.shortcuts import get_object_or_404 def get_category(request, category): category =",
"t.category_slug} for t in Tweeprint.objects.all()}.values() if request.method == 'GET': return",
"== 'POST': form = request.body json_data = json.loads(request.body) try: tweeprint",
"in Tweeprint.objects.all()}.values() if request.method == 'GET': return JsonResponse(list(used_categories), safe=False) def",
"== 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-score'), fields=('id', 'date_added', 'link', 'tweet_id',",
"if request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-score'), fields=('id', 'date_added',",
"STRIPE_API_KEY import json from django.views.decorators.csrf import csrf_exempt from django.shortcuts import",
"'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(category, content_type=\"application/json\")",
"requests import django.contrib.auth as auth from django.shortcuts import render, redirect,",
"import * from core.models import * from core.secrets import API_TOKEN,",
"get_most_popular(request): if request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-score'), fields=('id',",
"return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_recent(request): if request.method == 'GET': tweeprints",
"'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_popular(request): if",
"def get_categories(request): categories = [t[0] for t in Tweeprint.CHOICES] if",
"get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404 from django.contrib.auth.decorators import",
"form = request.body json_data = json.loads(request.body) try: tweeprint = Tweeprint.objects.create(link=str(json_data['link']),",
"as auth from django.shortcuts import render, redirect, get_object_or_404 from django.http",
"'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") @csrf_exempt def submit(request): if request.method ==",
"return HttpResponse(category, content_type=\"application/json\") def get_categories(request): categories = [t[0] for t",
"'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_popular(request):",
"API_TOKEN, STRIPE_API_KEY import json from django.views.decorators.csrf import csrf_exempt from django.shortcuts",
"except Exception as e: print(e) return HttpResponse('Submitted!') return HttpResponse(\"POST not",
"in Tweeprint.CHOICES] if request.method == 'GET': return JsonResponse(categories, safe=False) def",
"import csrf_exempt from django.shortcuts import get_object_or_404 def get_category(request, category): category",
"try: tweeprint = Tweeprint.objects.create(link=str(json_data['link']), category=json_data['category']) except Exception as e: print(e)",
"JsonResponse(categories, safe=False) def get_used_categories(request): used_categories = {t.category_slug: {'category': t.category, 'slug':",
"HttpResponse(category, content_type=\"application/json\") def get_categories(request): categories = [t[0] for t in",
"'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\")",
"'GET': return JsonResponse(categories, safe=False) def get_used_categories(request): used_categories = {t.category_slug: {'category':",
"'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_recent(request): if",
"def submit(request): if request.method == 'POST': form = request.body json_data",
"= Tweeprint.objects.create(link=str(json_data['link']), category=json_data['category']) except Exception as e: print(e) return HttpResponse('Submitted!')",
"request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-date_added'), fields=('id', 'date_added', 'link',",
"'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_popular(request): if request.method ==",
"safe=False) def get_tweeprints(request): if request.method == 'GET': tweeprints = serialize('json',",
"tweeprints = serialize('json', Tweeprint.objects.all().order_by('-date_added'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score',",
"import requests import django.contrib.auth as auth from django.shortcuts import render,",
"import API_TOKEN, STRIPE_API_KEY import json from django.views.decorators.csrf import csrf_exempt from",
"return JsonResponse(list(used_categories), safe=False) def get_tweeprints(request): if request.method == 'GET': tweeprints",
"serialize('json', Tweeprint.objects.all().order_by('-score'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug'))",
"* from core.models import * from core.secrets import API_TOKEN, STRIPE_API_KEY",
"Http404 from django.contrib.auth.decorators import login_required from django.core.serializers import serialize from",
"Tweeprint.objects.all().order_by('-date_added'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return",
"'slug': t.category_slug} for t in Tweeprint.objects.all()}.values() if request.method == 'GET':",
"'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_popular(request): if request.method",
"get_category(request, category): category = serialize('json', Tweeprint.objects.filter(category_slug=category), fields=('id', 'date_added', 'link', 'tweet_id',",
"get_object_or_404 def get_category(request, category): category = serialize('json', Tweeprint.objects.filter(category_slug=category), fields=('id', 'date_added',",
"request.method == 'GET': return JsonResponse(categories, safe=False) def get_used_categories(request): used_categories =",
"def get_tweeprints(request): if request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all(),",
"category): category = serialize('json', Tweeprint.objects.filter(category_slug=category), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json',",
"serialize('json', Tweeprint.objects.all().order_by('-date_added'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug'))",
"content_type=\"application/json\") def get_most_recent(request): if request.method == 'GET': tweeprints = serialize('json',",
"request.method == 'GET': return JsonResponse(list(used_categories), safe=False) def get_tweeprints(request): if request.method",
"core.secrets import API_TOKEN, STRIPE_API_KEY import json from django.views.decorators.csrf import csrf_exempt",
"request.body json_data = json.loads(request.body) try: tweeprint = Tweeprint.objects.create(link=str(json_data['link']), category=json_data['category']) except",
"for t in Tweeprint.objects.all()}.values() if request.method == 'GET': return JsonResponse(list(used_categories),",
"HttpResponse(tweeprints, content_type=\"application/json\") def get_most_recent(request): if request.method == 'GET': tweeprints =",
"category=json_data['category']) except Exception as e: print(e) return HttpResponse('Submitted!') return HttpResponse(\"POST",
"'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def get_most_recent(request):",
"= request.body json_data = json.loads(request.body) try: tweeprint = Tweeprint.objects.create(link=str(json_data['link']), category=json_data['category'])",
"def get_most_popular(request): if request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-score'),",
"Tweeprint.objects.create(link=str(json_data['link']), category=json_data['category']) except Exception as e: print(e) return HttpResponse('Submitted!') return",
"'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(category, content_type=\"application/json\") def get_categories(request):",
"== 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-date_added'), fields=('id', 'date_added', 'link', 'tweet_id',",
"import django.contrib.auth as auth from django.shortcuts import render, redirect, get_object_or_404",
"redirect, get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404 from django.contrib.auth.decorators",
"'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") @csrf_exempt def submit(request):",
"tweeprint = Tweeprint.objects.create(link=str(json_data['link']), category=json_data['category']) except Exception as e: print(e) return",
"== 'GET': return JsonResponse(categories, safe=False) def get_used_categories(request): used_categories = {t.category_slug:",
"import render, redirect, get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404",
"{'category': t.category, 'slug': t.category_slug} for t in Tweeprint.objects.all()}.values() if request.method",
"request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all(), fields=('id', 'date_added', 'link',",
"'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-score'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json',",
"core.models import * from core.secrets import API_TOKEN, STRIPE_API_KEY import json",
"from core.models import * from core.secrets import API_TOKEN, STRIPE_API_KEY import",
"<gh_stars>1-10 import requests import django.contrib.auth as auth from django.shortcuts import",
"def get_most_recent(request): if request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-date_added'),",
"from django.core.serializers import serialize from core.serializers import * from core.models",
"import login_required from django.core.serializers import serialize from core.serializers import *",
"json.loads(request.body) try: tweeprint = Tweeprint.objects.create(link=str(json_data['link']), category=json_data['category']) except Exception as e:",
"category = serialize('json', Tweeprint.objects.filter(category_slug=category), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score',",
"django.shortcuts import get_object_or_404 def get_category(request, category): category = serialize('json', Tweeprint.objects.filter(category_slug=category),",
"Tweeprint.objects.filter(category_slug=category), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return",
"'score', 'category', 'category_slug')) return HttpResponse(category, content_type=\"application/json\") def get_categories(request): categories =",
"get_used_categories(request): used_categories = {t.category_slug: {'category': t.category, 'slug': t.category_slug} for t",
"'GET': tweeprints = serialize('json', Tweeprint.objects.all(), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json',",
"Exception as e: print(e) return HttpResponse('Submitted!') return HttpResponse(\"POST not made\")",
"fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints,",
"'category', 'category_slug')) return HttpResponse(category, content_type=\"application/json\") def get_categories(request): categories = [t[0]",
"from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse,",
"import serialize from core.serializers import * from core.models import *",
"render, redirect, get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404 from",
"'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") @csrf_exempt def submit(request): if request.method",
"HttpResponse(tweeprints, content_type=\"application/json\") def get_most_popular(request): if request.method == 'GET': tweeprints =",
"if request.method == 'GET': return JsonResponse(list(used_categories), safe=False) def get_tweeprints(request): if",
"if request.method == 'POST': form = request.body json_data = json.loads(request.body)",
"def get_used_categories(request): used_categories = {t.category_slug: {'category': t.category, 'slug': t.category_slug} for",
"if request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-date_added'), fields=('id', 'date_added',",
"[t[0] for t in Tweeprint.CHOICES] if request.method == 'GET': return",
"== 'GET': tweeprints = serialize('json', Tweeprint.objects.all(), fields=('id', 'date_added', 'link', 'tweet_id',",
"t in Tweeprint.CHOICES] if request.method == 'GET': return JsonResponse(categories, safe=False)",
"django.contrib.auth as auth from django.shortcuts import render, redirect, get_object_or_404 from",
"used_categories = {t.category_slug: {'category': t.category, 'slug': t.category_slug} for t in",
"= json.loads(request.body) try: tweeprint = Tweeprint.objects.create(link=str(json_data['link']), category=json_data['category']) except Exception as",
"django.views.decorators.csrf import csrf_exempt from django.shortcuts import get_object_or_404 def get_category(request, category):",
"t in Tweeprint.objects.all()}.values() if request.method == 'GET': return JsonResponse(list(used_categories), safe=False)",
"'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return HttpResponse(tweeprints, content_type=\"application/json\") def",
"from django.views.decorators.csrf import csrf_exempt from django.shortcuts import get_object_or_404 def get_category(request,",
"from django.shortcuts import get_object_or_404 def get_category(request, category): category = serialize('json',",
"for t in Tweeprint.CHOICES] if request.method == 'GET': return JsonResponse(categories,",
"= serialize('json', Tweeprint.objects.all().order_by('-date_added'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category',",
"categories = [t[0] for t in Tweeprint.CHOICES] if request.method ==",
"def get_category(request, category): category = serialize('json', Tweeprint.objects.filter(category_slug=category), fields=('id', 'date_added', 'link',",
"Tweeprint.objects.all().order_by('-score'), fields=('id', 'date_added', 'link', 'tweet_id', 'tweet_json', 'score', 'category', 'category_slug')) return",
"content_type=\"application/json\") def get_categories(request): categories = [t[0] for t in Tweeprint.CHOICES]",
"get_most_recent(request): if request.method == 'GET': tweeprints = serialize('json', Tweeprint.objects.all().order_by('-date_added'), fields=('id',",
"if request.method == 'GET': return JsonResponse(categories, safe=False) def get_used_categories(request): used_categories"
] |
[
"features for simulating bioreactor operation. \"\"\" from .base import Organism,",
"simulating bioreactor operation. \"\"\" from .base import Organism, Bioreactor from",
"import Organism, Bioreactor from .bioreactors import ANAEROBIC, AEROBIC, MICROAEROBIC from",
"__future__ import absolute_import __author__ = 'kaizhuang' \"\"\" Package implementing features",
"Organism, Bioreactor from .bioreactors import ANAEROBIC, AEROBIC, MICROAEROBIC from .bioreactors",
"AEROBIC, MICROAEROBIC from .bioreactors import Bioreactor_ox, IdealBatch, IdealFedbatch from framed.bioreactor.dfba",
"'kaizhuang' \"\"\" Package implementing features for simulating bioreactor operation. \"\"\"",
"bioreactor operation. \"\"\" from .base import Organism, Bioreactor from .bioreactors",
"from .bioreactors import ANAEROBIC, AEROBIC, MICROAEROBIC from .bioreactors import Bioreactor_ox,",
"<gh_stars>10-100 from __future__ import absolute_import __author__ = 'kaizhuang' \"\"\" Package",
"Package implementing features for simulating bioreactor operation. \"\"\" from .base",
".base import Organism, Bioreactor from .bioreactors import ANAEROBIC, AEROBIC, MICROAEROBIC",
"operation. \"\"\" from .base import Organism, Bioreactor from .bioreactors import",
"Bioreactor from .bioreactors import ANAEROBIC, AEROBIC, MICROAEROBIC from .bioreactors import",
"MICROAEROBIC from .bioreactors import Bioreactor_ox, IdealBatch, IdealFedbatch from framed.bioreactor.dfba import",
"from .bioreactors import Bioreactor_ox, IdealBatch, IdealFedbatch from framed.bioreactor.dfba import *",
"import ANAEROBIC, AEROBIC, MICROAEROBIC from .bioreactors import Bioreactor_ox, IdealBatch, IdealFedbatch",
"__author__ = 'kaizhuang' \"\"\" Package implementing features for simulating bioreactor",
"absolute_import __author__ = 'kaizhuang' \"\"\" Package implementing features for simulating",
"ANAEROBIC, AEROBIC, MICROAEROBIC from .bioreactors import Bioreactor_ox, IdealBatch, IdealFedbatch from",
"from .base import Organism, Bioreactor from .bioreactors import ANAEROBIC, AEROBIC,",
"for simulating bioreactor operation. \"\"\" from .base import Organism, Bioreactor",
"from __future__ import absolute_import __author__ = 'kaizhuang' \"\"\" Package implementing",
"import absolute_import __author__ = 'kaizhuang' \"\"\" Package implementing features for",
"\"\"\" Package implementing features for simulating bioreactor operation. \"\"\" from",
"= 'kaizhuang' \"\"\" Package implementing features for simulating bioreactor operation.",
"implementing features for simulating bioreactor operation. \"\"\" from .base import",
"\"\"\" from .base import Organism, Bioreactor from .bioreactors import ANAEROBIC,",
".bioreactors import ANAEROBIC, AEROBIC, MICROAEROBIC from .bioreactors import Bioreactor_ox, IdealBatch,"
] |
[
"import parse_template_boolean_value def preprocess(data, lang): data[\"arg_negate\"] = parse_template_boolean_value(data, parameter=\"arg_negate\", default_value=False)",
"parse_template_boolean_value def preprocess(data, lang): data[\"arg_negate\"] = parse_template_boolean_value(data, parameter=\"arg_negate\", default_value=False) data[\"arg_is_regex\"]",
"ssg.utils import parse_template_boolean_value def preprocess(data, lang): data[\"arg_negate\"] = parse_template_boolean_value(data, parameter=\"arg_negate\",",
"from ssg.utils import parse_template_boolean_value def preprocess(data, lang): data[\"arg_negate\"] = parse_template_boolean_value(data,",
"def preprocess(data, lang): data[\"arg_negate\"] = parse_template_boolean_value(data, parameter=\"arg_negate\", default_value=False) data[\"arg_is_regex\"] =",
"= parse_template_boolean_value(data, parameter=\"arg_negate\", default_value=False) data[\"arg_is_regex\"] = parse_template_boolean_value(data, parameter=\"arg_is_regex\", default_value=False) return",
"data[\"arg_negate\"] = parse_template_boolean_value(data, parameter=\"arg_negate\", default_value=False) data[\"arg_is_regex\"] = parse_template_boolean_value(data, parameter=\"arg_is_regex\", default_value=False)",
"lang): data[\"arg_negate\"] = parse_template_boolean_value(data, parameter=\"arg_negate\", default_value=False) data[\"arg_is_regex\"] = parse_template_boolean_value(data, parameter=\"arg_is_regex\",",
"preprocess(data, lang): data[\"arg_negate\"] = parse_template_boolean_value(data, parameter=\"arg_negate\", default_value=False) data[\"arg_is_regex\"] = parse_template_boolean_value(data,",
"<reponame>deperrone/content<filename>shared/templates/coreos_kernel_option/template.py from ssg.utils import parse_template_boolean_value def preprocess(data, lang): data[\"arg_negate\"] =",
"parse_template_boolean_value(data, parameter=\"arg_negate\", default_value=False) data[\"arg_is_regex\"] = parse_template_boolean_value(data, parameter=\"arg_is_regex\", default_value=False) return data"
] |
[
"coding: UTF-8 -*- \"\"\" This file is part of Pondus,",
"# -*- coding: UTF-8 -*- \"\"\" This file is part",
"This file is part of Pondus, a personal weight manager.",
"part of Pondus, a personal weight manager. Copyright (C) 2011",
"is part of Pondus, a personal weight manager. Copyright (C)",
"UTF-8 -*- \"\"\" This file is part of Pondus, a",
"software licensed under the MIT license. For details see LICENSE",
"see LICENSE or http://www.opensource.org/licenses/mit-license.php \"\"\" __all__ = ['csv_backend', 'sportstracker_backend', 'xml_backend',",
"2011 <NAME> <<EMAIL>> This program is free software licensed under",
"(C) 2011 <NAME> <<EMAIL>> This program is free software licensed",
"Pondus, a personal weight manager. Copyright (C) 2011 <NAME> <<EMAIL>>",
"program is free software licensed under the MIT license. For",
"of Pondus, a personal weight manager. Copyright (C) 2011 <NAME>",
"weight manager. Copyright (C) 2011 <NAME> <<EMAIL>> This program is",
"personal weight manager. Copyright (C) 2011 <NAME> <<EMAIL>> This program",
"the MIT license. For details see LICENSE or http://www.opensource.org/licenses/mit-license.php \"\"\"",
"manager. Copyright (C) 2011 <NAME> <<EMAIL>> This program is free",
"LICENSE or http://www.opensource.org/licenses/mit-license.php \"\"\" __all__ = ['csv_backend', 'sportstracker_backend', 'xml_backend', 'xml_backend_old']",
"-*- \"\"\" This file is part of Pondus, a personal",
"license. For details see LICENSE or http://www.opensource.org/licenses/mit-license.php \"\"\" __all__ =",
"MIT license. For details see LICENSE or http://www.opensource.org/licenses/mit-license.php \"\"\" __all__",
"is free software licensed under the MIT license. For details",
"licensed under the MIT license. For details see LICENSE or",
"under the MIT license. For details see LICENSE or http://www.opensource.org/licenses/mit-license.php",
"For details see LICENSE or http://www.opensource.org/licenses/mit-license.php \"\"\" __all__ = ['csv_backend',",
"a personal weight manager. Copyright (C) 2011 <NAME> <<EMAIL>> This",
"file is part of Pondus, a personal weight manager. Copyright",
"-*- coding: UTF-8 -*- \"\"\" This file is part of",
"<NAME> <<EMAIL>> This program is free software licensed under the",
"Copyright (C) 2011 <NAME> <<EMAIL>> This program is free software",
"<<EMAIL>> This program is free software licensed under the MIT",
"details see LICENSE or http://www.opensource.org/licenses/mit-license.php \"\"\" __all__ = ['csv_backend', 'sportstracker_backend',",
"\"\"\" This file is part of Pondus, a personal weight",
"free software licensed under the MIT license. For details see",
"This program is free software licensed under the MIT license."
] |
[
"], packages=find_packages(exclude=[\"collections\", \"time\", \"math\", \"re\", \"os\"]), include_package_data=True, # install_requires=[\"networkx\", \"pandas\",",
"# author_email=\"<EMAIL>\", license=\"MIT\", classifiers=[ \"License :: OSI Approved :: MIT",
"file README = (HERE / \"README.md\").read_text() # This call to",
"license=\"MIT\", classifiers=[ \"License :: OSI Approved :: MIT License\", \"Programming",
"find_packages, setup # The directory containing this file HERE =",
"\"progressbar\", \"fuzzywuzzy\", # \"os\", \"requests\", \"math\", \"time\", \"collections\", \"re\"] )",
"Companies House API\", long_description=README, long_description_content_type=\"text/markdown\", url=\"https://github.com/specialprocedures/chpy\", author=\"<NAME>\", # author_email=\"<EMAIL>\", license=\"MIT\",",
"License\", \"Programming Language :: Python :: 3\", \"Programming Language ::",
"\"os\"]), include_package_data=True, # install_requires=[\"networkx\", \"pandas\", \"progressbar\", \"fuzzywuzzy\", # \"os\", \"requests\",",
"import pathlib from setuptools import find_packages, setup # The directory",
"# install_requires=[\"networkx\", \"pandas\", \"progressbar\", \"fuzzywuzzy\", # \"os\", \"requests\", \"math\", \"time\",",
"classifiers=[ \"License :: OSI Approved :: MIT License\", \"Programming Language",
"Language :: Python :: 3\", \"Programming Language :: Python ::",
"to setup() does all the work setup( name=\"chpy\", version=\"0.1.1\", description=\"Build",
"MIT License\", \"Programming Language :: Python :: 3\", \"Programming Language",
"pathlib.Path(__file__).parent # The text of the README file README =",
"version=\"0.1.1\", description=\"Build networks from the Companies House API\", long_description=README, long_description_content_type=\"text/markdown\",",
"\"Programming Language :: Python :: 3.7\", ], packages=find_packages(exclude=[\"collections\", \"time\", \"math\",",
"\"pandas\", \"progressbar\", \"fuzzywuzzy\", # \"os\", \"requests\", \"math\", \"time\", \"collections\", \"re\"]",
"text of the README file README = (HERE / \"README.md\").read_text()",
"README = (HERE / \"README.md\").read_text() # This call to setup()",
"the work setup( name=\"chpy\", version=\"0.1.1\", description=\"Build networks from the Companies",
"packages=find_packages(exclude=[\"collections\", \"time\", \"math\", \"re\", \"os\"]), include_package_data=True, # install_requires=[\"networkx\", \"pandas\", \"progressbar\",",
"Language :: Python :: 3.7\", ], packages=find_packages(exclude=[\"collections\", \"time\", \"math\", \"re\",",
"(HERE / \"README.md\").read_text() # This call to setup() does all",
"OSI Approved :: MIT License\", \"Programming Language :: Python ::",
"Approved :: MIT License\", \"Programming Language :: Python :: 3\",",
":: Python :: 3\", \"Programming Language :: Python :: 3.7\",",
"url=\"https://github.com/specialprocedures/chpy\", author=\"<NAME>\", # author_email=\"<EMAIL>\", license=\"MIT\", classifiers=[ \"License :: OSI Approved",
"HERE = pathlib.Path(__file__).parent # The text of the README file",
"from setuptools import find_packages, setup # The directory containing this",
"\"Programming Language :: Python :: 3\", \"Programming Language :: Python",
"the README file README = (HERE / \"README.md\").read_text() # This",
"does all the work setup( name=\"chpy\", version=\"0.1.1\", description=\"Build networks from",
":: Python :: 3.7\", ], packages=find_packages(exclude=[\"collections\", \"time\", \"math\", \"re\", \"os\"]),",
"/ \"README.md\").read_text() # This call to setup() does all the",
"from the Companies House API\", long_description=README, long_description_content_type=\"text/markdown\", url=\"https://github.com/specialprocedures/chpy\", author=\"<NAME>\", #",
"name=\"chpy\", version=\"0.1.1\", description=\"Build networks from the Companies House API\", long_description=README,",
"The directory containing this file HERE = pathlib.Path(__file__).parent # The",
"\"math\", \"re\", \"os\"]), include_package_data=True, # install_requires=[\"networkx\", \"pandas\", \"progressbar\", \"fuzzywuzzy\", #",
"Python :: 3\", \"Programming Language :: Python :: 3.7\", ],",
"author_email=\"<EMAIL>\", license=\"MIT\", classifiers=[ \"License :: OSI Approved :: MIT License\",",
"install_requires=[\"networkx\", \"pandas\", \"progressbar\", \"fuzzywuzzy\", # \"os\", \"requests\", \"math\", \"time\", \"collections\",",
"setuptools import find_packages, setup # The directory containing this file",
"\"re\", \"os\"]), include_package_data=True, # install_requires=[\"networkx\", \"pandas\", \"progressbar\", \"fuzzywuzzy\", # \"os\",",
"# This call to setup() does all the work setup(",
"3\", \"Programming Language :: Python :: 3.7\", ], packages=find_packages(exclude=[\"collections\", \"time\",",
"all the work setup( name=\"chpy\", version=\"0.1.1\", description=\"Build networks from the",
"pathlib from setuptools import find_packages, setup # The directory containing",
"networks from the Companies House API\", long_description=README, long_description_content_type=\"text/markdown\", url=\"https://github.com/specialprocedures/chpy\", author=\"<NAME>\",",
":: 3.7\", ], packages=find_packages(exclude=[\"collections\", \"time\", \"math\", \"re\", \"os\"]), include_package_data=True, #",
"3.7\", ], packages=find_packages(exclude=[\"collections\", \"time\", \"math\", \"re\", \"os\"]), include_package_data=True, # install_requires=[\"networkx\",",
"call to setup() does all the work setup( name=\"chpy\", version=\"0.1.1\",",
"= (HERE / \"README.md\").read_text() # This call to setup() does",
":: MIT License\", \"Programming Language :: Python :: 3\", \"Programming",
"\"README.md\").read_text() # This call to setup() does all the work",
"\"License :: OSI Approved :: MIT License\", \"Programming Language ::",
"This call to setup() does all the work setup( name=\"chpy\",",
"= pathlib.Path(__file__).parent # The text of the README file README",
"work setup( name=\"chpy\", version=\"0.1.1\", description=\"Build networks from the Companies House",
":: 3\", \"Programming Language :: Python :: 3.7\", ], packages=find_packages(exclude=[\"collections\",",
"\"time\", \"math\", \"re\", \"os\"]), include_package_data=True, # install_requires=[\"networkx\", \"pandas\", \"progressbar\", \"fuzzywuzzy\",",
"description=\"Build networks from the Companies House API\", long_description=README, long_description_content_type=\"text/markdown\", url=\"https://github.com/specialprocedures/chpy\",",
"README file README = (HERE / \"README.md\").read_text() # This call",
"containing this file HERE = pathlib.Path(__file__).parent # The text of",
"of the README file README = (HERE / \"README.md\").read_text() #",
"file HERE = pathlib.Path(__file__).parent # The text of the README",
"author=\"<NAME>\", # author_email=\"<EMAIL>\", license=\"MIT\", classifiers=[ \"License :: OSI Approved ::",
"this file HERE = pathlib.Path(__file__).parent # The text of the",
"setup( name=\"chpy\", version=\"0.1.1\", description=\"Build networks from the Companies House API\",",
"# The text of the README file README = (HERE",
"# The directory containing this file HERE = pathlib.Path(__file__).parent #",
"include_package_data=True, # install_requires=[\"networkx\", \"pandas\", \"progressbar\", \"fuzzywuzzy\", # \"os\", \"requests\", \"math\",",
"directory containing this file HERE = pathlib.Path(__file__).parent # The text",
"the Companies House API\", long_description=README, long_description_content_type=\"text/markdown\", url=\"https://github.com/specialprocedures/chpy\", author=\"<NAME>\", # author_email=\"<EMAIL>\",",
"long_description=README, long_description_content_type=\"text/markdown\", url=\"https://github.com/specialprocedures/chpy\", author=\"<NAME>\", # author_email=\"<EMAIL>\", license=\"MIT\", classifiers=[ \"License ::",
"House API\", long_description=README, long_description_content_type=\"text/markdown\", url=\"https://github.com/specialprocedures/chpy\", author=\"<NAME>\", # author_email=\"<EMAIL>\", license=\"MIT\", classifiers=[",
":: OSI Approved :: MIT License\", \"Programming Language :: Python",
"import find_packages, setup # The directory containing this file HERE",
"Python :: 3.7\", ], packages=find_packages(exclude=[\"collections\", \"time\", \"math\", \"re\", \"os\"]), include_package_data=True,",
"setup # The directory containing this file HERE = pathlib.Path(__file__).parent",
"long_description_content_type=\"text/markdown\", url=\"https://github.com/specialprocedures/chpy\", author=\"<NAME>\", # author_email=\"<EMAIL>\", license=\"MIT\", classifiers=[ \"License :: OSI",
"The text of the README file README = (HERE /",
"setup() does all the work setup( name=\"chpy\", version=\"0.1.1\", description=\"Build networks",
"API\", long_description=README, long_description_content_type=\"text/markdown\", url=\"https://github.com/specialprocedures/chpy\", author=\"<NAME>\", # author_email=\"<EMAIL>\", license=\"MIT\", classifiers=[ \"License",
"<filename>setup.py import pathlib from setuptools import find_packages, setup # The"
] |
[
"= frame.get('filename') or frame.get('abs_path') if fn: func = frame.get('function') if",
"'<unknown>' if not metadata.get('value'): return ty return u'{}: {}'.format( ty,",
"trim from sentry.utils.strings import truncatechars from .base import BaseEvent def",
"fn: func = frame.get('function') if func is not None: from",
"if ty is None: return metadata.get('function') or '<unknown>' if not",
"If the exception mechanism indicates a synthetic exception we do",
"} # If the exception mechanism indicates a synthetic exception",
"synthetic exception we do not # want to record the",
"if fn: rv['filename'] = fn if func: rv['function'] = func",
".base import BaseEvent def get_crash_location(exception, platform=None): default = None for",
"frame.get('filename') or frame.get('abs_path') if fn: func = frame.get('function') if func",
"# If the exception mechanism indicates a synthetic exception we",
"from sentry.utils.safe import get_path, trim from sentry.utils.strings import truncatechars from",
"Attach crash location if available if loc is not None:",
"= func return rv def get_title(self, metadata): ty = metadata.get('type')",
"truncatechars from .base import BaseEvent def get_crash_location(exception, platform=None): default =",
"for frame in reversed(get_path(exception, 'stacktrace', 'frames', filter=True) or ()): fn",
"rv['function'] = func return rv def get_title(self, metadata): ty =",
"mechanism indicates a synthetic exception we do not # want",
"available if loc is not None: fn, func = loc",
"{ 'value': trim(get_path(exception, 'value', default=''), 1024), } # If the",
"= None for frame in reversed(get_path(exception, 'stacktrace', 'frames', filter=True) or",
"def has_metadata(self, data): exception = get_path(data, 'exception', 'values', -1) return",
"location if available if loc is not None: fn, func",
"default = None for frame in reversed(get_path(exception, 'stacktrace', 'frames', filter=True)",
"absolute_import import six from sentry.utils.safe import get_path, trim from sentry.utils.strings",
"if func is not None: from sentry.interfaces.stacktrace import trim_function_name func",
"def get_metadata(self, data): exception = get_path(data, 'exception', 'values', -1) if",
"is not None: from sentry.interfaces.stacktrace import trim_function_name func = trim_function_name(func,",
"exception we do not # want to record the type",
"v in six.itervalues(exception)) def get_metadata(self, data): exception = get_path(data, 'exception',",
"trim_function_name(func, frame.get('platform') or platform) if frame.get('in_app'): return fn, func if",
"# Attach crash location if available if loc is not",
"if fn: func = frame.get('function') if func is not None:",
"or '<unknown>' if not metadata.get('value'): return ty return u'{}: {}'.format(",
"data): exception = get_path(data, 'exception', 'values', -1) if not exception:",
"get_metadata(self, data): exception = get_path(data, 'exception', 'values', -1) if not",
"is not None: fn, func = loc if fn: rv['filename']",
"None: fn, func = loc if fn: rv['filename'] = fn",
"return default class ErrorEvent(BaseEvent): key = 'error' def has_metadata(self, data):",
"default = fn, func return default class ErrorEvent(BaseEvent): key =",
"any(v is not None for v in six.itervalues(exception)) def get_metadata(self,",
"loc = get_crash_location(exception, data.get('platform')) rv = { 'value': trim(get_path(exception, 'value',",
"'stacktrace', 'frames', filter=True) or ()): fn = frame.get('filename') or frame.get('abs_path')",
"fn, func = loc if fn: rv['filename'] = fn if",
"func = loc if fn: rv['filename'] = fn if func:",
"= 'error' def has_metadata(self, data): exception = get_path(data, 'exception', 'values',",
"we do not # want to record the type and",
"is not None for v in six.itervalues(exception)) def get_metadata(self, data):",
"six from sentry.utils.safe import get_path, trim from sentry.utils.strings import truncatechars",
"the metadata. if not get_path(exception, 'mechanism', 'synthetic'): rv['type'] = trim(get_path(exception,",
"= trim_function_name(func, frame.get('platform') or platform) if frame.get('in_app'): return fn, func",
"= { 'value': trim(get_path(exception, 'value', default=''), 1024), } # If",
"fn, func return default class ErrorEvent(BaseEvent): key = 'error' def",
"value into the metadata. if not get_path(exception, 'mechanism', 'synthetic'): rv['type']",
"return {} loc = get_crash_location(exception, data.get('platform')) rv = { 'value':",
"return exception and any(v is not None for v in",
"and value into the metadata. if not get_path(exception, 'mechanism', 'synthetic'):",
"to record the type and value into the metadata. if",
"None: return metadata.get('function') or '<unknown>' if not metadata.get('value'): return ty",
"'values', -1) if not exception: return {} loc = get_crash_location(exception,",
"sentry.utils.strings import truncatechars from .base import BaseEvent def get_crash_location(exception, platform=None):",
"the type and value into the metadata. if not get_path(exception,",
"return metadata.get('function') or '<unknown>' if not metadata.get('value'): return ty return",
"return ty return u'{}: {}'.format( ty, truncatechars(metadata['value'].splitlines()[0], 100), ) def",
"from .base import BaseEvent def get_crash_location(exception, platform=None): default = None",
"do not # want to record the type and value",
"not exception: return {} loc = get_crash_location(exception, data.get('platform')) rv =",
"u'{}: {}'.format( ty, truncatechars(metadata['value'].splitlines()[0], 100), ) def get_location(self, metadata): return",
"'value', default=''), 1024), } # If the exception mechanism indicates",
"func: rv['function'] = func return rv def get_title(self, metadata): ty",
"'values', -1) return exception and any(v is not None for",
"crash location if available if loc is not None: fn,",
"None: from sentry.interfaces.stacktrace import trim_function_name func = trim_function_name(func, frame.get('platform') or",
"fn = frame.get('filename') or frame.get('abs_path') if fn: func = frame.get('function')",
"frame.get('abs_path') if fn: func = frame.get('function') if func is not",
"if available if loc is not None: fn, func =",
"BaseEvent def get_crash_location(exception, platform=None): default = None for frame in",
"exception and any(v is not None for v in six.itervalues(exception))",
"metadata.get('function') or '<unknown>' if not metadata.get('value'): return ty return u'{}:",
"import trim_function_name func = trim_function_name(func, frame.get('platform') or platform) if frame.get('in_app'):",
"or platform) if frame.get('in_app'): return fn, func if default is",
"class ErrorEvent(BaseEvent): key = 'error' def has_metadata(self, data): exception =",
"type and value into the metadata. if not get_path(exception, 'mechanism',",
"the exception mechanism indicates a synthetic exception we do not",
"func return rv def get_title(self, metadata): ty = metadata.get('type') if",
"__future__ import absolute_import import six from sentry.utils.safe import get_path, trim",
"metadata. if not get_path(exception, 'mechanism', 'synthetic'): rv['type'] = trim(get_path(exception, 'type',",
"or frame.get('abs_path') if fn: func = frame.get('function') if func is",
"not None: fn, func = loc if fn: rv['filename'] =",
"record the type and value into the metadata. if not",
"in six.itervalues(exception)) def get_metadata(self, data): exception = get_path(data, 'exception', 'values',",
"exception = get_path(data, 'exception', 'values', -1) if not exception: return",
"1024), } # If the exception mechanism indicates a synthetic",
"fn if func: rv['function'] = func return rv def get_title(self,",
"= get_path(data, 'exception', 'values', -1) return exception and any(v is",
"return rv def get_title(self, metadata): ty = metadata.get('type') if ty",
"not None: from sentry.interfaces.stacktrace import trim_function_name func = trim_function_name(func, frame.get('platform')",
"if not exception: return {} loc = get_crash_location(exception, data.get('platform')) rv",
"= get_path(data, 'exception', 'values', -1) if not exception: return {}",
"= trim(get_path(exception, 'type', default='Error'), 128) # Attach crash location if",
"filter=True) or ()): fn = frame.get('filename') or frame.get('abs_path') if fn:",
"rv def get_title(self, metadata): ty = metadata.get('type') if ty is",
"None: default = fn, func return default class ErrorEvent(BaseEvent): key",
"'exception', 'values', -1) if not exception: return {} loc =",
"if loc is not None: fn, func = loc if",
"from __future__ import absolute_import import six from sentry.utils.safe import get_path,",
"frame.get('platform') or platform) if frame.get('in_app'): return fn, func if default",
"platform=None): default = None for frame in reversed(get_path(exception, 'stacktrace', 'frames',",
"reversed(get_path(exception, 'stacktrace', 'frames', filter=True) or ()): fn = frame.get('filename') or",
"func if default is None: default = fn, func return",
"= loc if fn: rv['filename'] = fn if func: rv['function']",
"'synthetic'): rv['type'] = trim(get_path(exception, 'type', default='Error'), 128) # Attach crash",
"frame.get('function') if func is not None: from sentry.interfaces.stacktrace import trim_function_name",
"not # want to record the type and value into",
"def get_crash_location(exception, platform=None): default = None for frame in reversed(get_path(exception,",
"'error' def has_metadata(self, data): exception = get_path(data, 'exception', 'values', -1)",
"loc if fn: rv['filename'] = fn if func: rv['function'] =",
"import get_path, trim from sentry.utils.strings import truncatechars from .base import",
"{}'.format( ty, truncatechars(metadata['value'].splitlines()[0], 100), ) def get_location(self, metadata): return metadata.get('filename')",
"indicates a synthetic exception we do not # want to",
"fn, func if default is None: default = fn, func",
"import absolute_import import six from sentry.utils.safe import get_path, trim from",
"loc is not None: fn, func = loc if fn:",
"sentry.utils.safe import get_path, trim from sentry.utils.strings import truncatechars from .base",
"in reversed(get_path(exception, 'stacktrace', 'frames', filter=True) or ()): fn = frame.get('filename')",
"<gh_stars>0 from __future__ import absolute_import import six from sentry.utils.safe import",
"ty return u'{}: {}'.format( ty, truncatechars(metadata['value'].splitlines()[0], 100), ) def get_location(self,",
"if default is None: default = fn, func return default",
"frame in reversed(get_path(exception, 'stacktrace', 'frames', filter=True) or ()): fn =",
"not None for v in six.itervalues(exception)) def get_metadata(self, data): exception",
"not metadata.get('value'): return ty return u'{}: {}'.format( ty, truncatechars(metadata['value'].splitlines()[0], 100),",
"get_crash_location(exception, platform=None): default = None for frame in reversed(get_path(exception, 'stacktrace',",
"from sentry.interfaces.stacktrace import trim_function_name func = trim_function_name(func, frame.get('platform') or platform)",
"exception mechanism indicates a synthetic exception we do not #",
"import six from sentry.utils.safe import get_path, trim from sentry.utils.strings import",
"rv['type'] = trim(get_path(exception, 'type', default='Error'), 128) # Attach crash location",
"get_path, trim from sentry.utils.strings import truncatechars from .base import BaseEvent",
"data.get('platform')) rv = { 'value': trim(get_path(exception, 'value', default=''), 1024), }",
"# want to record the type and value into the",
"import truncatechars from .base import BaseEvent def get_crash_location(exception, platform=None): default",
"return u'{}: {}'.format( ty, truncatechars(metadata['value'].splitlines()[0], 100), ) def get_location(self, metadata):",
"default=''), 1024), } # If the exception mechanism indicates a",
"data): exception = get_path(data, 'exception', 'values', -1) return exception and",
"rv = { 'value': trim(get_path(exception, 'value', default=''), 1024), } #",
"metadata.get('type') if ty is None: return metadata.get('function') or '<unknown>' if",
"trim(get_path(exception, 'value', default=''), 1024), } # If the exception mechanism",
"frame.get('in_app'): return fn, func if default is None: default =",
"fn: rv['filename'] = fn if func: rv['function'] = func return",
"or ()): fn = frame.get('filename') or frame.get('abs_path') if fn: func",
"trim(get_path(exception, 'type', default='Error'), 128) # Attach crash location if available",
"default class ErrorEvent(BaseEvent): key = 'error' def has_metadata(self, data): exception",
"six.itervalues(exception)) def get_metadata(self, data): exception = get_path(data, 'exception', 'values', -1)",
"and any(v is not None for v in six.itervalues(exception)) def",
"exception = get_path(data, 'exception', 'values', -1) return exception and any(v",
"exception: return {} loc = get_crash_location(exception, data.get('platform')) rv = {",
"rv['filename'] = fn if func: rv['function'] = func return rv",
"= fn if func: rv['function'] = func return rv def",
"get_path(data, 'exception', 'values', -1) return exception and any(v is not",
"default='Error'), 128) # Attach crash location if available if loc",
"ty is None: return metadata.get('function') or '<unknown>' if not metadata.get('value'):",
"'exception', 'values', -1) return exception and any(v is not None",
"a synthetic exception we do not # want to record",
"default is None: default = fn, func return default class",
"if frame.get('in_app'): return fn, func if default is None: default",
"ErrorEvent(BaseEvent): key = 'error' def has_metadata(self, data): exception = get_path(data,",
"get_path(exception, 'mechanism', 'synthetic'): rv['type'] = trim(get_path(exception, 'type', default='Error'), 128) #",
"-1) if not exception: return {} loc = get_crash_location(exception, data.get('platform'))",
"= fn, func return default class ErrorEvent(BaseEvent): key = 'error'",
"= metadata.get('type') if ty is None: return metadata.get('function') or '<unknown>'",
"-1) return exception and any(v is not None for v",
"func is not None: from sentry.interfaces.stacktrace import trim_function_name func =",
"trim_function_name func = trim_function_name(func, frame.get('platform') or platform) if frame.get('in_app'): return",
"not get_path(exception, 'mechanism', 'synthetic'): rv['type'] = trim(get_path(exception, 'type', default='Error'), 128)",
"sentry.interfaces.stacktrace import trim_function_name func = trim_function_name(func, frame.get('platform') or platform) if",
"ty = metadata.get('type') if ty is None: return metadata.get('function') or",
"return fn, func if default is None: default = fn,",
"metadata.get('value'): return ty return u'{}: {}'.format( ty, truncatechars(metadata['value'].splitlines()[0], 100), )",
"has_metadata(self, data): exception = get_path(data, 'exception', 'values', -1) return exception",
"None for frame in reversed(get_path(exception, 'stacktrace', 'frames', filter=True) or ()):",
"func = frame.get('function') if func is not None: from sentry.interfaces.stacktrace",
"get_crash_location(exception, data.get('platform')) rv = { 'value': trim(get_path(exception, 'value', default=''), 1024),",
"get_title(self, metadata): ty = metadata.get('type') if ty is None: return",
"if not metadata.get('value'): return ty return u'{}: {}'.format( ty, truncatechars(metadata['value'].splitlines()[0],",
"'type', default='Error'), 128) # Attach crash location if available if",
"into the metadata. if not get_path(exception, 'mechanism', 'synthetic'): rv['type'] =",
"from sentry.utils.strings import truncatechars from .base import BaseEvent def get_crash_location(exception,",
"is None: default = fn, func return default class ErrorEvent(BaseEvent):",
"= frame.get('function') if func is not None: from sentry.interfaces.stacktrace import",
"platform) if frame.get('in_app'): return fn, func if default is None:",
"'mechanism', 'synthetic'): rv['type'] = trim(get_path(exception, 'type', default='Error'), 128) # Attach",
"get_path(data, 'exception', 'values', -1) if not exception: return {} loc",
"if not get_path(exception, 'mechanism', 'synthetic'): rv['type'] = trim(get_path(exception, 'type', default='Error'),",
"func return default class ErrorEvent(BaseEvent): key = 'error' def has_metadata(self,",
"def get_title(self, metadata): ty = metadata.get('type') if ty is None:",
"{} loc = get_crash_location(exception, data.get('platform')) rv = { 'value': trim(get_path(exception,",
"for v in six.itervalues(exception)) def get_metadata(self, data): exception = get_path(data,",
"metadata): ty = metadata.get('type') if ty is None: return metadata.get('function')",
"import BaseEvent def get_crash_location(exception, platform=None): default = None for frame",
"None for v in six.itervalues(exception)) def get_metadata(self, data): exception =",
"'frames', filter=True) or ()): fn = frame.get('filename') or frame.get('abs_path') if",
"= get_crash_location(exception, data.get('platform')) rv = { 'value': trim(get_path(exception, 'value', default=''),",
"is None: return metadata.get('function') or '<unknown>' if not metadata.get('value'): return",
"if func: rv['function'] = func return rv def get_title(self, metadata):",
"key = 'error' def has_metadata(self, data): exception = get_path(data, 'exception',",
"'value': trim(get_path(exception, 'value', default=''), 1024), } # If the exception",
"128) # Attach crash location if available if loc is",
"func = trim_function_name(func, frame.get('platform') or platform) if frame.get('in_app'): return fn,",
"()): fn = frame.get('filename') or frame.get('abs_path') if fn: func =",
"want to record the type and value into the metadata."
] |
[
"datetime import date from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import detect_date class DetectDate(TestCase): def",
"res = detect_date(dates_to_test[0]) self.assertEqual(10, res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[1])",
"import detect_date class DetectDate(TestCase): def test_detect_date(self): dates_to_test = ['10-1990', '09/12/2020',",
"TestCase from datetime import date from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import detect_date class",
"res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[1]) self.assertEqual(9, res.month) self.assertEqual(2020, res.year)",
"'09/12/2020', 'jan 1990', 'feb 2012', '9-12-2020'] res = detect_date(dates_to_test[0]) self.assertEqual(10,",
"res = detect_date(dates_to_test[1]) self.assertEqual(9, res.month) self.assertEqual(2020, res.year) res = detect_date(dates_to_test[2])",
"def test_detect_date(self): dates_to_test = ['10-1990', '09/12/2020', 'jan 1990', 'feb 2012',",
"res.year) res = detect_date(dates_to_test[3]) self.assertEqual(2, res.month) self.assertEqual(2012, res.year) res =",
"= detect_date(dates_to_test[3]) self.assertEqual(2, res.month) self.assertEqual(2012, res.year) res = detect_date(dates_to_test[4]) self.assertEqual(9,",
"'jan 1990', 'feb 2012', '9-12-2020'] res = detect_date(dates_to_test[0]) self.assertEqual(10, res.month)",
"from datetime import date from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import detect_date class DetectDate(TestCase):",
"= detect_date(dates_to_test[1]) self.assertEqual(9, res.month) self.assertEqual(2020, res.year) res = detect_date(dates_to_test[2]) self.assertEqual(1,",
"self.assertEqual(1990, res.year) res = detect_date(dates_to_test[3]) self.assertEqual(2, res.month) self.assertEqual(2012, res.year) res",
"= ['10-1990', '09/12/2020', 'jan 1990', 'feb 2012', '9-12-2020'] res =",
"'feb 2012', '9-12-2020'] res = detect_date(dates_to_test[0]) self.assertEqual(10, res.month) self.assertEqual(1990, res.year)",
"detect_date(dates_to_test[2]) self.assertEqual(1, res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[3]) self.assertEqual(2, res.month)",
"detect_date(dates_to_test[3]) self.assertEqual(2, res.month) self.assertEqual(2012, res.year) res = detect_date(dates_to_test[4]) self.assertEqual(9, res.month)",
"res = detect_date(dates_to_test[2]) self.assertEqual(1, res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[3])",
"keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import detect_date class DetectDate(TestCase): def test_detect_date(self): dates_to_test = ['10-1990',",
"import TestCase from datetime import date from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import detect_date",
"1990', 'feb 2012', '9-12-2020'] res = detect_date(dates_to_test[0]) self.assertEqual(10, res.month) self.assertEqual(1990,",
"detect_date(dates_to_test[1]) self.assertEqual(9, res.month) self.assertEqual(2020, res.year) res = detect_date(dates_to_test[2]) self.assertEqual(1, res.month)",
"date from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import detect_date class DetectDate(TestCase): def test_detect_date(self): dates_to_test",
"from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import detect_date class DetectDate(TestCase): def test_detect_date(self): dates_to_test =",
"class DetectDate(TestCase): def test_detect_date(self): dates_to_test = ['10-1990', '09/12/2020', 'jan 1990',",
"2012', '9-12-2020'] res = detect_date(dates_to_test[0]) self.assertEqual(10, res.month) self.assertEqual(1990, res.year) res",
"res.year) res = detect_date(dates_to_test[2]) self.assertEqual(1, res.month) self.assertEqual(1990, res.year) res =",
"detect_date(dates_to_test[0]) self.assertEqual(10, res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[1]) self.assertEqual(9, res.month)",
"'9-12-2020'] res = detect_date(dates_to_test[0]) self.assertEqual(10, res.month) self.assertEqual(1990, res.year) res =",
"from unittest import TestCase from datetime import date from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify",
"res.year) res = detect_date(dates_to_test[1]) self.assertEqual(9, res.month) self.assertEqual(2020, res.year) res =",
"res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[3]) self.assertEqual(2, res.month) self.assertEqual(2012, res.year)",
"res = detect_date(dates_to_test[3]) self.assertEqual(2, res.month) self.assertEqual(2012, res.year) res = detect_date(dates_to_test[4])",
"unittest import TestCase from datetime import date from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import",
"self.assertEqual(2020, res.year) res = detect_date(dates_to_test[2]) self.assertEqual(1, res.month) self.assertEqual(1990, res.year) res",
"detect_date class DetectDate(TestCase): def test_detect_date(self): dates_to_test = ['10-1990', '09/12/2020', 'jan",
"test_detect_date(self): dates_to_test = ['10-1990', '09/12/2020', 'jan 1990', 'feb 2012', '9-12-2020']",
"res.month) self.assertEqual(2020, res.year) res = detect_date(dates_to_test[2]) self.assertEqual(1, res.month) self.assertEqual(1990, res.year)",
"DetectDate(TestCase): def test_detect_date(self): dates_to_test = ['10-1990', '09/12/2020', 'jan 1990', 'feb",
"self.assertEqual(1, res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[3]) self.assertEqual(2, res.month) self.assertEqual(2012,",
"self.assertEqual(2, res.month) self.assertEqual(2012, res.year) res = detect_date(dates_to_test[4]) self.assertEqual(9, res.month) self.assertEqual(2020,",
"res.month) self.assertEqual(2012, res.year) res = detect_date(dates_to_test[4]) self.assertEqual(9, res.month) self.assertEqual(2020, res.year)",
"= detect_date(dates_to_test[2]) self.assertEqual(1, res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[3]) self.assertEqual(2,",
"dates_to_test = ['10-1990', '09/12/2020', 'jan 1990', 'feb 2012', '9-12-2020'] res",
"self.assertEqual(10, res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[1]) self.assertEqual(9, res.month) self.assertEqual(2020,",
"= detect_date(dates_to_test[0]) self.assertEqual(10, res.month) self.assertEqual(1990, res.year) res = detect_date(dates_to_test[1]) self.assertEqual(9,",
"self.assertEqual(9, res.month) self.assertEqual(2020, res.year) res = detect_date(dates_to_test[2]) self.assertEqual(1, res.month) self.assertEqual(1990,",
"self.assertEqual(1990, res.year) res = detect_date(dates_to_test[1]) self.assertEqual(9, res.month) self.assertEqual(2020, res.year) res",
"import date from keras_en_parser_and_analyzer.library.pipmp_my_cv_classify import detect_date class DetectDate(TestCase): def test_detect_date(self):",
"['10-1990', '09/12/2020', 'jan 1990', 'feb 2012', '9-12-2020'] res = detect_date(dates_to_test[0])"
] |
[
"Three cases are possible here, and they map directly to",
"inside this # __str__, replace with explicit method def __str__(self):",
"_PLATFORM = 'ipset' _SET_MAX_LENGTH = 31 _POSTJUMP_FORMAT = None _PREJUMP_FORMAT",
"2.0 (the \"License\"); # you may not use this file",
"# { 'src': ('set_name', [ipaddr object, ipaddr object]), # 'dst':",
"with destination address of the rule. Returns: tuple containing source",
"case is when there are more than one address in",
"%i' % (c_str, set_name, self._SET_TYPE, term.af, set_hashsize, set_maxelem)) for address",
"[ipaddr object, ipaddr object]) } self.addr_sets = {} def _CalculateAddresses(self,",
"source and destination address list for a term. Since ipset",
"addr_list = [self._all_ips] addr_list = [addr for addr in addr_list",
"for term in terms: output.extend(self._GenerateSetConfig(term)) output.append(self._MARKER_END) output.append(iptables_output) return '\\n'.join(output) def",
"single address match (-s or -d). Third case, is when",
"in addr_list if addr.version == target_af] if addr_exclude_list: addr_exclude_list =",
"address or network object with source address of the rule.",
"return '%s-%s' % (term_name, suffix) class Ipset(iptables.Iptables): \"\"\"Ipset generator.\"\"\" _PLATFORM",
"ipaddr object]) } self.addr_sets = {} def _CalculateAddresses(self, src_addr_list, src_addr_exclude_list,",
"# limitations under the License. # \"\"\"Ipset iptables generator. This",
"= Term _MARKER_BEGIN = '# begin:ipset-rules' _MARKER_END = '# end:ipset-rules'",
"set_hashsize output.append('%s %s %s family %s hashsize %i maxelem %i'",
"comment --comment \"$comment\"') _FILTER_TOP_FORMAT = string.Template('-A $filter') def __init__(self, *args,",
"**kwargs) # This stores tuples of set name and set",
"term_name, suffix): if self.af == 'inet6': suffix += '-v6' if",
"possible. First case is when there are no addresses. In",
"target_af, 'src') dst_addr_list = self._CalculateAddrList(dst_addr_list, dst_addr_exclude_list, target_af, 'dst') return (src_addr_list,",
"at matching large number of addresses, we never return any",
"- len(suffix) - 1 term_name = term_name[:set_name_max_lenth] return '%s-%s' %",
"= '# begin:ipset-rules' _MARKER_END = '# end:ipset-rules' _GOOD_OPTIONS = ['nostate',",
"list, source address exclude list, destination address list, destination address",
"we return single address match (-s or -d). Third case,",
"are possible here, and they map directly to cases in",
"src_addr.prefixlen) if dst_addr == self._all_ips: if 'dst' in self.addr_sets: dst_addr_stmt",
"return empty string. Second there can be stricly one address.",
"stores tuples of set name and set contents, keyed by",
"address match (-s or -d). Third case, is when the",
"_SET_TYPE = 'hash:net' SUFFIX = '.ips' _TERM = Term _MARKER_BEGIN",
"'-A $filter -m comment --comment \"$comment\"') _FILTER_TOP_FORMAT = string.Template('-A $filter')",
"we return _all_ips. Second case is when there is strictly",
"src_addr_exclude_list: source address exclude list of the term. dst_addr_list: destination",
"and they map directly to cases in _CalculateAddresses. First, there",
"match. Args: src_addr: ipaddr address or network object with source",
"'' if src_addr and dst_addr: if src_addr == self._all_ips: if",
"%s hashsize %i maxelem %i' % (c_str, set_name, self._SET_TYPE, term.af,",
"be used to dramatically increase performace of iptables firewall. \"\"\"",
"performace of iptables firewall. \"\"\" import string from capirca.lib import",
"representation.\"\"\" _PLATFORM = 'ipset' _SET_MAX_LENGTH = 31 _POSTJUMP_FORMAT = None",
"method def __str__(self): # Actual rendering happens in __str__, so",
"'inet6': suffix += '-v6' if len(term_name) + len(suffix) + 1",
"tuples of set name and set contents, keyed by direction.",
"= 31 _POSTJUMP_FORMAT = None _PREJUMP_FORMAT = None _TERM_FORMAT =",
"addr_exclude_list = [addr_exclude for addr_exclude in addr_exclude_list if addr_exclude.version ==",
"-exist' for direction in sorted(term.addr_sets, reverse=True): set_name, addr_list = term.addr_sets[direction]",
"src_addr_list = self._CalculateAddrList(src_addr_list, src_addr_exclude_list, target_af, 'src') dst_addr_list = self._CalculateAddrList(dst_addr_list, dst_addr_exclude_list,",
"tuple containing source address list, source address exclude list, destination",
"use this file except in compliance with the License. #",
"generate a set and also return _all_ips. Note the difference",
"set. Third case is when there are more than one",
"src_addr_exclude_list, target_af, 'src') dst_addr_list = self._CalculateAddrList(dst_addr_list, dst_addr_exclude_list, target_af, 'dst') return",
"_CalculateAddresses documentation. Three cases are possible here, and they map",
"address list, destination address exclude list in that order. \"\"\"",
"with explicit method def __str__(self): # Actual rendering happens in",
"capirca.lib import nacaddr class Error(Exception): \"\"\"Base error class.\"\"\" class Term(iptables.Term):",
"the difference to the first case where no set is",
"address exclude list of the term. target_af: target address family.",
"addr_list = term.addr_sets[direction] set_hashsize = 1 << len(addr_list).bit_length() set_maxelem =",
"_all_ips but also the set for particular direction is present.",
"address section of an individual iptables rule. See _CalculateAddresses documentation.",
"License. # You may obtain a copy of the License",
"happening inside this # __str__, replace with explicit method def",
"subclass of Iptables generator. ipset is a system inside the",
"source and destination address list, three cases are possible. First",
"_CalculateAddresses(self, src_addr_list, src_addr_exclude_list, dst_addr_list, dst_addr_exclude_list): \"\"\"Calculates source and destination address",
"def _GenerateAddressStatement(self, src_addr, dst_addr): \"\"\"Returns the address section of an",
"governing permissions and # limitations under the License. # \"\"\"Ipset",
"contents, keyed by direction. # For example: # { 'src':",
"under the License is distributed on an \"AS IS\" BASIS,",
"ipaddr object]), # 'dst': ('set_name', [ipaddr object, ipaddr object]) }",
"of the term. dst_addr_list: destination address list of the term.",
"number of addresses, we never return any exclude addresses. Instead",
"License for the specific language governing permissions and # limitations",
"never return any exclude addresses. Instead least positive match is",
"there are no addresses. In that case we return _all_ips.",
"else: dst_addr_stmt = '-d %s/%d' % (dst_addr.network_address, dst_addr.prefixlen) return (src_addr_stmt,",
"_all_ips. Second case is when there is strictly one address.",
"% self.addr_sets['dst'][0]) else: dst_addr_stmt = '-d %s/%d' % (dst_addr.network_address, dst_addr.prefixlen)",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"for target AF and direction. Args: addr_list: address list. addr_exclude_list:",
"and destination address statement, in that order. \"\"\" src_addr_stmt =",
"kernel, which can very efficiently store and match IPv4 and",
"if dst_addr == self._all_ips: if 'dst' in self.addr_sets: dst_addr_stmt =",
"target_af] addr_list = nacaddr.ExcludeAddrs(addr_list, addr_exclude_list) if len(addr_list) > 1: set_name",
"a_str + ' -exist' for direction in sorted(term.addr_sets, reverse=True): set_name,",
"the Linux kernel, which can very efficiently store and match",
"src_addr_stmt = '-s %s/%d' % (src_addr.network_address, src_addr.prefixlen) if dst_addr ==",
"terms) in self.iptables_policies: for term in terms: output.extend(self._GenerateSetConfig(term)) output.append(self._MARKER_END) output.append(iptables_output)",
"a set, and it's then the only element of returned",
"dst_addr: if src_addr == self._all_ips: if 'src' in self.addr_sets: src_addr_stmt",
"exclude list of the term. Returns: tuple containing source address",
"input term. Returns: string that is configuration of supplied term.",
"section of an individual iptables rule. See _CalculateAddresses documentation. Three",
"# unless required by applicable law or agreed to in",
"None _TERM_FORMAT = None _COMMENT_FORMAT = string.Template( '-A $filter -m",
"First, there can be no addresses for a direction (value",
"generating a set, and it's then the only element of",
"src' % self.addr_sets['src'][0]) else: src_addr_stmt = '-s %s/%d' % (src_addr.network_address,",
"= self._SET_MAX_LENGTH - len(suffix) - 1 term_name = term_name[:set_name_max_lenth] return",
"in compliance with the License. # You may obtain a",
"set_hashsize, set_maxelem)) for address in addr_list: output.append('%s %s %s' %",
"list, destination address list, destination address exclude list in that",
"no set is actually generated. Args: src_addr_list: source address list",
"software # distributed under the License is distributed on an",
"source address exclude list of the term. dst_addr_list: destination address",
"'-v6' if len(term_name) + len(suffix) + 1 > self._SET_MAX_LENGTH: set_name_max_lenth",
"TODO(vklimovs): some not trivial processing is happening inside this #",
"maxelem %i' % (c_str, set_name, self._SET_TYPE, term.af, set_hashsize, set_maxelem)) for",
"\"\"\"Ipset iptables generator. This is a subclass of Iptables generator.",
"addr_list: address list. addr_exclude_list: address exclude list of the term.",
"the value is _all_ips but also the set for particular",
"can be used to dramatically increase performace of iptables firewall.",
"self._SET_MAX_LENGTH - len(suffix) - 1 term_name = term_name[:set_name_max_lenth] return '%s-%s'",
"('set_name', [ipaddr object, ipaddr object]) } self.addr_sets = {} def",
"> 1: set_name = self._GenerateSetName(self.term.name, direction) self.addr_sets[direction] = (set_name, addr_list)",
"<< len(addr_list).bit_length() set_maxelem = set_hashsize output.append('%s %s %s family %s",
"set_maxelem = set_hashsize output.append('%s %s %s family %s hashsize %i",
"self._CalculateAddrList(dst_addr_list, dst_addr_exclude_list, target_af, 'dst') return (src_addr_list, [], dst_addr_list, []) def",
"Term _MARKER_BEGIN = '# begin:ipset-rules' _MARKER_END = '# end:ipset-rules' _GOOD_OPTIONS",
"direction in which address list will be used. Returns: calculated",
"1 term_name = term_name[:set_name_max_lenth] return '%s-%s' % (term_name, suffix) class",
"suffix) class Ipset(iptables.Iptables): \"\"\"Ipset generator.\"\"\" _PLATFORM = 'ipset' _SET_TYPE =",
"\"$comment\"') _FILTER_TOP_FORMAT = string.Template('-A $filter') def __init__(self, *args, **kwargs): super().__init__(*args,",
"[addr_exclude for addr_exclude in addr_exclude_list if addr_exclude.version == target_af] addr_list",
"set for particular direction is present. That's when we return",
"do set specific part. iptables_output = super().__str__() output = []",
"return single address match (-s or -d). Third case, is",
"' -exist' a_str = a_str + ' -exist' for direction",
"class Term(iptables.Term): \"\"\"Single Ipset term representation.\"\"\" _PLATFORM = 'ipset' _SET_MAX_LENGTH",
"self.filter_options: c_str = c_str + ' -exist' a_str = a_str",
"of iptables firewall. \"\"\" import string from capirca.lib import iptables",
"we return empty string. Second there can be stricly one",
"are more than one address in a set. In that",
"+ ' -exist' a_str = a_str + ' -exist' for",
"'abbreviateterms', 'truncateterms', 'noverbose', 'exists'] # TODO(vklimovs): some not trivial processing",
"dst_addr): \"\"\"Returns the address section of an individual iptables rule.",
"addresses. In that case we return _all_ips. Second case is",
"(src_addr_stmt, dst_addr_stmt) def _GenerateSetName(self, term_name, suffix): if self.af == 'inet6':",
"set --match-set %s dst' % self.addr_sets['dst'][0]) else: dst_addr_stmt = '-d",
"self.addr_sets: dst_addr_stmt = ('-m set --match-set %s dst' % self.addr_sets['dst'][0])",
"containing source address list, source address exclude list, destination address",
"This can be used to dramatically increase performace of iptables",
"'-s %s/%d' % (src_addr.network_address, src_addr.prefixlen) if dst_addr == self._all_ips: if",
"list of the term. dst_addr_exclude_list: destination address exclude list of",
"% self.addr_sets['src'][0]) else: src_addr_stmt = '-s %s/%d' % (src_addr.network_address, src_addr.prefixlen)",
"addr_list: output.append('%s %s %s' % (a_str, set_name, address)) return output",
"{ 'src': ('set_name', [ipaddr object, ipaddr object]), # 'dst': ('set_name',",
"happens in __str__, so it has to be called #",
"firewall. \"\"\" import string from capirca.lib import iptables from capirca.lib",
"term in terms: output.extend(self._GenerateSetConfig(term)) output.append(self._MARKER_END) output.append(iptables_output) return '\\n'.join(output) def _GenerateSetConfig(self,",
"string from capirca.lib import iptables from capirca.lib import nacaddr class",
"match is calculated for both source and destination addresses. For",
"for direction in sorted(term.addr_sets, reverse=True): set_name, addr_list = term.addr_sets[direction] set_hashsize",
"def __str__(self): # Actual rendering happens in __str__, so it",
"dst_addr_stmt = '-d %s/%d' % (dst_addr.network_address, dst_addr.prefixlen) return (src_addr_stmt, dst_addr_stmt)",
"# before we do set specific part. iptables_output = super().__str__()",
"\"\"\" import string from capirca.lib import iptables from capirca.lib import",
"dst_addr_stmt = ('-m set --match-set %s dst' % self.addr_sets['dst'][0]) else:",
"set_name, addr_list = term.addr_sets[direction] set_hashsize = 1 << len(addr_list).bit_length() set_maxelem",
"{} def _CalculateAddresses(self, src_addr_list, src_addr_exclude_list, dst_addr_list, dst_addr_exclude_list): \"\"\"Calculates source and",
"direction: direction in which address list will be used. Returns:",
"iptables firewall. \"\"\" import string from capirca.lib import iptables from",
"Returns: calculated address list. \"\"\" if not addr_list: addr_list =",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"# For example: # { 'src': ('set_name', [ipaddr object, ipaddr",
"address family. direction: direction in which address list will be",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"of Iptables generator. ipset is a system inside the Linux",
"address statement, in that order. \"\"\" src_addr_stmt = '' dst_addr_stmt",
"term): \"\"\"Generates set configuration for supplied term. Args: term: input",
"address list, source address exclude list, destination address list, destination",
"self.addr_sets[direction] = (set_name, addr_list) addr_list = [self._all_ips] return addr_list def",
"%s dst' % self.addr_sets['dst'][0]) else: dst_addr_stmt = '-d %s/%d' %",
"the License. # You may obtain a copy of the",
"for the specific language governing permissions and # limitations under",
"for a term. Since ipset is very efficient at matching",
"_TERM = Term _MARKER_BEGIN = '# begin:ipset-rules' _MARKER_END = '#",
"not trivial processing is happening inside this # __str__, replace",
"output.append(iptables_output) return '\\n'.join(output) def _GenerateSetConfig(self, term): \"\"\"Generates set configuration for",
"to in writing, software # distributed under the License is",
"# See the License for the specific language governing permissions",
"returned set. Third case is when there are more than",
"$filter') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This stores",
"31 _POSTJUMP_FORMAT = None _PREJUMP_FORMAT = None _TERM_FORMAT = None",
"if self.af == 'inet6': suffix += '-v6' if len(term_name) +",
"'add' if 'exists' in self.filter_options: c_str = c_str + '",
"language governing permissions and # limitations under the License. #",
"= {} def _CalculateAddresses(self, src_addr_list, src_addr_exclude_list, dst_addr_list, dst_addr_exclude_list): \"\"\"Calculates source",
"or agreed to in writing, software # distributed under the",
"some not trivial processing is happening inside this # __str__,",
"required by applicable law or agreed to in writing, software",
"set. In that case we generate a set and also",
"address list of the term. src_addr_exclude_list: source address exclude list",
"direction. Args: addr_list: address list. addr_exclude_list: address exclude list of",
"+ 1 > self._SET_MAX_LENGTH: set_name_max_lenth = self._SET_MAX_LENGTH - len(suffix) -",
"list will be used. Returns: calculated address list. \"\"\" if",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"first case where no set is actually generated. Args: src_addr_list:",
"string that is configuration of supplied term. \"\"\" output =",
"ipaddr address or network object with destination address of the",
"with the License. # You may obtain a copy of",
"output = [] output.append(self._MARKER_BEGIN) for (_, _, _, _, terms)",
"both source and destination addresses. For source and destination address",
"trivial processing is happening inside this # __str__, replace with",
"if addr.version == target_af] if addr_exclude_list: addr_exclude_list = [addr_exclude for",
"\"\"\"Generates set configuration for supplied term. Args: term: input term.",
"we optimize by not generating a set, and it's then",
"addr_exclude.version == target_af] addr_list = nacaddr.ExcludeAddrs(addr_list, addr_exclude_list) if len(addr_list) >",
"exclude list of the term. target_af: target address family. direction:",
"no addresses for a direction (value is _all_ips then) In",
"cases are possible here, and they map directly to cases",
"_GenerateSetName(self, term_name, suffix): if self.af == 'inet6': suffix += '-v6'",
"before we do set specific part. iptables_output = super().__str__() output",
"dst_addr_list, []) def _CalculateAddrList(self, addr_list, addr_exclude_list, target_af, direction): \"\"\"Calculates and",
"is calculated for both source and destination addresses. For source",
"src_addr_list, src_addr_exclude_list, dst_addr_list, dst_addr_exclude_list): \"\"\"Calculates source and destination address list",
"object, ipaddr object]) } self.addr_sets = {} def _CalculateAddresses(self, src_addr_list,",
"list of the term. target_af: target address family. direction: direction",
"'exists' in self.filter_options: c_str = c_str + ' -exist' a_str",
"more than one address in a set. In that case",
"is _all_ips but also the set for particular direction is",
"ipaddr address or network object with source address of the",
"in self.iptables_policies: for term in terms: output.extend(self._GenerateSetConfig(term)) output.append(self._MARKER_END) output.append(iptables_output) return",
"compliance with the License. # You may obtain a copy",
"addr_exclude_list: address exclude list of the term. target_af: target address",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"we return a set match. Args: src_addr: ipaddr address or",
"the term. dst_addr_exclude_list: destination address exclude list of the term.",
"dst_addr_exclude_list, target_af, 'dst') return (src_addr_list, [], dst_addr_list, []) def _CalculateAddrList(self,",
"Actual rendering happens in __str__, so it has to be",
"term. dst_addr_exclude_list: destination address exclude list of the term. Returns:",
"specific part. iptables_output = super().__str__() output = [] output.append(self._MARKER_BEGIN) for",
"set_hashsize = 1 << len(addr_list).bit_length() set_maxelem = set_hashsize output.append('%s %s",
"__str__(self): # Actual rendering happens in __str__, so it has",
"License. # \"\"\"Ipset iptables generator. This is a subclass of",
"case is when there is strictly one address. In that",
"distributed under the License is distributed on an \"AS IS\"",
"Inc. All Rights Reserved. # # Licensed under the Apache",
"large number of addresses, we never return any exclude addresses.",
"src_addr_stmt = '' dst_addr_stmt = '' if src_addr and dst_addr:",
"of addresses, we never return any exclude addresses. Instead least",
"src_addr, dst_addr): \"\"\"Returns the address section of an individual iptables",
"set_name, self._SET_TYPE, term.af, set_hashsize, set_maxelem)) for address in addr_list: output.append('%s",
"of supplied term. \"\"\" output = [] c_str = 'create'",
"Error(Exception): \"\"\"Base error class.\"\"\" class Term(iptables.Term): \"\"\"Single Ipset term representation.\"\"\"",
"+= '-v6' if len(term_name) + len(suffix) + 1 > self._SET_MAX_LENGTH:",
"AF and direction. Args: addr_list: address list. addr_exclude_list: address exclude",
"dramatically increase performace of iptables firewall. \"\"\" import string from",
"and also return _all_ips. Note the difference to the first",
"express or implied. # See the License for the specific",
"self._SET_MAX_LENGTH: set_name_max_lenth = self._SET_MAX_LENGTH - len(suffix) - 1 term_name =",
"address list of the term. dst_addr_exclude_list: destination address exclude list",
"except in compliance with the License. # You may obtain",
"suffix): if self.af == 'inet6': suffix += '-v6' if len(term_name)",
"= [addr_exclude for addr_exclude in addr_exclude_list if addr_exclude.version == target_af]",
"= string.Template('-A $filter') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #",
"of the rule. dst_addr: ipaddr address or network object with",
"super().__str__() output = [] output.append(self._MARKER_BEGIN) for (_, _, _, _,",
"set_name_max_lenth = self._SET_MAX_LENGTH - len(suffix) - 1 term_name = term_name[:set_name_max_lenth]",
"Returns: string that is configuration of supplied term. \"\"\" output",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"and set contents, keyed by direction. # For example: #",
"to cases in _CalculateAddresses. First, there can be no addresses",
"term: input term. Returns: string that is configuration of supplied",
"is configuration of supplied term. \"\"\" output = [] c_str",
"not use this file except in compliance with the License.",
"and # limitations under the License. # \"\"\"Ipset iptables generator.",
"Returns: tuple containing source and destination address statement, in that",
"that case we return single address match (-s or -d).",
"= [self._all_ips] addr_list = [addr for addr in addr_list if",
"addr_exclude in addr_exclude_list if addr_exclude.version == target_af] addr_list = nacaddr.ExcludeAddrs(addr_list,",
"for particular direction is present. That's when we return a",
"calculated address list. \"\"\" if not addr_list: addr_list = [self._all_ips]",
"Returns: tuple containing source address list, source address exclude list,",
"source address of the rule. dst_addr: ipaddr address or network",
"_, terms) in self.iptables_policies: for term in terms: output.extend(self._GenerateSetConfig(term)) output.append(self._MARKER_END)",
"writing, software # distributed under the License is distributed on",
"of the term. dst_addr_exclude_list: destination address exclude list of the",
"dst_addr_stmt = '' if src_addr and dst_addr: if src_addr ==",
"you may not use this file except in compliance with",
"len(addr_list).bit_length() set_maxelem = set_hashsize output.append('%s %s %s family %s hashsize",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"2015 Google Inc. All Rights Reserved. # # Licensed under",
"then) In that case we return empty string. Second there",
"> self._SET_MAX_LENGTH: set_name_max_lenth = self._SET_MAX_LENGTH - len(suffix) - 1 term_name",
"by direction. # For example: # { 'src': ('set_name', [ipaddr",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # unless required by",
"list for a term. Since ipset is very efficient at",
"First case is when there are no addresses. In that",
"[]) def _CalculateAddrList(self, addr_list, addr_exclude_list, target_af, direction): \"\"\"Calculates and stores",
"(set_name, addr_list) addr_list = [self._all_ips] return addr_list def _GenerateAddressStatement(self, src_addr,",
"= ['nostate', 'abbreviateterms', 'truncateterms', 'noverbose', 'exists'] # TODO(vklimovs): some not",
"= set_hashsize output.append('%s %s %s family %s hashsize %i maxelem",
"is a system inside the Linux kernel, which can very",
"def _CalculateAddrList(self, addr_list, addr_exclude_list, target_af, direction): \"\"\"Calculates and stores address",
"'# end:ipset-rules' _GOOD_OPTIONS = ['nostate', 'abbreviateterms', 'truncateterms', 'noverbose', 'exists'] #",
"stricly one address. In that case we return single address",
"(term_name, suffix) class Ipset(iptables.Iptables): \"\"\"Ipset generator.\"\"\" _PLATFORM = 'ipset' _SET_TYPE",
"' -exist' for direction in sorted(term.addr_sets, reverse=True): set_name, addr_list =",
"the first case where no set is actually generated. Args:",
"['nostate', 'abbreviateterms', 'truncateterms', 'noverbose', 'exists'] # TODO(vklimovs): some not trivial",
"that is configuration of supplied term. \"\"\" output = []",
"they map directly to cases in _CalculateAddresses. First, there can",
"from capirca.lib import iptables from capirca.lib import nacaddr class Error(Exception):",
"_all_ips then) In that case we return empty string. Second",
"= super().__str__() output = [] output.append(self._MARKER_BEGIN) for (_, _, _,",
"= ('-m set --match-set %s dst' % self.addr_sets['dst'][0]) else: dst_addr_stmt",
"target_af, direction): \"\"\"Calculates and stores address list for target AF",
"address exclude list of the term. dst_addr_list: destination address list",
"unless required by applicable law or agreed to in writing,",
"addr_exclude_list if addr_exclude.version == target_af] addr_list = nacaddr.ExcludeAddrs(addr_list, addr_exclude_list) if",
"%s family %s hashsize %i maxelem %i' % (c_str, set_name,",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"family. direction: direction in which address list will be used.",
"be called # before we do set specific part. iptables_output",
"= [addr for addr in addr_list if addr.version == target_af]",
"is when there is strictly one address. In that case,",
"addr_exclude_list) if len(addr_list) > 1: set_name = self._GenerateSetName(self.term.name, direction) self.addr_sets[direction]",
"'src' in self.addr_sets: src_addr_stmt = ('-m set --match-set %s src'",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"self.addr_sets = {} def _CalculateAddresses(self, src_addr_list, src_addr_exclude_list, dst_addr_list, dst_addr_exclude_list): \"\"\"Calculates",
"or network object with destination address of the rule. Returns:",
"we do set specific part. iptables_output = super().__str__() output =",
"Second case is when there is strictly one address. In",
"'exists'] # TODO(vklimovs): some not trivial processing is happening inside",
"supplied term. \"\"\" output = [] c_str = 'create' a_str",
"if len(addr_list) > 1: set_name = self._GenerateSetName(self.term.name, direction) self.addr_sets[direction] =",
"that case we return empty string. Second there can be",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # unless required by applicable law",
"'truncateterms', 'noverbose', 'exists'] # TODO(vklimovs): some not trivial processing is",
"used. Returns: calculated address list. \"\"\" if not addr_list: addr_list",
"-d). Third case, is when the value is _all_ips but",
"the term. Returns: tuple containing source address list, source address",
"in __str__, so it has to be called # before",
"element of returned set. Third case is when there are",
"= a_str + ' -exist' for direction in sorted(term.addr_sets, reverse=True):",
"rule. Returns: tuple containing source and destination address statement, in",
"positive match is calculated for both source and destination addresses.",
"case where no set is actually generated. Args: src_addr_list: source",
"[self._all_ips] return addr_list def _GenerateAddressStatement(self, src_addr, dst_addr): \"\"\"Returns the address",
"'.ips' _TERM = Term _MARKER_BEGIN = '# begin:ipset-rules' _MARKER_END =",
"= None _TERM_FORMAT = None _COMMENT_FORMAT = string.Template( '-A $filter",
"\"\"\"Calculates source and destination address list for a term. Since",
"__str__, replace with explicit method def __str__(self): # Actual rendering",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"output.append(self._MARKER_END) output.append(iptables_output) return '\\n'.join(output) def _GenerateSetConfig(self, term): \"\"\"Generates set configuration",
"configuration of supplied term. \"\"\" output = [] c_str =",
"self.addr_sets['dst'][0]) else: dst_addr_stmt = '-d %s/%d' % (dst_addr.network_address, dst_addr.prefixlen) return",
"the License is distributed on an \"AS IS\" BASIS, #",
"= 1 << len(addr_list).bit_length() set_maxelem = set_hashsize output.append('%s %s %s",
"# TODO(vklimovs): some not trivial processing is happening inside this",
"'noverbose', 'exists'] # TODO(vklimovs): some not trivial processing is happening",
"== self._all_ips: if 'src' in self.addr_sets: src_addr_stmt = ('-m set",
"def _CalculateAddresses(self, src_addr_list, src_addr_exclude_list, dst_addr_list, dst_addr_exclude_list): \"\"\"Calculates source and destination",
"of set name and set contents, keyed by direction. #",
"when the value is _all_ips but also the set for",
"list in that order. \"\"\" target_af = self.AF_MAP[self.af] src_addr_list =",
"output.extend(self._GenerateSetConfig(term)) output.append(self._MARKER_END) output.append(iptables_output) return '\\n'.join(output) def _GenerateSetConfig(self, term): \"\"\"Generates set",
"\"\"\"Base error class.\"\"\" class Term(iptables.Term): \"\"\"Single Ipset term representation.\"\"\" _PLATFORM",
"_GenerateAddressStatement(self, src_addr, dst_addr): \"\"\"Returns the address section of an individual",
"network object with destination address of the rule. Returns: tuple",
"exclude list of the term. dst_addr_list: destination address list of",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # unless",
"address in a set. In that case we generate a",
"direction is present. That's when we return a set match.",
"In that case we generate a set and also return",
"_SET_MAX_LENGTH = 31 _POSTJUMP_FORMAT = None _PREJUMP_FORMAT = None _TERM_FORMAT",
"address or network object with destination address of the rule.",
"_PLATFORM = 'ipset' _SET_TYPE = 'hash:net' SUFFIX = '.ips' _TERM",
"This is a subclass of Iptables generator. ipset is a",
"documentation. Three cases are possible here, and they map directly",
"destination address exclude list of the term. Returns: tuple containing",
"def _GenerateSetConfig(self, term): \"\"\"Generates set configuration for supplied term. Args:",
"match IPv4 and IPv6 addresses. This can be used to",
"'dst': ('set_name', [ipaddr object, ipaddr object]) } self.addr_sets = {}",
"limitations under the License. # \"\"\"Ipset iptables generator. This is",
"law or agreed to in writing, software # distributed under",
"= 'hash:net' SUFFIX = '.ips' _TERM = Term _MARKER_BEGIN =",
"increase performace of iptables firewall. \"\"\" import string from capirca.lib",
"addresses. For source and destination address list, three cases are",
"(src_addr.network_address, src_addr.prefixlen) if dst_addr == self._all_ips: if 'dst' in self.addr_sets:",
"be no addresses for a direction (value is _all_ips then)",
"return any exclude addresses. Instead least positive match is calculated",
"are no addresses. In that case we return _all_ips. Second",
"rendering happens in __str__, so it has to be called",
"term. Since ipset is very efficient at matching large number",
"stores address list for target AF and direction. Args: addr_list:",
"generated. Args: src_addr_list: source address list of the term. src_addr_exclude_list:",
"== target_af] if addr_exclude_list: addr_exclude_list = [addr_exclude for addr_exclude in",
"if addr_exclude_list: addr_exclude_list = [addr_exclude for addr_exclude in addr_exclude_list if",
"dst_addr_exclude_list: destination address exclude list of the term. Returns: tuple",
"= '# end:ipset-rules' _GOOD_OPTIONS = ['nostate', 'abbreviateterms', 'truncateterms', 'noverbose', 'exists']",
"one address in a set. In that case we generate",
"_CalculateAddrList(self, addr_list, addr_exclude_list, target_af, direction): \"\"\"Calculates and stores address list",
"object with destination address of the rule. Returns: tuple containing",
"and destination address list for a term. Since ipset is",
"= self._CalculateAddrList(src_addr_list, src_addr_exclude_list, target_af, 'src') dst_addr_list = self._CalculateAddrList(dst_addr_list, dst_addr_exclude_list, target_af,",
"case, is when the value is _all_ips but also the",
"may obtain a copy of the License at # #",
"len(addr_list) > 1: set_name = self._GenerateSetName(self.term.name, direction) self.addr_sets[direction] = (set_name,",
"addr_list = nacaddr.ExcludeAddrs(addr_list, addr_exclude_list) if len(addr_list) > 1: set_name =",
"super().__init__(*args, **kwargs) # This stores tuples of set name and",
"= '' dst_addr_stmt = '' if src_addr and dst_addr: if",
"= 'ipset' _SET_MAX_LENGTH = 31 _POSTJUMP_FORMAT = None _PREJUMP_FORMAT =",
"address list for target AF and direction. Args: addr_list: address",
"which address list will be used. Returns: calculated address list.",
"set_maxelem)) for address in addr_list: output.append('%s %s %s' % (a_str,",
"addr_exclude_list: addr_exclude_list = [addr_exclude for addr_exclude in addr_exclude_list if addr_exclude.version",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"and match IPv4 and IPv6 addresses. This can be used",
"-m comment --comment \"$comment\"') _FILTER_TOP_FORMAT = string.Template('-A $filter') def __init__(self,",
"be stricly one address. In that case we return single",
"self.AF_MAP[self.af] src_addr_list = self._CalculateAddrList(src_addr_list, src_addr_exclude_list, target_af, 'src') dst_addr_list = self._CalculateAddrList(dst_addr_list,",
"also return _all_ips. Note the difference to the first case",
"if src_addr == self._all_ips: if 'src' in self.addr_sets: src_addr_stmt =",
"may not use this file except in compliance with the",
"end:ipset-rules' _GOOD_OPTIONS = ['nostate', 'abbreviateterms', 'truncateterms', 'noverbose', 'exists'] # TODO(vklimovs):",
"= self._CalculateAddrList(dst_addr_list, dst_addr_exclude_list, target_af, 'dst') return (src_addr_list, [], dst_addr_list, [])",
"in terms: output.extend(self._GenerateSetConfig(term)) output.append(self._MARKER_END) output.append(iptables_output) return '\\n'.join(output) def _GenerateSetConfig(self, term):",
"than one address in a set. In that case we",
"not addr_list: addr_list = [self._all_ips] addr_list = [addr for addr",
"None _PREJUMP_FORMAT = None _TERM_FORMAT = None _COMMENT_FORMAT = string.Template(",
"1 << len(addr_list).bit_length() set_maxelem = set_hashsize output.append('%s %s %s family",
"generator. ipset is a system inside the Linux kernel, which",
"we never return any exclude addresses. Instead least positive match",
"cases are possible. First case is when there are no",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"1: set_name = self._GenerateSetName(self.term.name, direction) self.addr_sets[direction] = (set_name, addr_list) addr_list",
"= nacaddr.ExcludeAddrs(addr_list, addr_exclude_list) if len(addr_list) > 1: set_name = self._GenerateSetName(self.term.name,",
"addr_list def _GenerateAddressStatement(self, src_addr, dst_addr): \"\"\"Returns the address section of",
"'dst' in self.addr_sets: dst_addr_stmt = ('-m set --match-set %s dst'",
"this file except in compliance with the License. # You",
"very efficiently store and match IPv4 and IPv6 addresses. This",
"target address family. direction: direction in which address list will",
"reverse=True): set_name, addr_list = term.addr_sets[direction] set_hashsize = 1 << len(addr_list).bit_length()",
"case we return single address match (-s or -d). Third",
"list. addr_exclude_list: address exclude list of the term. target_af: target",
"a subclass of Iptables generator. ipset is a system inside",
"where no set is actually generated. Args: src_addr_list: source address",
"address list. addr_exclude_list: address exclude list of the term. target_af:",
"store and match IPv4 and IPv6 addresses. This can be",
"return '\\n'.join(output) def _GenerateSetConfig(self, term): \"\"\"Generates set configuration for supplied",
"# # Licensed under the Apache License, Version 2.0 (the",
"individual iptables rule. See _CalculateAddresses documentation. Three cases are possible",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"also the set for particular direction is present. That's when",
"% (c_str, set_name, self._SET_TYPE, term.af, set_hashsize, set_maxelem)) for address in",
"and dst_addr: if src_addr == self._all_ips: if 'src' in self.addr_sets:",
"addr_list, addr_exclude_list, target_af, direction): \"\"\"Calculates and stores address list for",
"order. \"\"\" src_addr_stmt = '' dst_addr_stmt = '' if src_addr",
"addr_list) addr_list = [self._all_ips] return addr_list def _GenerateAddressStatement(self, src_addr, dst_addr):",
"calculated for both source and destination addresses. For source and",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"= [] c_str = 'create' a_str = 'add' if 'exists'",
"direction) self.addr_sets[direction] = (set_name, addr_list) addr_list = [self._all_ips] return addr_list",
"= 'ipset' _SET_TYPE = 'hash:net' SUFFIX = '.ips' _TERM =",
"for address in addr_list: output.append('%s %s %s' % (a_str, set_name,",
"http://www.apache.org/licenses/LICENSE-2.0 # # unless required by applicable law or agreed",
"if len(term_name) + len(suffix) + 1 > self._SET_MAX_LENGTH: set_name_max_lenth =",
"part. iptables_output = super().__str__() output = [] output.append(self._MARKER_BEGIN) for (_,",
"= string.Template( '-A $filter -m comment --comment \"$comment\"') _FILTER_TOP_FORMAT =",
"_COMMENT_FORMAT = string.Template( '-A $filter -m comment --comment \"$comment\"') _FILTER_TOP_FORMAT",
"so it has to be called # before we do",
"\"\"\"Returns the address section of an individual iptables rule. See",
"supplied term. Args: term: input term. Returns: string that is",
"Since ipset is very efficient at matching large number of",
"has to be called # before we do set specific",
"[] c_str = 'create' a_str = 'add' if 'exists' in",
"containing source and destination address statement, in that order. \"\"\"",
"Args: addr_list: address list. addr_exclude_list: address exclude list of the",
"Google Inc. All Rights Reserved. # # Licensed under the",
"\"\"\" src_addr_stmt = '' dst_addr_stmt = '' if src_addr and",
"inside the Linux kernel, which can very efficiently store and",
"in addr_exclude_list if addr_exclude.version == target_af] addr_list = nacaddr.ExcludeAddrs(addr_list, addr_exclude_list)",
"addr_list = [addr for addr in addr_list if addr.version ==",
"src_addr_stmt = ('-m set --match-set %s src' % self.addr_sets['src'][0]) else:",
"in addr_list: output.append('%s %s %s' % (a_str, set_name, address)) return",
"direction (value is _all_ips then) In that case we return",
"and it's then the only element of returned set. Third",
"%i maxelem %i' % (c_str, set_name, self._SET_TYPE, term.af, set_hashsize, set_maxelem))",
"no addresses. In that case we return _all_ips. Second case",
"if 'dst' in self.addr_sets: dst_addr_stmt = ('-m set --match-set %s",
"used to dramatically increase performace of iptables firewall. \"\"\" import",
"actually generated. Args: src_addr_list: source address list of the term.",
"dst_addr_list = self._CalculateAddrList(dst_addr_list, dst_addr_exclude_list, target_af, 'dst') return (src_addr_list, [], dst_addr_list,",
"in that order. \"\"\" src_addr_stmt = '' dst_addr_stmt = ''",
"empty string. Second there can be stricly one address. In",
"addr.version == target_af] if addr_exclude_list: addr_exclude_list = [addr_exclude for addr_exclude",
"term. Returns: string that is configuration of supplied term. \"\"\"",
"by not generating a set, and it's then the only",
"in which address list will be used. Returns: calculated address",
"very efficient at matching large number of addresses, we never",
"'ipset' _SET_MAX_LENGTH = 31 _POSTJUMP_FORMAT = None _PREJUMP_FORMAT = None",
"list, destination address exclude list in that order. \"\"\" target_af",
"= '-d %s/%d' % (dst_addr.network_address, dst_addr.prefixlen) return (src_addr_stmt, dst_addr_stmt) def",
"in self.addr_sets: dst_addr_stmt = ('-m set --match-set %s dst' %",
"the term. src_addr_exclude_list: source address exclude list of the term.",
"return _all_ips. Note the difference to the first case where",
"the term. dst_addr_list: destination address list of the term. dst_addr_exclude_list:",
"configuration for supplied term. Args: term: input term. Returns: string",
"or implied. # See the License for the specific language",
"dst_addr_stmt) def _GenerateSetName(self, term_name, suffix): if self.af == 'inet6': suffix",
"Rights Reserved. # # Licensed under the Apache License, Version",
"is present. That's when we return a set match. Args:",
"address exclude list of the term. Returns: tuple containing source",
"a direction (value is _all_ips then) In that case we",
"(dst_addr.network_address, dst_addr.prefixlen) return (src_addr_stmt, dst_addr_stmt) def _GenerateSetName(self, term_name, suffix): if",
"dst_addr == self._all_ips: if 'dst' in self.addr_sets: dst_addr_stmt = ('-m",
"can be stricly one address. In that case we return",
"there can be no addresses for a direction (value is",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"of returned set. Third case is when there are more",
"len(term_name) + len(suffix) + 1 > self._SET_MAX_LENGTH: set_name_max_lenth = self._SET_MAX_LENGTH",
"_PREJUMP_FORMAT = None _TERM_FORMAT = None _COMMENT_FORMAT = string.Template( '-A",
"replace with explicit method def __str__(self): # Actual rendering happens",
"= None _COMMENT_FORMAT = string.Template( '-A $filter -m comment --comment",
"exclude list in that order. \"\"\" target_af = self.AF_MAP[self.af] src_addr_list",
"list for target AF and direction. Args: addr_list: address list.",
"Third case, is when the value is _all_ips but also",
"address of the rule. Returns: tuple containing source and destination",
"is very efficient at matching large number of addresses, we",
"the term. target_af: target address family. direction: direction in which",
"in self.addr_sets: src_addr_stmt = ('-m set --match-set %s src' %",
"'# begin:ipset-rules' _MARKER_END = '# end:ipset-rules' _GOOD_OPTIONS = ['nostate', 'abbreviateterms',",
"term_name = term_name[:set_name_max_lenth] return '%s-%s' % (term_name, suffix) class Ipset(iptables.Iptables):",
"when there is strictly one address. In that case, we",
"the address section of an individual iptables rule. See _CalculateAddresses",
"begin:ipset-rules' _MARKER_END = '# end:ipset-rules' _GOOD_OPTIONS = ['nostate', 'abbreviateterms', 'truncateterms',",
"= 'add' if 'exists' in self.filter_options: c_str = c_str +",
"import iptables from capirca.lib import nacaddr class Error(Exception): \"\"\"Base error",
"an individual iptables rule. See _CalculateAddresses documentation. Three cases are",
"which can very efficiently store and match IPv4 and IPv6",
"set name and set contents, keyed by direction. # For",
"# Actual rendering happens in __str__, so it has to",
"== 'inet6': suffix += '-v6' if len(term_name) + len(suffix) +",
"= None _PREJUMP_FORMAT = None _TERM_FORMAT = None _COMMENT_FORMAT =",
"(the \"License\"); # you may not use this file except",
"destination addresses. For source and destination address list, three cases",
"map directly to cases in _CalculateAddresses. First, there can be",
"self._all_ips: if 'dst' in self.addr_sets: dst_addr_stmt = ('-m set --match-set",
"# you may not use this file except in compliance",
"destination address list, destination address exclude list in that order.",
"== target_af] addr_list = nacaddr.ExcludeAddrs(addr_list, addr_exclude_list) if len(addr_list) > 1:",
"system inside the Linux kernel, which can very efficiently store",
"_POSTJUMP_FORMAT = None _PREJUMP_FORMAT = None _TERM_FORMAT = None _COMMENT_FORMAT",
"object]) } self.addr_sets = {} def _CalculateAddresses(self, src_addr_list, src_addr_exclude_list, dst_addr_list,",
"Args: term: input term. Returns: string that is configuration of",
"name and set contents, keyed by direction. # For example:",
"family %s hashsize %i maxelem %i' % (c_str, set_name, self._SET_TYPE,",
"address. In that case we return single address match (-s",
"error class.\"\"\" class Term(iptables.Term): \"\"\"Single Ipset term representation.\"\"\" _PLATFORM =",
"possible here, and they map directly to cases in _CalculateAddresses.",
"\"\"\"Ipset generator.\"\"\" _PLATFORM = 'ipset' _SET_TYPE = 'hash:net' SUFFIX =",
"Ipset term representation.\"\"\" _PLATFORM = 'ipset' _SET_MAX_LENGTH = 31 _POSTJUMP_FORMAT",
"'-d %s/%d' % (dst_addr.network_address, dst_addr.prefixlen) return (src_addr_stmt, dst_addr_stmt) def _GenerateSetName(self,",
"In that case we return empty string. Second there can",
"== self._all_ips: if 'dst' in self.addr_sets: dst_addr_stmt = ('-m set",
"_GOOD_OPTIONS = ['nostate', 'abbreviateterms', 'truncateterms', 'noverbose', 'exists'] # TODO(vklimovs): some",
"if src_addr and dst_addr: if src_addr == self._all_ips: if 'src'",
"address list for a term. Since ipset is very efficient",
"set is actually generated. Args: src_addr_list: source address list of",
"= '' if src_addr and dst_addr: if src_addr == self._all_ips:",
"Term(iptables.Term): \"\"\"Single Ipset term representation.\"\"\" _PLATFORM = 'ipset' _SET_MAX_LENGTH =",
"src_addr and dst_addr: if src_addr == self._all_ips: if 'src' in",
"= [self._all_ips] return addr_list def _GenerateAddressStatement(self, src_addr, dst_addr): \"\"\"Returns the",
"target_af, 'dst') return (src_addr_list, [], dst_addr_list, []) def _CalculateAddrList(self, addr_list,",
"return (src_addr_stmt, dst_addr_stmt) def _GenerateSetName(self, term_name, suffix): if self.af ==",
"_CalculateAddresses. First, there can be no addresses for a direction",
"dst_addr_list: destination address list of the term. dst_addr_exclude_list: destination address",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"permissions and # limitations under the License. # \"\"\"Ipset iptables",
"= (set_name, addr_list) addr_list = [self._all_ips] return addr_list def _GenerateAddressStatement(self,",
"len(suffix) + 1 > self._SET_MAX_LENGTH: set_name_max_lenth = self._SET_MAX_LENGTH - len(suffix)",
"_MARKER_END = '# end:ipset-rules' _GOOD_OPTIONS = ['nostate', 'abbreviateterms', 'truncateterms', 'noverbose',",
"that case, we optimize by not generating a set, and",
"a set match. Args: src_addr: ipaddr address or network object",
"iptables_output = super().__str__() output = [] output.append(self._MARKER_BEGIN) for (_, _,",
"Version 2.0 (the \"License\"); # you may not use this",
"output.append(self._MARKER_BEGIN) for (_, _, _, _, terms) in self.iptables_policies: for",
"only element of returned set. Third case is when there",
"[] output.append(self._MARKER_BEGIN) for (_, _, _, _, terms) in self.iptables_policies:",
"for addr in addr_list if addr.version == target_af] if addr_exclude_list:",
"but also the set for particular direction is present. That's",
"in a set. In that case we generate a set",
"then the only element of returned set. Third case is",
"return _all_ips. Second case is when there is strictly one",
"can very efficiently store and match IPv4 and IPv6 addresses.",
"when we return a set match. Args: src_addr: ipaddr address",
"if 'exists' in self.filter_options: c_str = c_str + ' -exist'",
"%s/%d' % (dst_addr.network_address, dst_addr.prefixlen) return (src_addr_stmt, dst_addr_stmt) def _GenerateSetName(self, term_name,",
"addresses, we never return any exclude addresses. Instead least positive",
"implied. # See the License for the specific language governing",
"addresses for a direction (value is _all_ips then) In that",
"case we generate a set and also return _all_ips. Note",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"addr in addr_list if addr.version == target_af] if addr_exclude_list: addr_exclude_list",
"destination address list for a term. Since ipset is very",
"for both source and destination addresses. For source and destination",
"self._SET_TYPE, term.af, set_hashsize, set_maxelem)) for address in addr_list: output.append('%s %s",
"terms: output.extend(self._GenerateSetConfig(term)) output.append(self._MARKER_END) output.append(iptables_output) return '\\n'.join(output) def _GenerateSetConfig(self, term): \"\"\"Generates",
"# 'dst': ('set_name', [ipaddr object, ipaddr object]) } self.addr_sets =",
"of the term. src_addr_exclude_list: source address exclude list of the",
"addr_list = [self._all_ips] return addr_list def _GenerateAddressStatement(self, src_addr, dst_addr): \"\"\"Returns",
"be used. Returns: calculated address list. \"\"\" if not addr_list:",
"by applicable law or agreed to in writing, software #",
"case is when there are no addresses. In that case",
"will be used. Returns: calculated address list. \"\"\" if not",
"the only element of returned set. Third case is when",
"cases in _CalculateAddresses. First, there can be no addresses for",
"_GenerateSetConfig(self, term): \"\"\"Generates set configuration for supplied term. Args: term:",
"addresses. This can be used to dramatically increase performace of",
"one address. In that case, we optimize by not generating",
"address. In that case, we optimize by not generating a",
"source address exclude list, destination address list, destination address exclude",
"src_addr: ipaddr address or network object with source address of",
"Second there can be stricly one address. In that case",
"term.af, set_hashsize, set_maxelem)) for address in addr_list: output.append('%s %s %s'",
"'src') dst_addr_list = self._CalculateAddrList(dst_addr_list, dst_addr_exclude_list, target_af, 'dst') return (src_addr_list, [],",
"value is _all_ips but also the set for particular direction",
"dst_addr_exclude_list): \"\"\"Calculates source and destination address list for a term.",
"[ipaddr object, ipaddr object]), # 'dst': ('set_name', [ipaddr object, ipaddr",
"dst_addr: ipaddr address or network object with destination address of",
"for addr_exclude in addr_exclude_list if addr_exclude.version == target_af] addr_list =",
"__str__, so it has to be called # before we",
"'create' a_str = 'add' if 'exists' in self.filter_options: c_str =",
"term.addr_sets[direction] set_hashsize = 1 << len(addr_list).bit_length() set_maxelem = set_hashsize output.append('%s",
"is when there are no addresses. In that case we",
"'src': ('set_name', [ipaddr object, ipaddr object]), # 'dst': ('set_name', [ipaddr",
"from capirca.lib import nacaddr class Error(Exception): \"\"\"Base error class.\"\"\" class",
"of the term. Returns: tuple containing source address list, source",
"1 > self._SET_MAX_LENGTH: set_name_max_lenth = self._SET_MAX_LENGTH - len(suffix) - 1",
"= 'create' a_str = 'add' if 'exists' in self.filter_options: c_str",
"here, and they map directly to cases in _CalculateAddresses. First,",
"that case we generate a set and also return _all_ips.",
"set configuration for supplied term. Args: term: input term. Returns:",
"three cases are possible. First case is when there are",
"for a direction (value is _all_ips then) In that case",
"ipset is very efficient at matching large number of addresses,",
"def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This stores tuples",
"if not addr_list: addr_list = [self._all_ips] addr_list = [addr for",
"source address list, source address exclude list, destination address list,",
"sorted(term.addr_sets, reverse=True): set_name, addr_list = term.addr_sets[direction] set_hashsize = 1 <<",
"term. dst_addr_list: destination address list of the term. dst_addr_exclude_list: destination",
"target AF and direction. Args: addr_list: address list. addr_exclude_list: address",
"nacaddr class Error(Exception): \"\"\"Base error class.\"\"\" class Term(iptables.Term): \"\"\"Single Ipset",
"that order. \"\"\" src_addr_stmt = '' dst_addr_stmt = '' if",
"dst_addr.prefixlen) return (src_addr_stmt, dst_addr_stmt) def _GenerateSetName(self, term_name, suffix): if self.af",
"Ipset(iptables.Iptables): \"\"\"Ipset generator.\"\"\" _PLATFORM = 'ipset' _SET_TYPE = 'hash:net' SUFFIX",
"ipset is a system inside the Linux kernel, which can",
"$filter -m comment --comment \"$comment\"') _FILTER_TOP_FORMAT = string.Template('-A $filter') def",
"iptables from capirca.lib import nacaddr class Error(Exception): \"\"\"Base error class.\"\"\"",
"strictly one address. In that case, we optimize by not",
"_MARKER_BEGIN = '# begin:ipset-rules' _MARKER_END = '# end:ipset-rules' _GOOD_OPTIONS =",
"tuple containing source and destination address statement, in that order.",
"IPv6 addresses. This can be used to dramatically increase performace",
"% (dst_addr.network_address, dst_addr.prefixlen) return (src_addr_stmt, dst_addr_stmt) def _GenerateSetName(self, term_name, suffix):",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"efficient at matching large number of addresses, we never return",
"when there are no addresses. In that case we return",
"See _CalculateAddresses documentation. Three cases are possible here, and they",
"that order. \"\"\" target_af = self.AF_MAP[self.af] src_addr_list = self._CalculateAddrList(src_addr_list, src_addr_exclude_list,",
"In that case we return single address match (-s or",
"nacaddr.ExcludeAddrs(addr_list, addr_exclude_list) if len(addr_list) > 1: set_name = self._GenerateSetName(self.term.name, direction)",
"term. Returns: tuple containing source address list, source address exclude",
"'ipset' _SET_TYPE = 'hash:net' SUFFIX = '.ips' _TERM = Term",
"efficiently store and match IPv4 and IPv6 addresses. This can",
"import string from capirca.lib import iptables from capirca.lib import nacaddr",
"not generating a set, and it's then the only element",
"- 1 term_name = term_name[:set_name_max_lenth] return '%s-%s' % (term_name, suffix)",
"if 'src' in self.addr_sets: src_addr_stmt = ('-m set --match-set %s",
"address list, three cases are possible. First case is when",
"case we return empty string. Second there can be stricly",
"else: src_addr_stmt = '-s %s/%d' % (src_addr.network_address, src_addr.prefixlen) if dst_addr",
"For source and destination address list, three cases are possible.",
"the specific language governing permissions and # limitations under the",
"we generate a set and also return _all_ips. Note the",
"direction. # For example: # { 'src': ('set_name', [ipaddr object,",
"term. src_addr_exclude_list: source address exclude list of the term. dst_addr_list:",
"object with source address of the rule. dst_addr: ipaddr address",
"or network object with source address of the rule. dst_addr:",
"exclude list, destination address list, destination address exclude list in",
"address list will be used. Returns: calculated address list. \"\"\"",
"applicable law or agreed to in writing, software # distributed",
"any exclude addresses. Instead least positive match is calculated for",
"term representation.\"\"\" _PLATFORM = 'ipset' _SET_MAX_LENGTH = 31 _POSTJUMP_FORMAT =",
"address list. \"\"\" if not addr_list: addr_list = [self._all_ips] addr_list",
"\"\"\"Calculates and stores address list for target AF and direction.",
"address of the rule. dst_addr: ipaddr address or network object",
"len(suffix) - 1 term_name = term_name[:set_name_max_lenth] return '%s-%s' % (term_name,",
"\"\"\" target_af = self.AF_MAP[self.af] src_addr_list = self._CalculateAddrList(src_addr_list, src_addr_exclude_list, target_af, 'src')",
"set_name = self._GenerateSetName(self.term.name, direction) self.addr_sets[direction] = (set_name, addr_list) addr_list =",
"list of the term. src_addr_exclude_list: source address exclude list of",
"a system inside the Linux kernel, which can very efficiently",
"c_str + ' -exist' a_str = a_str + ' -exist'",
"output = [] c_str = 'create' a_str = 'add' if",
"that case we return _all_ips. Second case is when there",
"Note the difference to the first case where no set",
"for supplied term. Args: term: input term. Returns: string that",
"iptables generator. This is a subclass of Iptables generator. ipset",
"_, _, terms) in self.iptables_policies: for term in terms: output.extend(self._GenerateSetConfig(term))",
"Iptables generator. ipset is a system inside the Linux kernel,",
"example: # { 'src': ('set_name', [ipaddr object, ipaddr object]), #",
"least positive match is calculated for both source and destination",
"(src_addr_list, [], dst_addr_list, []) def _CalculateAddrList(self, addr_list, addr_exclude_list, target_af, direction):",
"src_addr_exclude_list, dst_addr_list, dst_addr_exclude_list): \"\"\"Calculates source and destination address list for",
"with source address of the rule. dst_addr: ipaddr address or",
"(c_str, set_name, self._SET_TYPE, term.af, set_hashsize, set_maxelem)) for address in addr_list:",
"in writing, software # distributed under the License is distributed",
"there are more than one address in a set. In",
"set and also return _all_ips. Note the difference to the",
"there is strictly one address. In that case, we optimize",
"[self._all_ips] addr_list = [addr for addr in addr_list if addr.version",
"of an individual iptables rule. See _CalculateAddresses documentation. Three cases",
"generator. This is a subclass of Iptables generator. ipset is",
"object, ipaddr object]), # 'dst': ('set_name', [ipaddr object, ipaddr object])",
"Linux kernel, which can very efficiently store and match IPv4",
"to the first case where no set is actually generated.",
"address exclude list in that order. \"\"\" target_af = self.AF_MAP[self.af]",
"is when the value is _all_ips but also the set",
"in that order. \"\"\" target_af = self.AF_MAP[self.af] src_addr_list = self._CalculateAddrList(src_addr_list,",
"= self._GenerateSetName(self.term.name, direction) self.addr_sets[direction] = (set_name, addr_list) addr_list = [self._all_ips]",
"direction): \"\"\"Calculates and stores address list for target AF and",
"'' dst_addr_stmt = '' if src_addr and dst_addr: if src_addr",
"('-m set --match-set %s dst' % self.addr_sets['dst'][0]) else: dst_addr_stmt =",
"\"\"\" if not addr_list: addr_list = [self._all_ips] addr_list = [addr",
"network object with source address of the rule. dst_addr: ipaddr",
"\"\"\" output = [] c_str = 'create' a_str = 'add'",
"In that case, we optimize by not generating a set,",
"set match. Args: src_addr: ipaddr address or network object with",
"= term.addr_sets[direction] set_hashsize = 1 << len(addr_list).bit_length() set_maxelem = set_hashsize",
"class.\"\"\" class Term(iptables.Term): \"\"\"Single Ipset term representation.\"\"\" _PLATFORM = 'ipset'",
"term. target_af: target address family. direction: direction in which address",
"matching large number of addresses, we never return any exclude",
"case, we optimize by not generating a set, and it's",
"dst_addr_list, dst_addr_exclude_list): \"\"\"Calculates source and destination address list for a",
"--match-set %s dst' % self.addr_sets['dst'][0]) else: dst_addr_stmt = '-d %s/%d'",
"object]), # 'dst': ('set_name', [ipaddr object, ipaddr object]) } self.addr_sets",
"= '.ips' _TERM = Term _MARKER_BEGIN = '# begin:ipset-rules' _MARKER_END",
"_all_ips. Note the difference to the first case where no",
"match (-s or -d). Third case, is when the value",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"is actually generated. Args: src_addr_list: source address list of the",
"destination address list of the term. dst_addr_exclude_list: destination address exclude",
"addr_exclude_list, target_af, direction): \"\"\"Calculates and stores address list for target",
"this # __str__, replace with explicit method def __str__(self): #",
"License, Version 2.0 (the \"License\"); # you may not use",
"set specific part. iptables_output = super().__str__() output = [] output.append(self._MARKER_BEGIN)",
"# http://www.apache.org/licenses/LICENSE-2.0 # # unless required by applicable law or",
"# You may obtain a copy of the License at",
"% (src_addr.network_address, src_addr.prefixlen) if dst_addr == self._all_ips: if 'dst' in",
"# __str__, replace with explicit method def __str__(self): # Actual",
"IPv4 and IPv6 addresses. This can be used to dramatically",
"a_str = 'add' if 'exists' in self.filter_options: c_str = c_str",
"self._CalculateAddrList(src_addr_list, src_addr_exclude_list, target_af, 'src') dst_addr_list = self._CalculateAddrList(dst_addr_list, dst_addr_exclude_list, target_af, 'dst')",
"return addr_list def _GenerateAddressStatement(self, src_addr, dst_addr): \"\"\"Returns the address section",
"This stores tuples of set name and set contents, keyed",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"is when there are more than one address in a",
"[addr for addr in addr_list if addr.version == target_af] if",
"self.iptables_policies: for term in terms: output.extend(self._GenerateSetConfig(term)) output.append(self._MARKER_END) output.append(iptables_output) return '\\n'.join(output)",
"the set for particular direction is present. That's when we",
"suffix += '-v6' if len(term_name) + len(suffix) + 1 >",
"In that case we return _all_ips. Second case is when",
"_FILTER_TOP_FORMAT = string.Template('-A $filter') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)",
"destination address exclude list in that order. \"\"\" target_af =",
"and destination addresses. For source and destination address list, three",
"exclude addresses. Instead least positive match is calculated for both",
"set contents, keyed by direction. # For example: # {",
"list of the term. Returns: tuple containing source address list,",
"rule. See _CalculateAddresses documentation. Three cases are possible here, and",
"'hash:net' SUFFIX = '.ips' _TERM = Term _MARKER_BEGIN = '#",
"addr_list if addr.version == target_af] if addr_exclude_list: addr_exclude_list = [addr_exclude",
"SUFFIX = '.ips' _TERM = Term _MARKER_BEGIN = '# begin:ipset-rules'",
"and stores address list for target AF and direction. Args:",
"the License for the specific language governing permissions and #",
"in self.filter_options: c_str = c_str + ' -exist' a_str =",
"statement, in that order. \"\"\" src_addr_stmt = '' dst_addr_stmt =",
"term. \"\"\" output = [] c_str = 'create' a_str =",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"term. Args: term: input term. Returns: string that is configuration",
"either express or implied. # See the License for the",
"= '-s %s/%d' % (src_addr.network_address, src_addr.prefixlen) if dst_addr == self._all_ips:",
"= [] output.append(self._MARKER_BEGIN) for (_, _, _, _, terms) in",
"called # before we do set specific part. iptables_output =",
"keyed by direction. # For example: # { 'src': ('set_name',",
"class Ipset(iptables.Iptables): \"\"\"Ipset generator.\"\"\" _PLATFORM = 'ipset' _SET_TYPE = 'hash:net'",
"it's then the only element of returned set. Third case",
"= c_str + ' -exist' a_str = a_str + '",
"--match-set %s src' % self.addr_sets['src'][0]) else: src_addr_stmt = '-s %s/%d'",
"term_name[:set_name_max_lenth] return '%s-%s' % (term_name, suffix) class Ipset(iptables.Iptables): \"\"\"Ipset generator.\"\"\"",
"**kwargs): super().__init__(*args, **kwargs) # This stores tuples of set name",
"'dst') return (src_addr_list, [], dst_addr_list, []) def _CalculateAddrList(self, addr_list, addr_exclude_list,",
"to be called # before we do set specific part.",
"direction in sorted(term.addr_sets, reverse=True): set_name, addr_list = term.addr_sets[direction] set_hashsize =",
"% (term_name, suffix) class Ipset(iptables.Iptables): \"\"\"Ipset generator.\"\"\" _PLATFORM = 'ipset'",
"list of the term. dst_addr_list: destination address list of the",
"self.addr_sets['src'][0]) else: src_addr_stmt = '-s %s/%d' % (src_addr.network_address, src_addr.prefixlen) if",
"addresses. Instead least positive match is calculated for both source",
"rule. dst_addr: ipaddr address or network object with destination address",
"destination address statement, in that order. \"\"\" src_addr_stmt = ''",
"source address list of the term. src_addr_exclude_list: source address exclude",
"self.af == 'inet6': suffix += '-v6' if len(term_name) + len(suffix)",
"a_str = a_str + ' -exist' for direction in sorted(term.addr_sets,",
"'\\n'.join(output) def _GenerateSetConfig(self, term): \"\"\"Generates set configuration for supplied term.",
"return (src_addr_list, [], dst_addr_list, []) def _CalculateAddrList(self, addr_list, addr_exclude_list, target_af,",
"explicit method def __str__(self): # Actual rendering happens in __str__,",
"string. Second there can be stricly one address. In that",
"the rule. Returns: tuple containing source and destination address statement,",
"_, _, _, terms) in self.iptables_policies: for term in terms:",
"can be no addresses for a direction (value is _all_ips",
"None _COMMENT_FORMAT = string.Template( '-A $filter -m comment --comment \"$comment\"')",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"return a set match. Args: src_addr: ipaddr address or network",
"%s/%d' % (src_addr.network_address, src_addr.prefixlen) if dst_addr == self._all_ips: if 'dst'",
"c_str = 'create' a_str = 'add' if 'exists' in self.filter_options:",
"address in addr_list: output.append('%s %s %s' % (a_str, set_name, address))",
"are possible. First case is when there are no addresses.",
"for (_, _, _, _, terms) in self.iptables_policies: for term",
"('-m set --match-set %s src' % self.addr_sets['src'][0]) else: src_addr_stmt =",
"# Copyright 2015 Google Inc. All Rights Reserved. # #",
"the rule. dst_addr: ipaddr address or network object with destination",
"in sorted(term.addr_sets, reverse=True): set_name, addr_list = term.addr_sets[direction] set_hashsize = 1",
"# \"\"\"Ipset iptables generator. This is a subclass of Iptables",
"of the term. target_af: target address family. direction: direction in",
"_TERM_FORMAT = None _COMMENT_FORMAT = string.Template( '-A $filter -m comment",
"Copyright 2015 Google Inc. All Rights Reserved. # # Licensed",
"For example: # { 'src': ('set_name', [ipaddr object, ipaddr object]),",
"(-s or -d). Third case, is when the value is",
"*args, **kwargs): super().__init__(*args, **kwargs) # This stores tuples of set",
"} self.addr_sets = {} def _CalculateAddresses(self, src_addr_list, src_addr_exclude_list, dst_addr_list, dst_addr_exclude_list):",
"list, three cases are possible. First case is when there",
"to dramatically increase performace of iptables firewall. \"\"\" import string",
"a set. In that case we generate a set and",
"self.addr_sets: src_addr_stmt = ('-m set --match-set %s src' % self.addr_sets['src'][0])",
"self._GenerateSetName(self.term.name, direction) self.addr_sets[direction] = (set_name, addr_list) addr_list = [self._all_ips] return",
"target_af = self.AF_MAP[self.af] src_addr_list = self._CalculateAddrList(src_addr_list, src_addr_exclude_list, target_af, 'src') dst_addr_list",
"= term_name[:set_name_max_lenth] return '%s-%s' % (term_name, suffix) class Ipset(iptables.Iptables): \"\"\"Ipset",
"\"\"\"Single Ipset term representation.\"\"\" _PLATFORM = 'ipset' _SET_MAX_LENGTH = 31",
"# This stores tuples of set name and set contents,",
"+ ' -exist' for direction in sorted(term.addr_sets, reverse=True): set_name, addr_list",
"target_af] if addr_exclude_list: addr_exclude_list = [addr_exclude for addr_exclude in addr_exclude_list",
"case we return _all_ips. Second case is when there is",
"iptables rule. See _CalculateAddresses documentation. Three cases are possible here,",
"one address. In that case we return single address match",
"and destination address list, three cases are possible. First case",
"source and destination address statement, in that order. \"\"\" src_addr_stmt",
"\"License\"); # you may not use this file except in",
"list. \"\"\" if not addr_list: addr_list = [self._all_ips] addr_list =",
"under the License. # \"\"\"Ipset iptables generator. This is a",
"source and destination addresses. For source and destination address list,",
"Instead least positive match is calculated for both source and",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"+ len(suffix) + 1 > self._SET_MAX_LENGTH: set_name_max_lenth = self._SET_MAX_LENGTH -",
"hashsize %i maxelem %i' % (c_str, set_name, self._SET_TYPE, term.af, set_hashsize,",
"(value is _all_ips then) In that case we return empty",
"# distributed under the License is distributed on an \"AS",
"capirca.lib import iptables from capirca.lib import nacaddr class Error(Exception): \"\"\"Base",
"string.Template( '-A $filter -m comment --comment \"$comment\"') _FILTER_TOP_FORMAT = string.Template('-A",
"'%s-%s' % (term_name, suffix) class Ipset(iptables.Iptables): \"\"\"Ipset generator.\"\"\" _PLATFORM =",
"optimize by not generating a set, and it's then the",
"= self.AF_MAP[self.af] src_addr_list = self._CalculateAddrList(src_addr_list, src_addr_exclude_list, target_af, 'src') dst_addr_list =",
"src_addr_list: source address list of the term. src_addr_exclude_list: source address",
"the License. # \"\"\"Ipset iptables generator. This is a subclass",
"--comment \"$comment\"') _FILTER_TOP_FORMAT = string.Template('-A $filter') def __init__(self, *args, **kwargs):",
"('set_name', [ipaddr object, ipaddr object]), # 'dst': ('set_name', [ipaddr object,",
"and IPv6 addresses. This can be used to dramatically increase",
"[], dst_addr_list, []) def _CalculateAddrList(self, addr_list, addr_exclude_list, target_af, direction): \"\"\"Calculates",
"and direction. Args: addr_list: address list. addr_exclude_list: address exclude list",
"target_af: target address family. direction: direction in which address list",
"is a subclass of Iptables generator. ipset is a system",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"if addr_exclude.version == target_af] addr_list = nacaddr.ExcludeAddrs(addr_list, addr_exclude_list) if len(addr_list)",
"Args: src_addr: ipaddr address or network object with source address",
"-exist' a_str = a_str + ' -exist' for direction in",
"particular direction is present. That's when we return a set",
"%s %s family %s hashsize %i maxelem %i' % (c_str,",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # unless required by applicable",
"dst' % self.addr_sets['dst'][0]) else: dst_addr_stmt = '-d %s/%d' % (dst_addr.network_address,",
"or -d). Third case, is when the value is _all_ips",
"difference to the first case where no set is actually",
"# # unless required by applicable law or agreed to",
"class Error(Exception): \"\"\"Base error class.\"\"\" class Term(iptables.Term): \"\"\"Single Ipset term",
"directly to cases in _CalculateAddresses. First, there can be no",
"set --match-set %s src' % self.addr_sets['src'][0]) else: src_addr_stmt = '-s",
"is happening inside this # __str__, replace with explicit method",
"src_addr == self._all_ips: if 'src' in self.addr_sets: src_addr_stmt = ('-m",
"address exclude list, destination address list, destination address exclude list",
"order. \"\"\" target_af = self.AF_MAP[self.af] src_addr_list = self._CalculateAddrList(src_addr_list, src_addr_exclude_list, target_af,",
"You may obtain a copy of the License at #",
"def _GenerateSetName(self, term_name, suffix): if self.af == 'inet6': suffix +=",
"in _CalculateAddresses. First, there can be no addresses for a",
"of the rule. Returns: tuple containing source and destination address",
"__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This stores tuples of",
"%s src' % self.addr_sets['src'][0]) else: src_addr_stmt = '-s %s/%d' %",
"processing is happening inside this # __str__, replace with explicit",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # unless required",
"output.append('%s %s %s family %s hashsize %i maxelem %i' %",
"is strictly one address. In that case, we optimize by",
"it has to be called # before we do set",
"present. That's when we return a set match. Args: src_addr:",
"c_str = c_str + ' -exist' a_str = a_str +",
"import nacaddr class Error(Exception): \"\"\"Base error class.\"\"\" class Term(iptables.Term): \"\"\"Single",
"addr_list: addr_list = [self._all_ips] addr_list = [addr for addr in",
"there can be stricly one address. In that case we",
"is _all_ips then) In that case we return empty string.",
"That's when we return a set match. Args: src_addr: ipaddr",
"= ('-m set --match-set %s src' % self.addr_sets['src'][0]) else: src_addr_stmt",
"a term. Since ipset is very efficient at matching large",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"generator.\"\"\" _PLATFORM = 'ipset' _SET_TYPE = 'hash:net' SUFFIX = '.ips'",
"(_, _, _, _, terms) in self.iptables_policies: for term in",
"set, and it's then the only element of returned set.",
"Args: src_addr_list: source address list of the term. src_addr_exclude_list: source",
"when there are more than one address in a set.",
"destination address list, three cases are possible. First case is",
"destination address of the rule. Returns: tuple containing source and",
"string.Template('-A $filter') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This",
"self._all_ips: if 'src' in self.addr_sets: src_addr_stmt = ('-m set --match-set",
"Third case is when there are more than one address",
"a set and also return _all_ips. Note the difference to"
] |
[
"# need to do r['data'][:r['length']] here. # This simplifies downsampling.",
"should not overlap # but... https://github.com/AxFoundation/strax/issues/119 y[y_start:y_end, r['channel']] += w[r_start:r_end]",
"w = w.reshape(duration // dt, -1).sum(axis=1).astype(np.int32) elif dt < r['dt']:",
"@straxen.mini_analysis(requires=('records',), warn_beyond_sec=10, default_time_selection='touching') def records_matrix(records, time_range, seconds_range, config, to_pe, max_samples=DEFAULT_MAX_SAMPLES,",
"to_pe, max_samples=DEFAULT_MAX_SAMPLES, ignore_max_sample_warning=False): \"\"\"Return (wv_matrix, times, pms) - wv_matrix: (n_samples,",
"ys = np.arange(wvm.shape[1] + 1) return wvm, ts, ys @straxen.mini_analysis(requires=('raw_records',),",
"if dt >= samples_per_record * r['dt']: # Downsample to single",
"rows) - pmts: PMT numbers (corr. to columns) Both times",
"happy ... ?? w = w.reshape(duration // dt, -1).sum(axis=1).astype(np.int32) elif",
"we do not # need to do r['data'][:r['length']] here. #",
"max_samples {max_samples}, \" f\"downsampling to dt = {dt} ns.\") wvm",
"not be able to baseline correctly # at the start",
"t0, window, n_channels, dt=10): n_samples = (window // dt) +",
"not # need to do r['data'][:r['length']] here. # This simplifies",
"ignore_max_sample_warning=False, max_samples=DEFAULT_MAX_SAMPLES, **kwargs): # Convert raw to records. We may",
"dt dts = np.arange(0, record_duration + dt, dt).astype(np.int) # b)",
"dt, n_samples) # += is paranoid, data in individual channels",
"> max_samples: with np.errstate(divide='ignore', invalid='ignore'): # Downsample. New dt must",
"samples doesn't # cause wraparounds # TODO: amplitude bit shift!",
"dt < r['dt']: raise ValueError(\"Upsampling not yet implemented\") (r_start, r_end),",
"raise IndexError('Despite n_samples = window // dt + 1, our",
"will be downsampled to single points dt = max(record_duration, window",
"# += is paranoid, data in individual channels should not",
"- wv_matrix: (n_samples, n_pmt) array with per-PMT waveform intensity in",
"dts = np.arange(0, record_duration + dt, dt).astype(np.int) # b) divisor",
"allow_sloppy_chunking=True) strax.zero_out_of_bounds(records) return context.records_matrix(run_id=run_id, records=records, time_range=time_range, max_samples=max_samples, ignore_max_sample_warning=ignore_max_sample_warning, **kwargs) @numba.njit",
"PE/ns - times: time labels in seconds (corr. to rows)",
"need to do r['data'][:r['length']] here. # This simplifies downsampling. w",
"# Downsample duration = samples_per_record * r['dt'] assert duration %",
"= 20_000 @straxen.mini_analysis(requires=('records',), warn_beyond_sec=10, default_time_selection='touching') def records_matrix(records, time_range, seconds_range, config,",
"max_samples=DEFAULT_MAX_SAMPLES, ignore_max_sample_warning=False): \"\"\"Return (wv_matrix, times, pms) - wv_matrix: (n_samples, n_pmt)",
"as np import strax import straxen DEFAULT_MAX_SAMPLES = 20_000 @straxen.mini_analysis(requires=('records',),",
"IndexError('Despite n_samples = window // dt + 1, our '",
"records=records, time_range=time_range, max_samples=max_samples, ignore_max_sample_warning=ignore_max_sample_warning, **kwargs) @numba.njit def _records_to_matrix(records, t0, window,",
"window // dt + 1, our ' 'idx is too",
"+= is paranoid, data in individual channels should not overlap",
"integers, so downsampling saturated samples doesn't # cause wraparounds #",
"f\"downsampling to dt = {dt} ns.\") wvm = _records_to_matrix( records,",
"dts[window / dts < max_samples] if len(dts): # Pick lowest",
"# Use 32-bit integers, so downsampling saturated samples doesn't #",
"divisor of record duration dts = dts[record_duration / dts %",
"/ dts < max_samples] if len(dts): # Pick lowest dt",
"data for sample 0 will range from 0-1 in plot",
"wv_matrix: (n_samples, n_pmt) array with per-PMT waveform intensity in PE/ns",
"/ dts % 1 == 0] # c) total samples",
"import straxen DEFAULT_MAX_SAMPLES = 20_000 @straxen.mini_analysis(requires=('records',), warn_beyond_sec=10, default_time_selection='touching') def records_matrix(records,",
"nothing will be plotted anyway dt = 10, 110 record_duration",
"= dts[record_duration / dts % 1 == 0] # c)",
"been zeroed, so we do not # need to do",
"warnings import numba import numpy as np import strax import",
"waveform intensity in PE/ns - times: time labels in seconds",
"= time_range[1] - time_range[0] if window / dt > max_samples:",
"dt conspire to exceed this, waveforms will be downsampled. :param",
"(np.arange(wvm.shape[0] + 1) * dt / int(1e9) + seconds_range[0]) ys",
"the range due to missing zeroth fragments records = strax.raw_to_records(raw_records)",
"criteria dt = dts.min() else: # Records will be downsampled",
"of record duration dts = dts[record_duration / dts % 1",
"?? w = w.reshape(duration // dt, -1).sum(axis=1).astype(np.int32) elif dt <",
"warn_beyond_sec=3e-3, default_time_selection='touching') def raw_records_matrix(context, run_id, raw_records, time_range, ignore_max_sample_warning=False, max_samples=DEFAULT_MAX_SAMPLES, **kwargs):",
"Downsample to single sample -> store area idx = (r['time']",
"110 record_duration = samples_per_record * dt window = time_range[1] -",
"wraparounds # TODO: amplitude bit shift! y = np.zeros((n_samples, n_channels),",
"n_samples) # += is paranoid, data in individual channels should",
"import numba import numpy as np import strax import straxen",
"< r['dt']: raise ValueError(\"Upsampling not yet implemented\") (r_start, r_end), (y_start,",
"duration % dt == 0, \"Cannot downsample fractionally\" # .astype",
"np.zeros((n_samples, n_channels), dtype=np.int32) if not len(records): return y samples_per_record =",
"strax.raw_to_records(raw_records) strax.baseline(records, allow_sloppy_chunking=True) strax.zero_out_of_bounds(records) return context.records_matrix(run_id=run_id, records=records, time_range=time_range, max_samples=max_samples, ignore_max_sample_warning=ignore_max_sample_warning,",
"dt > max_samples: with np.errstate(divide='ignore', invalid='ignore'): # Downsample. New dt",
"not yet implemented\") (r_start, r_end), (y_start, y_end) = strax.overlap_indices( r['time']",
"return y samples_per_record = len(records[0]['data']) for r in records: if",
"= {dt} ns.\") wvm = _records_to_matrix( records, t0=time_range[0], n_channels=config['n_tpc_pmts'], dt=dt,",
"len(w), t0 // dt, n_samples) # += is paranoid, data",
"ys = st.records_matrix(run_id, seconds_range=(1., 1.00001)) plt.pcolormesh(ts, ys, wvm.T, norm=matplotlib.colors.LogNorm()) plt.colorbar(label='Intensity",
"(r_start, r_end), (y_start, y_end) = strax.overlap_indices( r['time'] // dt, len(w),",
"to single points dt = max(record_duration, window // max_samples) if",
"correctly # at the start of the range due to",
"ignore_max_sample_warning=ignore_max_sample_warning, **kwargs) @numba.njit def _records_to_matrix(records, t0, window, n_channels, dt=10): n_samples",
"Use 32-bit integers, so downsampling saturated samples doesn't # cause",
"that satisfies criteria dt = dts.min() else: # Records will",
"records_matrix(records, time_range, seconds_range, config, to_pe, max_samples=DEFAULT_MAX_SAMPLES, ignore_max_sample_warning=False): \"\"\"Return (wv_matrix, times,",
"samples_per_record = len(records[0]['data']) for r in records: if r['channel'] >",
"is paranoid, data in individual channels should not overlap #",
"t0=time_range[0], n_channels=config['n_tpc_pmts'], dt=dt, window=window) wvm = wvm.astype(np.float32) * to_pe.reshape(1, -1)",
"plt.pcolormesh(ts, ys, wvm.T, norm=matplotlib.colors.LogNorm()) plt.colorbar(label='Intensity [PE / ns]') \"\"\" if",
"dt = 10, 110 record_duration = samples_per_record * dt window",
"a) multiple of old dt dts = np.arange(0, record_duration +",
"wvm, ts, ys = st.records_matrix(run_id, seconds_range=(1., 1.00001)) plt.pcolormesh(ts, ys, wvm.T,",
"10, 110 record_duration = samples_per_record * dt window = time_range[1]",
"happens. Example: wvm, ts, ys = st.records_matrix(run_id, seconds_range=(1., 1.00001)) plt.pcolormesh(ts,",
"would exceed max_samples {max_samples}, \" f\"downsampling to dt = {dt}",
"dt / int(1e9) + seconds_range[0]) ys = np.arange(wvm.shape[1] + 1)",
"r in records: if r['channel'] > n_channels: continue if dt",
"simplifies downsampling. w = r['data'].astype(np.int32) if dt > r['dt']: #",
"continue # Assume out-of-bounds data has been zeroed, so we",
"+ seconds_range[0]) ys = np.arange(wvm.shape[1] + 1) return wvm, ts,",
"1, so data for sample 0 will range from 0-1",
"range due to missing zeroth fragments records = strax.raw_to_records(raw_records) strax.baseline(records,",
"= 10, 110 record_duration = samples_per_record * dt window =",
"here keeps numba happy ... ?? w = w.reshape(duration //",
"time_range=time_range, max_samples=max_samples, ignore_max_sample_warning=ignore_max_sample_warning, **kwargs) @numba.njit def _records_to_matrix(records, t0, window, n_channels,",
"# Downsample to single sample -> store area idx =",
"b) divisor of record duration dts = dts[record_duration / dts",
"= wvm.astype(np.float32) * to_pe.reshape(1, -1) / dt # Note +",
"numbers (corr. to columns) Both times and pmts have one",
"len(records): return y samples_per_record = len(records[0]['data']) for r in records:",
"return wvm, ts, ys @straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=3e-3, default_time_selection='touching') def raw_records_matrix(context, run_id,",
"wvm, ts, ys @straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=3e-3, default_time_selection='touching') def raw_records_matrix(context, run_id, raw_records,",
"times, pms) - wv_matrix: (n_samples, n_pmt) array with per-PMT waveform",
"will range from 0-1 in plot ts = (np.arange(wvm.shape[0] +",
"plt.colorbar(label='Intensity [PE / ns]') \"\"\" if len(records): dt = records[0]['dt']",
"# Records will be downsampled to single points dt =",
"records: if r['channel'] > n_channels: continue if dt >= samples_per_record",
"dts.min() else: # Records will be downsampled to single points",
"(window // dt) + 1 # Use 32-bit integers, so",
"be plotted anyway dt = 10, 110 record_duration = samples_per_record",
"(corr. to columns) Both times and pmts have one extra",
"// dt, n_samples) # += is paranoid, data in individual",
"not matter, nothing will be plotted anyway dt = 10,",
"def _records_to_matrix(records, t0, window, n_channels, dt=10): n_samples = (window //",
"so downsampling saturated samples doesn't # cause wraparounds # TODO:",
"/ dt # Note + 1, so data for sample",
"fragments records = strax.raw_to_records(raw_records) strax.baseline(records, allow_sloppy_chunking=True) strax.zero_out_of_bounds(records) return context.records_matrix(run_id=run_id, records=records,",
"if dt > r['dt']: # Downsample duration = samples_per_record *",
"if r['channel'] > n_channels: continue if dt >= samples_per_record *",
"r['data'].astype(np.int32) if dt > r['dt']: # Downsample duration = samples_per_record",
"single points dt = max(record_duration, window // max_samples) if not",
"dtype=np.int32) if not len(records): return y samples_per_record = len(records[0]['data']) for",
"32-bit integers, so downsampling saturated samples doesn't # cause wraparounds",
"yet implemented\") (r_start, r_end), (y_start, y_end) = strax.overlap_indices( r['time'] //",
"numba happy ... ?? w = w.reshape(duration // dt, -1).sum(axis=1).astype(np.int32)",
"time_range[0] if window / dt > max_samples: with np.errstate(divide='ignore', invalid='ignore'):",
"len(records): dt = records[0]['dt'] samples_per_record = len(records[0]['data']) else: # Defaults",
"this happens. Example: wvm, ts, ys = st.records_matrix(run_id, seconds_range=(1., 1.00001))",
"default_time_selection='touching') def records_matrix(records, time_range, seconds_range, config, to_pe, max_samples=DEFAULT_MAX_SAMPLES, ignore_max_sample_warning=False): \"\"\"Return",
"1.00001)) plt.pcolormesh(ts, ys, wvm.T, norm=matplotlib.colors.LogNorm()) plt.colorbar(label='Intensity [PE / ns]') \"\"\"",
"old dt dts = np.arange(0, record_duration + dt, dt).astype(np.int) #",
"ValueError(\"Upsampling not yet implemented\") (r_start, r_end), (y_start, y_end) = strax.overlap_indices(",
"be # a) multiple of old dt dts = np.arange(0,",
"dt, -1).sum(axis=1).astype(np.int32) elif dt < r['dt']: raise ValueError(\"Upsampling not yet",
"waveforms will be downsampled. :param ignore_max_sample_warning: If True, suppress warning",
"If True, suppress warning when this happens. Example: wvm, ts,",
"do not # need to do r['data'][:r['length']] here. # This",
"n_channels: continue if dt >= samples_per_record * r['dt']: # Downsample",
"r['channel'] > n_channels: continue if dt >= samples_per_record * r['dt']:",
"pmts have one extra element. :param max_samples: Maximum number of",
"records[0]['dt'] samples_per_record = len(records[0]['data']) else: # Defaults here do not",
"numba import numpy as np import strax import straxen DEFAULT_MAX_SAMPLES",
"-1).sum(axis=1).astype(np.int32) elif dt < r['dt']: raise ValueError(\"Upsampling not yet implemented\")",
"import strax import straxen DEFAULT_MAX_SAMPLES = 20_000 @straxen.mini_analysis(requires=('records',), warn_beyond_sec=10, default_time_selection='touching')",
"PMT numbers (corr. to columns) Both times and pmts have",
"def records_matrix(records, time_range, seconds_range, config, to_pe, max_samples=DEFAULT_MAX_SAMPLES, ignore_max_sample_warning=False): \"\"\"Return (wv_matrix,",
"Both times and pmts have one extra element. :param max_samples:",
"{dt} ns.\") wvm = _records_to_matrix( records, t0=time_range[0], n_channels=config['n_tpc_pmts'], dt=dt, window=window)",
"matter, nothing will be plotted anyway dt = 10, 110",
"high?!') y[idx, r['channel']] += r['area'] continue # Assume out-of-bounds data",
"/ int(1e9) + seconds_range[0]) ys = np.arange(wvm.shape[1] + 1) return",
"return context.records_matrix(run_id=run_id, records=records, time_range=time_range, max_samples=max_samples, ignore_max_sample_warning=ignore_max_sample_warning, **kwargs) @numba.njit def _records_to_matrix(records,",
"dt=dt, window=window) wvm = wvm.astype(np.float32) * to_pe.reshape(1, -1) / dt",
"+= r['area'] continue # Assume out-of-bounds data has been zeroed,",
"# at the start of the range due to missing",
"+ 1 # Use 32-bit integers, so downsampling saturated samples",
"with per-PMT waveform intensity in PE/ns - times: time labels",
"n_channels), dtype=np.int32) if not len(records): return y samples_per_record = len(records[0]['data'])",
"element. :param max_samples: Maximum number of time samples. If window",
"np.errstate(divide='ignore', invalid='ignore'): # Downsample. New dt must be # a)",
">= samples_per_record * r['dt']: # Downsample to single sample ->",
"strax.baseline(records, allow_sloppy_chunking=True) strax.zero_out_of_bounds(records) return context.records_matrix(run_id=run_id, records=records, time_range=time_range, max_samples=max_samples, ignore_max_sample_warning=ignore_max_sample_warning, **kwargs)",
"cause wraparounds # TODO: amplitude bit shift! y = np.zeros((n_samples,",
"for r in records: if r['channel'] > n_channels: continue if",
"amplitude bit shift! y = np.zeros((n_samples, n_channels), dtype=np.int32) if not",
"points dt = max(record_duration, window // max_samples) if not ignore_max_sample_warning:",
"@straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=3e-3, default_time_selection='touching') def raw_records_matrix(context, run_id, raw_records, time_range, ignore_max_sample_warning=False, max_samples=DEFAULT_MAX_SAMPLES,",
"so we do not # need to do r['data'][:r['length']] here.",
"not overlap # but... https://github.com/AxFoundation/strax/issues/119 y[y_start:y_end, r['channel']] += w[r_start:r_end] return",
"DEFAULT_MAX_SAMPLES = 20_000 @straxen.mini_analysis(requires=('records',), warn_beyond_sec=10, default_time_selection='touching') def records_matrix(records, time_range, seconds_range,",
"+ 1, so data for sample 0 will range from",
":param max_samples: Maximum number of time samples. If window and",
"wvm.astype(np.float32) * to_pe.reshape(1, -1) / dt # Note + 1,",
"samples_per_record * r['dt'] assert duration % dt == 0, \"Cannot",
"in seconds (corr. to rows) - pmts: PMT numbers (corr.",
"duration dts = dts[record_duration / dts % 1 == 0]",
"This simplifies downsampling. w = r['data'].astype(np.int32) if dt > r['dt']:",
"conspire to exceed this, waveforms will be downsampled. :param ignore_max_sample_warning:",
"dts < max_samples] if len(dts): # Pick lowest dt that",
"continue if dt >= samples_per_record * r['dt']: # Downsample to",
"to missing zeroth fragments records = strax.raw_to_records(raw_records) strax.baseline(records, allow_sloppy_chunking=True) strax.zero_out_of_bounds(records)",
"r['dt'] assert duration % dt == 0, \"Cannot downsample fractionally\"",
"per-PMT waveform intensity in PE/ns - times: time labels in",
"-> store area idx = (r['time'] - t0) // dt",
".astype here keeps numba happy ... ?? w = w.reshape(duration",
"= strax.raw_to_records(raw_records) strax.baseline(records, allow_sloppy_chunking=True) strax.zero_out_of_bounds(records) return context.records_matrix(run_id=run_id, records=records, time_range=time_range, max_samples=max_samples,",
"0 will range from 0-1 in plot ts = (np.arange(wvm.shape[0]",
"n_samples = (window // dt) + 1 # Use 32-bit",
"overlap # but... https://github.com/AxFoundation/strax/issues/119 y[y_start:y_end, r['channel']] += w[r_start:r_end] return y",
"{max_samples}, \" f\"downsampling to dt = {dt} ns.\") wvm =",
"We may not be able to baseline correctly # at",
"may not be able to baseline correctly # at the",
"elif dt < r['dt']: raise ValueError(\"Upsampling not yet implemented\") (r_start,",
"to rows) - pmts: PMT numbers (corr. to columns) Both",
"strax.zero_out_of_bounds(records) return context.records_matrix(run_id=run_id, records=records, time_range=time_range, max_samples=max_samples, ignore_max_sample_warning=ignore_max_sample_warning, **kwargs) @numba.njit def",
"implemented\") (r_start, r_end), (y_start, y_end) = strax.overlap_indices( r['time'] // dt,",
"ns]') \"\"\" if len(records): dt = records[0]['dt'] samples_per_record = len(records[0]['data'])",
"-1) / dt # Note + 1, so data for",
"be downsampled to single points dt = max(record_duration, window //",
"= len(records[0]['data']) else: # Defaults here do not matter, nothing",
"print(len(y), idx) raise IndexError('Despite n_samples = window // dt +",
"saturated samples doesn't # cause wraparounds # TODO: amplitude bit",
"20_000 @straxen.mini_analysis(requires=('records',), warn_beyond_sec=10, default_time_selection='touching') def records_matrix(records, time_range, seconds_range, config, to_pe,",
"len(records[0]['data']) for r in records: if r['channel'] > n_channels: continue",
"c) total samples < max_samples dts = dts[window / dts",
"1) return wvm, ts, ys @straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=3e-3, default_time_selection='touching') def raw_records_matrix(context,",
"seconds_range, config, to_pe, max_samples=DEFAULT_MAX_SAMPLES, ignore_max_sample_warning=False): \"\"\"Return (wv_matrix, times, pms) -",
"max_samples dts = dts[window / dts < max_samples] if len(dts):",
"plot ts = (np.arange(wvm.shape[0] + 1) * dt / int(1e9)",
"else: # Records will be downsampled to single points dt",
"zeroth fragments records = strax.raw_to_records(raw_records) strax.baseline(records, allow_sloppy_chunking=True) strax.zero_out_of_bounds(records) return context.records_matrix(run_id=run_id,",
"if len(records): dt = records[0]['dt'] samples_per_record = len(records[0]['data']) else: #",
"records, t0=time_range[0], n_channels=config['n_tpc_pmts'], dt=dt, window=window) wvm = wvm.astype(np.float32) * to_pe.reshape(1,",
"if idx >= len(y): print(len(y), idx) raise IndexError('Despite n_samples =",
"do not matter, nothing will be plotted anyway dt =",
"== 0, \"Cannot downsample fractionally\" # .astype here keeps numba",
"+ 1, our ' 'idx is too high?!') y[idx, r['channel']]",
"dt, dt).astype(np.int) # b) divisor of record duration dts =",
"seconds (corr. to rows) - pmts: PMT numbers (corr. to",
"dt == 0, \"Cannot downsample fractionally\" # .astype here keeps",
"\"\"\"Return (wv_matrix, times, pms) - wv_matrix: (n_samples, n_pmt) array with",
"< max_samples] if len(dts): # Pick lowest dt that satisfies",
"wvm.T, norm=matplotlib.colors.LogNorm()) plt.colorbar(label='Intensity [PE / ns]') \"\"\" if len(records): dt",
"ys, wvm.T, norm=matplotlib.colors.LogNorm()) plt.colorbar(label='Intensity [PE / ns]') \"\"\" if len(records):",
"of time samples. If window and dt conspire to exceed",
"of the range due to missing zeroth fragments records =",
"has been zeroed, so we do not # need to",
"to dt = {dt} ns.\") wvm = _records_to_matrix( records, t0=time_range[0],",
"this, waveforms will be downsampled. :param ignore_max_sample_warning: If True, suppress",
"Maximum number of time samples. If window and dt conspire",
"raw to records. We may not be able to baseline",
"= strax.overlap_indices( r['time'] // dt, len(w), t0 // dt, n_samples)",
"**kwargs): # Convert raw to records. We may not be",
"samples. If window and dt conspire to exceed this, waveforms",
"be able to baseline correctly # at the start of",
"r['dt']: # Downsample to single sample -> store area idx",
"* r['dt']: # Downsample to single sample -> store area",
"* dt / int(1e9) + seconds_range[0]) ys = np.arange(wvm.shape[1] +",
"downsampled. :param ignore_max_sample_warning: If True, suppress warning when this happens.",
"assert duration % dt == 0, \"Cannot downsample fractionally\" #",
"# This simplifies downsampling. w = r['data'].astype(np.int32) if dt >",
"\"\"\" if len(records): dt = records[0]['dt'] samples_per_record = len(records[0]['data']) else:",
"anyway dt = 10, 110 record_duration = samples_per_record * dt",
"New dt must be # a) multiple of old dt",
"else: # Defaults here do not matter, nothing will be",
"len(dts): # Pick lowest dt that satisfies criteria dt =",
"_records_to_matrix( records, t0=time_range[0], n_channels=config['n_tpc_pmts'], dt=dt, window=window) wvm = wvm.astype(np.float32) *",
"// dt if idx >= len(y): print(len(y), idx) raise IndexError('Despite",
"r['data'][:r['length']] here. # This simplifies downsampling. w = r['data'].astype(np.int32) if",
"raise ValueError(\"Upsampling not yet implemented\") (r_start, r_end), (y_start, y_end) =",
"def raw_records_matrix(context, run_id, raw_records, time_range, ignore_max_sample_warning=False, max_samples=DEFAULT_MAX_SAMPLES, **kwargs): # Convert",
"plotted anyway dt = 10, 110 record_duration = samples_per_record *",
"from 0-1 in plot ts = (np.arange(wvm.shape[0] + 1) *",
"record_duration + dt, dt).astype(np.int) # b) divisor of record duration",
"\"Cannot downsample fractionally\" # .astype here keeps numba happy ...",
"max_samples=max_samples, ignore_max_sample_warning=ignore_max_sample_warning, **kwargs) @numba.njit def _records_to_matrix(records, t0, window, n_channels, dt=10):",
"y samples_per_record = len(records[0]['data']) for r in records: if r['channel']",
"= r['data'].astype(np.int32) if dt > r['dt']: # Downsample duration =",
"records = strax.raw_to_records(raw_records) strax.baseline(records, allow_sloppy_chunking=True) strax.zero_out_of_bounds(records) return context.records_matrix(run_id=run_id, records=records, time_range=time_range,",
"dt # Note + 1, so data for sample 0",
"our ' 'idx is too high?!') y[idx, r['channel']] += r['area']",
"number of time samples. If window and dt conspire to",
"\" f\"downsampling to dt = {dt} ns.\") wvm = _records_to_matrix(",
"array with per-PMT waveform intensity in PE/ns - times: time",
"' 'idx is too high?!') y[idx, r['channel']] += r['area'] continue",
"data has been zeroed, so we do not # need",
"% 1 == 0] # c) total samples < max_samples",
"columns) Both times and pmts have one extra element. :param",
"area idx = (r['time'] - t0) // dt if idx",
"np.arange(0, record_duration + dt, dt).astype(np.int) # b) divisor of record",
"# .astype here keeps numba happy ... ?? w =",
"// max_samples) if not ignore_max_sample_warning: warnings.warn(f\"Matrix would exceed max_samples {max_samples},",
"zeroed, so we do not # need to do r['data'][:r['length']]",
"config, to_pe, max_samples=DEFAULT_MAX_SAMPLES, ignore_max_sample_warning=False): \"\"\"Return (wv_matrix, times, pms) - wv_matrix:",
"will be downsampled. :param ignore_max_sample_warning: If True, suppress warning when",
"== 0] # c) total samples < max_samples dts =",
"duration = samples_per_record * r['dt'] assert duration % dt ==",
"= w.reshape(duration // dt, -1).sum(axis=1).astype(np.int32) elif dt < r['dt']: raise",
"(n_samples, n_pmt) array with per-PMT waveform intensity in PE/ns -",
"max_samples) if not ignore_max_sample_warning: warnings.warn(f\"Matrix would exceed max_samples {max_samples}, \"",
"ys @straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=3e-3, default_time_selection='touching') def raw_records_matrix(context, run_id, raw_records, time_range, ignore_max_sample_warning=False,",
"to columns) Both times and pmts have one extra element.",
"must be # a) multiple of old dt dts =",
"warn_beyond_sec=10, default_time_selection='touching') def records_matrix(records, time_range, seconds_range, config, to_pe, max_samples=DEFAULT_MAX_SAMPLES, ignore_max_sample_warning=False):",
"(corr. to rows) - pmts: PMT numbers (corr. to columns)",
"/ dt > max_samples: with np.errstate(divide='ignore', invalid='ignore'): # Downsample. New",
"* to_pe.reshape(1, -1) / dt # Note + 1, so",
"ns.\") wvm = _records_to_matrix( records, t0=time_range[0], n_channels=config['n_tpc_pmts'], dt=dt, window=window) wvm",
"default_time_selection='touching') def raw_records_matrix(context, run_id, raw_records, time_range, ignore_max_sample_warning=False, max_samples=DEFAULT_MAX_SAMPLES, **kwargs): #",
"dt must be # a) multiple of old dt dts",
"Pick lowest dt that satisfies criteria dt = dts.min() else:",
"individual channels should not overlap # but... https://github.com/AxFoundation/strax/issues/119 y[y_start:y_end, r['channel']]",
"multiple of old dt dts = np.arange(0, record_duration + dt,",
"r['channel']] += r['area'] continue # Assume out-of-bounds data has been",
"window and dt conspire to exceed this, waveforms will be",
"# Pick lowest dt that satisfies criteria dt = dts.min()",
"not ignore_max_sample_warning: warnings.warn(f\"Matrix would exceed max_samples {max_samples}, \" f\"downsampling to",
"= len(records[0]['data']) for r in records: if r['channel'] > n_channels:",
"= dts[window / dts < max_samples] if len(dts): # Pick",
"// dt + 1, our ' 'idx is too high?!')",
"// dt, len(w), t0 // dt, n_samples) # += is",
"here. # This simplifies downsampling. w = r['data'].astype(np.int32) if dt",
"single sample -> store area idx = (r['time'] - t0)",
"ignore_max_sample_warning: If True, suppress warning when this happens. Example: wvm,",
"... ?? w = w.reshape(duration // dt, -1).sum(axis=1).astype(np.int32) elif dt",
"// dt) + 1 # Use 32-bit integers, so downsampling",
"# Note + 1, so data for sample 0 will",
"doesn't # cause wraparounds # TODO: amplitude bit shift! y",
"1, our ' 'idx is too high?!') y[idx, r['channel']] +=",
"[PE / ns]') \"\"\" if len(records): dt = records[0]['dt'] samples_per_record",
"0-1 in plot ts = (np.arange(wvm.shape[0] + 1) * dt",
"_records_to_matrix(records, t0, window, n_channels, dt=10): n_samples = (window // dt)",
"out-of-bounds data has been zeroed, so we do not #",
"and dt conspire to exceed this, waveforms will be downsampled.",
"// dt, -1).sum(axis=1).astype(np.int32) elif dt < r['dt']: raise ValueError(\"Upsampling not",
"extra element. :param max_samples: Maximum number of time samples. If",
"norm=matplotlib.colors.LogNorm()) plt.colorbar(label='Intensity [PE / ns]') \"\"\" if len(records): dt =",
"= _records_to_matrix( records, t0=time_range[0], n_channels=config['n_tpc_pmts'], dt=dt, window=window) wvm = wvm.astype(np.float32)",
"record_duration = samples_per_record * dt window = time_range[1] - time_range[0]",
"y[idx, r['channel']] += r['area'] continue # Assume out-of-bounds data has",
"to do r['data'][:r['length']] here. # This simplifies downsampling. w =",
"and pmts have one extra element. :param max_samples: Maximum number",
"time_range, seconds_range, config, to_pe, max_samples=DEFAULT_MAX_SAMPLES, ignore_max_sample_warning=False): \"\"\"Return (wv_matrix, times, pms)",
"window = time_range[1] - time_range[0] if window / dt >",
"dt) + 1 # Use 32-bit integers, so downsampling saturated",
"r['area'] continue # Assume out-of-bounds data has been zeroed, so",
"True, suppress warning when this happens. Example: wvm, ts, ys",
"sample -> store area idx = (r['time'] - t0) //",
"w = r['data'].astype(np.int32) if dt > r['dt']: # Downsample duration",
"run_id, raw_records, time_range, ignore_max_sample_warning=False, max_samples=DEFAULT_MAX_SAMPLES, **kwargs): # Convert raw to",
"will be plotted anyway dt = 10, 110 record_duration =",
"= samples_per_record * dt window = time_range[1] - time_range[0] if",
"= np.arange(wvm.shape[1] + 1) return wvm, ts, ys @straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=3e-3,",
"@numba.njit def _records_to_matrix(records, t0, window, n_channels, dt=10): n_samples = (window",
"due to missing zeroth fragments records = strax.raw_to_records(raw_records) strax.baseline(records, allow_sloppy_chunking=True)",
"so data for sample 0 will range from 0-1 in",
"strax import straxen DEFAULT_MAX_SAMPLES = 20_000 @straxen.mini_analysis(requires=('records',), warn_beyond_sec=10, default_time_selection='touching') def",
"records. We may not be able to baseline correctly #",
"len(y): print(len(y), idx) raise IndexError('Despite n_samples = window // dt",
"samples_per_record * r['dt']: # Downsample to single sample -> store",
"n_channels, dt=10): n_samples = (window // dt) + 1 #",
"* r['dt'] assert duration % dt == 0, \"Cannot downsample",
"TODO: amplitude bit shift! y = np.zeros((n_samples, n_channels), dtype=np.int32) if",
"downsampling. w = r['data'].astype(np.int32) if dt > r['dt']: # Downsample",
"(y_start, y_end) = strax.overlap_indices( r['time'] // dt, len(w), t0 //",
"r['dt']: raise ValueError(\"Upsampling not yet implemented\") (r_start, r_end), (y_start, y_end)",
"labels in seconds (corr. to rows) - pmts: PMT numbers",
"to records. We may not be able to baseline correctly",
"data in individual channels should not overlap # but... https://github.com/AxFoundation/strax/issues/119",
"ts, ys = st.records_matrix(run_id, seconds_range=(1., 1.00001)) plt.pcolormesh(ts, ys, wvm.T, norm=matplotlib.colors.LogNorm())",
"dts % 1 == 0] # c) total samples <",
"1 # Use 32-bit integers, so downsampling saturated samples doesn't",
"suppress warning when this happens. Example: wvm, ts, ys =",
"ts, ys @straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=3e-3, default_time_selection='touching') def raw_records_matrix(context, run_id, raw_records, time_range,",
"st.records_matrix(run_id, seconds_range=(1., 1.00001)) plt.pcolormesh(ts, ys, wvm.T, norm=matplotlib.colors.LogNorm()) plt.colorbar(label='Intensity [PE /",
"r_end), (y_start, y_end) = strax.overlap_indices( r['time'] // dt, len(w), t0",
"exceed this, waveforms will be downsampled. :param ignore_max_sample_warning: If True,",
"total samples < max_samples dts = dts[window / dts <",
"start of the range due to missing zeroth fragments records",
"dt = dts.min() else: # Records will be downsampled to",
"lowest dt that satisfies criteria dt = dts.min() else: #",
"idx = (r['time'] - t0) // dt if idx >=",
"if not len(records): return y samples_per_record = len(records[0]['data']) for r",
"0, \"Cannot downsample fractionally\" # .astype here keeps numba happy",
"= st.records_matrix(run_id, seconds_range=(1., 1.00001)) plt.pcolormesh(ts, ys, wvm.T, norm=matplotlib.colors.LogNorm()) plt.colorbar(label='Intensity [PE",
"in individual channels should not overlap # but... https://github.com/AxFoundation/strax/issues/119 y[y_start:y_end,",
"dt > r['dt']: # Downsample duration = samples_per_record * r['dt']",
"# c) total samples < max_samples dts = dts[window /",
"% dt == 0, \"Cannot downsample fractionally\" # .astype here",
"be downsampled. :param ignore_max_sample_warning: If True, suppress warning when this",
"raw_records_matrix(context, run_id, raw_records, time_range, ignore_max_sample_warning=False, max_samples=DEFAULT_MAX_SAMPLES, **kwargs): # Convert raw",
"/ ns]') \"\"\" if len(records): dt = records[0]['dt'] samples_per_record =",
"pms) - wv_matrix: (n_samples, n_pmt) array with per-PMT waveform intensity",
"Example: wvm, ts, ys = st.records_matrix(run_id, seconds_range=(1., 1.00001)) plt.pcolormesh(ts, ys,",
"= records[0]['dt'] samples_per_record = len(records[0]['data']) else: # Defaults here do",
"Downsample. New dt must be # a) multiple of old",
"of old dt dts = np.arange(0, record_duration + dt, dt).astype(np.int)",
"idx) raise IndexError('Despite n_samples = window // dt + 1,",
"range from 0-1 in plot ts = (np.arange(wvm.shape[0] + 1)",
"= np.arange(0, record_duration + dt, dt).astype(np.int) # b) divisor of",
"window // max_samples) if not ignore_max_sample_warning: warnings.warn(f\"Matrix would exceed max_samples",
"# a) multiple of old dt dts = np.arange(0, record_duration",
"If window and dt conspire to exceed this, waveforms will",
"exceed max_samples {max_samples}, \" f\"downsampling to dt = {dt} ns.\")",
"< max_samples dts = dts[window / dts < max_samples] if",
"not len(records): return y samples_per_record = len(records[0]['data']) for r in",
"bit shift! y = np.zeros((n_samples, n_channels), dtype=np.int32) if not len(records):",
"in records: if r['channel'] > n_channels: continue if dt >=",
"straxen DEFAULT_MAX_SAMPLES = 20_000 @straxen.mini_analysis(requires=('records',), warn_beyond_sec=10, default_time_selection='touching') def records_matrix(records, time_range,",
"strax.overlap_indices( r['time'] // dt, len(w), t0 // dt, n_samples) #",
"idx >= len(y): print(len(y), idx) raise IndexError('Despite n_samples = window",
"if len(dts): # Pick lowest dt that satisfies criteria dt",
"keeps numba happy ... ?? w = w.reshape(duration // dt,",
"have one extra element. :param max_samples: Maximum number of time",
"np.arange(wvm.shape[1] + 1) return wvm, ts, ys @straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=3e-3, default_time_selection='touching')",
"dt = records[0]['dt'] samples_per_record = len(records[0]['data']) else: # Defaults here",
"'idx is too high?!') y[idx, r['channel']] += r['area'] continue #",
"warning when this happens. Example: wvm, ts, ys = st.records_matrix(run_id,",
"+ dt, dt).astype(np.int) # b) divisor of record duration dts",
"1 == 0] # c) total samples < max_samples dts",
"ts = (np.arange(wvm.shape[0] + 1) * dt / int(1e9) +",
"# Convert raw to records. We may not be able",
"dt + 1, our ' 'idx is too high?!') y[idx,",
"+ 1) * dt / int(1e9) + seconds_range[0]) ys =",
"intensity in PE/ns - times: time labels in seconds (corr.",
"samples_per_record = len(records[0]['data']) else: # Defaults here do not matter,",
"time labels in seconds (corr. to rows) - pmts: PMT",
"dts = dts[record_duration / dts % 1 == 0] #",
"- time_range[0] if window / dt > max_samples: with np.errstate(divide='ignore',",
"# TODO: amplitude bit shift! y = np.zeros((n_samples, n_channels), dtype=np.int32)",
"dt that satisfies criteria dt = dts.min() else: # Records",
"> n_channels: continue if dt >= samples_per_record * r['dt']: #",
"times and pmts have one extra element. :param max_samples: Maximum",
":param ignore_max_sample_warning: If True, suppress warning when this happens. Example:",
"(wv_matrix, times, pms) - wv_matrix: (n_samples, n_pmt) array with per-PMT",
"to single sample -> store area idx = (r['time'] -",
"downsampled to single points dt = max(record_duration, window // max_samples)",
"warnings.warn(f\"Matrix would exceed max_samples {max_samples}, \" f\"downsampling to dt =",
"fractionally\" # .astype here keeps numba happy ... ?? w",
"1) * dt / int(1e9) + seconds_range[0]) ys = np.arange(wvm.shape[1]",
"time samples. If window and dt conspire to exceed this,",
"missing zeroth fragments records = strax.raw_to_records(raw_records) strax.baseline(records, allow_sloppy_chunking=True) strax.zero_out_of_bounds(records) return",
"# b) divisor of record duration dts = dts[record_duration /",
"numpy as np import strax import straxen DEFAULT_MAX_SAMPLES = 20_000",
">= len(y): print(len(y), idx) raise IndexError('Despite n_samples = window //",
"paranoid, data in individual channels should not overlap # but...",
"> r['dt']: # Downsample duration = samples_per_record * r['dt'] assert",
"at the start of the range due to missing zeroth",
"Assume out-of-bounds data has been zeroed, so we do not",
"**kwargs) @numba.njit def _records_to_matrix(records, t0, window, n_channels, dt=10): n_samples =",
"= samples_per_record * r['dt'] assert duration % dt == 0,",
"= max(record_duration, window // max_samples) if not ignore_max_sample_warning: warnings.warn(f\"Matrix would",
"times: time labels in seconds (corr. to rows) - pmts:",
"max_samples=DEFAULT_MAX_SAMPLES, **kwargs): # Convert raw to records. We may not",
"= np.zeros((n_samples, n_channels), dtype=np.int32) if not len(records): return y samples_per_record",
"seconds_range=(1., 1.00001)) plt.pcolormesh(ts, ys, wvm.T, norm=matplotlib.colors.LogNorm()) plt.colorbar(label='Intensity [PE / ns]')",
"import numpy as np import strax import straxen DEFAULT_MAX_SAMPLES =",
"Defaults here do not matter, nothing will be plotted anyway",
"# Downsample. New dt must be # a) multiple of",
"np import strax import straxen DEFAULT_MAX_SAMPLES = 20_000 @straxen.mini_analysis(requires=('records',), warn_beyond_sec=10,",
"for sample 0 will range from 0-1 in plot ts",
"Note + 1, so data for sample 0 will range",
"to baseline correctly # at the start of the range",
"Convert raw to records. We may not be able to",
"downsampling saturated samples doesn't # cause wraparounds # TODO: amplitude",
"dt >= samples_per_record * r['dt']: # Downsample to single sample",
"# Assume out-of-bounds data has been zeroed, so we do",
"samples < max_samples dts = dts[window / dts < max_samples]",
"import warnings import numba import numpy as np import strax",
"- times: time labels in seconds (corr. to rows) -",
"= window // dt + 1, our ' 'idx is",
"do r['data'][:r['length']] here. # This simplifies downsampling. w = r['data'].astype(np.int32)",
"y_end) = strax.overlap_indices( r['time'] // dt, len(w), t0 // dt,",
"when this happens. Example: wvm, ts, ys = st.records_matrix(run_id, seconds_range=(1.,",
"Records will be downsampled to single points dt = max(record_duration,",
"dt = {dt} ns.\") wvm = _records_to_matrix( records, t0=time_range[0], n_channels=config['n_tpc_pmts'],",
"downsample fractionally\" # .astype here keeps numba happy ... ??",
"context.records_matrix(run_id=run_id, records=records, time_range=time_range, max_samples=max_samples, ignore_max_sample_warning=ignore_max_sample_warning, **kwargs) @numba.njit def _records_to_matrix(records, t0,",
"with np.errstate(divide='ignore', invalid='ignore'): # Downsample. New dt must be #",
"baseline correctly # at the start of the range due",
"int(1e9) + seconds_range[0]) ys = np.arange(wvm.shape[1] + 1) return wvm,",
"time_range[1] - time_range[0] if window / dt > max_samples: with",
"satisfies criteria dt = dts.min() else: # Records will be",
"y = np.zeros((n_samples, n_channels), dtype=np.int32) if not len(records): return y",
"dts = dts[window / dts < max_samples] if len(dts): #",
"time_range, ignore_max_sample_warning=False, max_samples=DEFAULT_MAX_SAMPLES, **kwargs): # Convert raw to records. We",
"wvm = _records_to_matrix( records, t0=time_range[0], n_channels=config['n_tpc_pmts'], dt=dt, window=window) wvm =",
"too high?!') y[idx, r['channel']] += r['area'] continue # Assume out-of-bounds",
"r['dt']: # Downsample duration = samples_per_record * r['dt'] assert duration",
"- t0) // dt if idx >= len(y): print(len(y), idx)",
"(r['time'] - t0) // dt if idx >= len(y): print(len(y),",
"store area idx = (r['time'] - t0) // dt if",
"samples_per_record * dt window = time_range[1] - time_range[0] if window",
"- pmts: PMT numbers (corr. to columns) Both times and",
"window, n_channels, dt=10): n_samples = (window // dt) + 1",
"wvm = wvm.astype(np.float32) * to_pe.reshape(1, -1) / dt # Note",
"window=window) wvm = wvm.astype(np.float32) * to_pe.reshape(1, -1) / dt #",
"* dt window = time_range[1] - time_range[0] if window /",
"pmts: PMT numbers (corr. to columns) Both times and pmts",
"= (window // dt) + 1 # Use 32-bit integers,",
"= (r['time'] - t0) // dt if idx >= len(y):",
"dt).astype(np.int) # b) divisor of record duration dts = dts[record_duration",
"one extra element. :param max_samples: Maximum number of time samples.",
"max_samples: Maximum number of time samples. If window and dt",
"record duration dts = dts[record_duration / dts % 1 ==",
"window / dt > max_samples: with np.errstate(divide='ignore', invalid='ignore'): # Downsample.",
"if not ignore_max_sample_warning: warnings.warn(f\"Matrix would exceed max_samples {max_samples}, \" f\"downsampling",
"dt window = time_range[1] - time_range[0] if window / dt",
"+ 1) return wvm, ts, ys @straxen.mini_analysis(requires=('raw_records',), warn_beyond_sec=3e-3, default_time_selection='touching') def",
"n_samples = window // dt + 1, our ' 'idx",
"the start of the range due to missing zeroth fragments",
"r['time'] // dt, len(w), t0 // dt, n_samples) # +=",
"is too high?!') y[idx, r['channel']] += r['area'] continue # Assume",
"to exceed this, waveforms will be downsampled. :param ignore_max_sample_warning: If",
"0] # c) total samples < max_samples dts = dts[window",
"ignore_max_sample_warning: warnings.warn(f\"Matrix would exceed max_samples {max_samples}, \" f\"downsampling to dt",
"invalid='ignore'): # Downsample. New dt must be # a) multiple",
"max_samples] if len(dts): # Pick lowest dt that satisfies criteria",
"= (np.arange(wvm.shape[0] + 1) * dt / int(1e9) + seconds_range[0])",
"seconds_range[0]) ys = np.arange(wvm.shape[1] + 1) return wvm, ts, ys",
"if window / dt > max_samples: with np.errstate(divide='ignore', invalid='ignore'): #",
"Downsample duration = samples_per_record * r['dt'] assert duration % dt",
"here do not matter, nothing will be plotted anyway dt",
"in plot ts = (np.arange(wvm.shape[0] + 1) * dt /",
"t0) // dt if idx >= len(y): print(len(y), idx) raise",
"dt=10): n_samples = (window // dt) + 1 # Use",
"channels should not overlap # but... https://github.com/AxFoundation/strax/issues/119 y[y_start:y_end, r['channel']] +=",
"raw_records, time_range, ignore_max_sample_warning=False, max_samples=DEFAULT_MAX_SAMPLES, **kwargs): # Convert raw to records.",
"in PE/ns - times: time labels in seconds (corr. to",
"sample 0 will range from 0-1 in plot ts =",
"able to baseline correctly # at the start of the",
"# cause wraparounds # TODO: amplitude bit shift! y =",
"t0 // dt, n_samples) # += is paranoid, data in",
"ignore_max_sample_warning=False): \"\"\"Return (wv_matrix, times, pms) - wv_matrix: (n_samples, n_pmt) array",
"dt, len(w), t0 // dt, n_samples) # += is paranoid,",
"n_pmt) array with per-PMT waveform intensity in PE/ns - times:",
"dt if idx >= len(y): print(len(y), idx) raise IndexError('Despite n_samples",
"w.reshape(duration // dt, -1).sum(axis=1).astype(np.int32) elif dt < r['dt']: raise ValueError(\"Upsampling",
"max_samples: with np.errstate(divide='ignore', invalid='ignore'): # Downsample. New dt must be",
"len(records[0]['data']) else: # Defaults here do not matter, nothing will",
"to_pe.reshape(1, -1) / dt # Note + 1, so data",
"dt = max(record_duration, window // max_samples) if not ignore_max_sample_warning: warnings.warn(f\"Matrix",
"max(record_duration, window // max_samples) if not ignore_max_sample_warning: warnings.warn(f\"Matrix would exceed",
"= dts.min() else: # Records will be downsampled to single",
"# Defaults here do not matter, nothing will be plotted",
"dts[record_duration / dts % 1 == 0] # c) total",
"n_channels=config['n_tpc_pmts'], dt=dt, window=window) wvm = wvm.astype(np.float32) * to_pe.reshape(1, -1) /",
"shift! y = np.zeros((n_samples, n_channels), dtype=np.int32) if not len(records): return"
] |
[
"('signing_key', 'verifying_key')) def generate_keypair(): \"\"\"Generates a cryptographic key pair. Returns:",
"CryptoKeypair = namedtuple('CryptoKeypair', ('signing_key', 'verifying_key')) def generate_keypair(): \"\"\"Generates a cryptographic",
"def generate_keypair(): \"\"\"Generates a cryptographic key pair. Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`: A",
"from cryptoconditions import crypto CryptoKeypair = namedtuple('CryptoKeypair', ('signing_key', 'verifying_key')) def",
"import namedtuple from cryptoconditions import crypto CryptoKeypair = namedtuple('CryptoKeypair', ('signing_key',",
"namedtuple from cryptoconditions import crypto CryptoKeypair = namedtuple('CryptoKeypair', ('signing_key', 'verifying_key'))",
"crypto CryptoKeypair = namedtuple('CryptoKeypair', ('signing_key', 'verifying_key')) def generate_keypair(): \"\"\"Generates a",
":class:`~bigchaindb_driver.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`. \"\"\"",
"cryptoconditions import crypto CryptoKeypair = namedtuple('CryptoKeypair', ('signing_key', 'verifying_key')) def generate_keypair():",
"a cryptographic key pair. Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named",
"\"\"\"Generates a cryptographic key pair. Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with",
"generate_keypair(): \"\"\"Generates a cryptographic key pair. Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`: A :obj:`collections.namedtuple`",
"namedtuple('CryptoKeypair', ('signing_key', 'verifying_key')) def generate_keypair(): \"\"\"Generates a cryptographic key pair.",
"key pair. Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key`",
"= namedtuple('CryptoKeypair', ('signing_key', 'verifying_key')) def generate_keypair(): \"\"\"Generates a cryptographic key",
"and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`. \"\"\" return CryptoKeypair( *(k.decode() for k in crypto.ed25519_generate_key_pair()))",
"with named fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`. \"\"\" return CryptoKeypair( *(k.decode()",
"import crypto CryptoKeypair = namedtuple('CryptoKeypair', ('signing_key', 'verifying_key')) def generate_keypair(): \"\"\"Generates",
"fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`. \"\"\" return CryptoKeypair( *(k.decode() for k",
"named fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`. \"\"\" return CryptoKeypair( *(k.decode() for",
":obj:`collections.namedtuple` with named fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`. \"\"\" return CryptoKeypair(",
"cryptographic key pair. Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields",
"'verifying_key')) def generate_keypair(): \"\"\"Generates a cryptographic key pair. Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`:",
":attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`. \"\"\" return CryptoKeypair( *(k.decode() for k in",
"pair. Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and",
"A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`. \"\"\" return",
"Returns: :class:`~bigchaindb_driver.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb_driver.crypto.CryptoKeypair.signing_key` and :attr:`~bigchaindb_driver.crypto.CryptoKeypair.verifying_key`.",
"collections import namedtuple from cryptoconditions import crypto CryptoKeypair = namedtuple('CryptoKeypair',",
"from collections import namedtuple from cryptoconditions import crypto CryptoKeypair ="
] |
[
"of new items. * ``removed``: A list of items that",
"webapi_check_local_site from reviewboard.webapi.mixins import MarkdownFieldsMixin from reviewboard.webapi.resources import resources class",
"get_list(self, *args, **kwargs): \"\"\"Returns a list of changes made on",
"* ``old``: A list of old items. * ``new``: A",
"public review request. A change includes, optionally, text entered by",
"updated. \"\"\" added_in = '1.6' model = ChangeDescription name =",
"* ``new``: The new caption. * ``screenshot``: The screenshot that",
"are in ``fields_changed``. The keys are the names of the",
"'fields_changed': { 'type': dict, 'description': 'The fields that were changed.',",
"for the text field.', 'added_in': '2.0', }, 'timestamp': { 'type':",
"field_cls = get_review_request_field(field_name) field = field_cls(review_request) fields_changed[field.field_id] = field.serialize_change_entry(obj) return",
"get(self, *args, **kwargs): \"\"\"Returns the information on a change to",
"reviewboard.reviews.fields import get_review_request_field from reviewboard.webapi.base import WebAPIResource from reviewboard.webapi.decorators import",
"details on that particular change to the field. For ``summary``,",
"any. * ``added``: A list of items that were added,",
"date and time that the change was made ' '(in",
"``target_groups`` fields: * ``old``: A list of old items. *",
"= '1.6' model = ChangeDescription name = 'change' fields =",
"fields, the following detail keys will be available: * ``old``:",
"field_name, data in six.iteritems(obj.fields_changed): field_cls = get_review_request_field(field_name) field = field_cls(review_request)",
"the field. For ``summary``, ``description``, ``testing_done`` and ``branch`` fields, the",
"mimetype_list_resource_name = 'review-request-changes' mimetype_item_resource_name = 'review-request-change' def serialize_fields_changed_field(self, obj, **kwargs):",
"list of old bugs. * ``new``: A list of new",
"six from djblets.util.decorators import augment_method_from from reviewboard.changedescs.models import ChangeDescription from",
"HH:MM:SS format).', }, } uri_object_key = 'change_id' model_parent_key = 'review_request'",
"* ``removed``: A list of bugs that were removed, if",
"For ``diff`` fields: * ``added``: The diff that was added.",
"numeric ID of the change description.', }, 'fields_changed': { 'type':",
"``description``, ``testing_done`` and ``branch`` fields, the following detail keys will",
"value of the field. For ``diff`` fields: * ``added``: The",
"from reviewboard.webapi.mixins import MarkdownFieldsMixin from reviewboard.webapi.resources import resources class ChangeResource(MarkdownFieldsMixin,",
"includes a list of fields that were changed on the",
"= 'review_request' allowed_methods = ('GET',) mimetype_list_resource_name = 'review-request-changes' mimetype_item_resource_name =",
"information on a change to a review request.\"\"\" pass change_resource",
"reviewboard.webapi.base import WebAPIResource from reviewboard.webapi.decorators import webapi_check_local_site from reviewboard.webapi.mixins import",
"fields = { 'id': { 'type': int, 'description': 'The numeric",
"mimetype_item_resource_name = 'review-request-change' def serialize_fields_changed_field(self, obj, **kwargs): review_request = obj.review_request.get()",
"particular change to the field. For ``summary``, ``description``, ``testing_done`` and",
"= 'change_id' model_parent_key = 'review_request' allowed_methods = ('GET',) mimetype_list_resource_name =",
"information on a change made to a public review request.",
"are details on that particular change to the field. For",
"old caption. * ``new``: The new caption. * ``screenshot``: The",
"= field_cls(review_request) fields_changed[field.field_id] = field.serialize_change_entry(obj) return fields_changed def has_access_permissions(self, request,",
"``branch`` fields, the following detail keys will be available: *",
"were removed, if any. * ``added``: A list of bugs",
"fields_changed = {} for field_name, data in six.iteritems(obj.fields_changed): field_cls =",
"**kwargs): \"\"\"Returns a list of changes made on a review",
"{} for field_name, data in six.iteritems(obj.fields_changed): field_cls = get_review_request_field(field_name) field",
"the information on a change to a review request.\"\"\" pass",
"written by the ' 'submitter.', 'supports_text_types': True, }, 'text_type': {",
"get_review_request_field from reviewboard.webapi.base import WebAPIResource from reviewboard.webapi.decorators import webapi_check_local_site from",
"def serialize_fields_changed_field(self, obj, **kwargs): review_request = obj.review_request.get() fields_changed = {}",
"serialize_fields_changed_field(self, obj, **kwargs): review_request = obj.review_request.get() fields_changed = {} for",
"return fields_changed def has_access_permissions(self, request, obj, *args, **kwargs): return obj.review_request.get().is_accessible_by(request.user)",
"was made ' '(in YYYY-MM-DD HH:MM:SS format).', }, } uri_object_key",
"list of changes made on a review request.\"\"\" pass @webapi_check_local_site",
"format).', }, } uri_object_key = 'change_id' model_parent_key = 'review_request' allowed_methods",
"``summary``, ``description``, ``testing_done`` and ``branch`` fields, the following detail keys",
"are the names of the fields, and the values are",
"reviewboard.changedescs.models import ChangeDescription from reviewboard.reviews.fields import get_review_request_field from reviewboard.webapi.base import",
"'type': dict, 'description': 'The fields that were changed.', }, 'text':",
"dict, 'description': 'The fields that were changed.', }, 'text': {",
"MarkdownFieldsMixin from reviewboard.webapi.resources import resources class ChangeResource(MarkdownFieldsMixin, WebAPIResource): \"\"\"Provides information",
"list of new bugs. * ``removed``: A list of bugs",
"items that were added, if any. For ``screenshot_captions`` and ``file_captions``",
"'text': { 'type': six.text_type, 'description': 'The description of the change",
"a change made to a public review request. A change",
"The list of fields changed are in ``fields_changed``. The keys",
"made on a review request.\"\"\" pass @webapi_check_local_site @augment_method_from(WebAPIResource) def get(self,",
"six.text_type, 'description': 'The date and time that the change was",
"A list of old items. * ``new``: A list of",
"and ``branch`` fields, the following detail keys will be available:",
"}, } uri_object_key = 'change_id' model_parent_key = 'review_request' allowed_methods =",
"**kwargs) return review_request.changedescs.filter(public=True) @webapi_check_local_site @augment_method_from(WebAPIResource) def get_list(self, *args, **kwargs): \"\"\"Returns",
"review request. The list of fields changed are in ``fields_changed``.",
"also includes a list of fields that were changed on",
"request.\"\"\" pass @webapi_check_local_site @augment_method_from(WebAPIResource) def get(self, *args, **kwargs): \"\"\"Returns the",
"of bugs that were removed, if any. * ``added``: A",
"of items that were added, if any. For ``screenshot_captions`` and",
"value of the field. * ``new``: The new value of",
"and time that the change was made ' '(in YYYY-MM-DD",
"} uri_object_key = 'change_id' model_parent_key = 'review_request' allowed_methods = ('GET',)",
"if any. * ``added``: A list of items that were",
"describing the change, and also includes a list of fields",
"* ``added``: A list of items that were added, if",
"pass @webapi_check_local_site @augment_method_from(WebAPIResource) def get(self, *args, **kwargs): \"\"\"Returns the information",
"for field_name, data in six.iteritems(obj.fields_changed): field_cls = get_review_request_field(field_name) field =",
"keys are the names of the fields, and the values",
"change was made ' '(in YYYY-MM-DD HH:MM:SS format).', }, }",
"@augment_method_from(WebAPIResource) def get_list(self, *args, **kwargs): \"\"\"Returns a list of changes",
"made ' '(in YYYY-MM-DD HH:MM:SS format).', }, } uri_object_key =",
"django.utils import six from djblets.util.decorators import augment_method_from from reviewboard.changedescs.models import",
"field = field_cls(review_request) fields_changed[field.field_id] = field.serialize_change_entry(obj) return fields_changed def has_access_permissions(self,",
"review request.\"\"\" pass @webapi_check_local_site @augment_method_from(WebAPIResource) def get(self, *args, **kwargs): \"\"\"Returns",
"from reviewboard.reviews.fields import get_review_request_field from reviewboard.webapi.base import WebAPIResource from reviewboard.webapi.decorators",
"in ``fields_changed``. The keys are the names of the fields,",
"The old value of the field. * ``new``: The new",
"For ``bugs_closed`` fields: * ``old``: A list of old bugs.",
"list of old items. * ``new``: A list of new",
"by the user describing the change, and also includes a",
"review_request.changedescs.filter(public=True) @webapi_check_local_site @augment_method_from(WebAPIResource) def get_list(self, *args, **kwargs): \"\"\"Returns a list",
"``target_people`` and ``target_groups`` fields: * ``old``: A list of old",
"'id': { 'type': int, 'description': 'The numeric ID of the",
"@webapi_check_local_site @augment_method_from(WebAPIResource) def get_list(self, *args, **kwargs): \"\"\"Returns a list of",
"of new bugs. * ``removed``: A list of bugs that",
"ID of the change description.', }, 'fields_changed': { 'type': dict,",
"the following detail keys will be available: * ``old``: The",
"fields: * ``old``: A list of old bugs. * ``new``:",
"list of bugs that were removed, if any. * ``added``:",
"``added``: A list of bugs that were added, if any.",
"* ``new``: A list of new items. * ``removed``: A",
"= {} for field_name, data in six.iteritems(obj.fields_changed): field_cls = get_review_request_field(field_name)",
"= ChangeDescription name = 'change' fields = { 'id': {",
"``screenshot``: The screenshot that was updated. \"\"\" added_in = '1.6'",
"'type': MarkdownFieldsMixin.TEXT_TYPES, 'description': 'The mode for the text field.', 'added_in':",
"= 'review-request-changes' mimetype_item_resource_name = 'review-request-change' def serialize_fields_changed_field(self, obj, **kwargs): review_request",
"keys will be available: * ``old``: The old value of",
"description of the change written by the ' 'submitter.', 'supports_text_types':",
"user describing the change, and also includes a list of",
"new caption. * ``screenshot``: The screenshot that was updated. \"\"\"",
"request, *args, **kwargs): review_request = resources.review_request.get_object( request, *args, **kwargs) return",
"obj, **kwargs): review_request = obj.review_request.get() fields_changed = {} for field_name,",
"new items. * ``removed``: A list of items that were",
"The screenshot that was updated. \"\"\" added_in = '1.6' model",
"* ``old``: The old value of the field. * ``new``:",
"return review_request.changedescs.filter(public=True) @webapi_check_local_site @augment_method_from(WebAPIResource) def get_list(self, *args, **kwargs): \"\"\"Returns a",
"\"\"\"Returns the information on a change to a review request.\"\"\"",
"list of items that were removed, if any. * ``added``:",
"= field.serialize_change_entry(obj) return fields_changed def has_access_permissions(self, request, obj, *args, **kwargs):",
"'description': 'The description of the change written by the '",
"import unicode_literals from django.utils import six from djblets.util.decorators import augment_method_from",
"of items that were removed, if any. * ``added``: A",
"a list of changes made on a review request.\"\"\" pass",
"caption. * ``new``: The new caption. * ``screenshot``: The screenshot",
"def has_access_permissions(self, request, obj, *args, **kwargs): return obj.review_request.get().is_accessible_by(request.user) def get_queryset(self,",
"changes made on a review request.\"\"\" pass @webapi_check_local_site @augment_method_from(WebAPIResource) def",
"A list of bugs that were removed, if any. *",
"the change, and also includes a list of fields that",
"new bugs. * ``removed``: A list of bugs that were",
"augment_method_from from reviewboard.changedescs.models import ChangeDescription from reviewboard.reviews.fields import get_review_request_field from",
"change description.', }, 'fields_changed': { 'type': dict, 'description': 'The fields",
"\"\"\"Returns a list of changes made on a review request.\"\"\"",
"allowed_methods = ('GET',) mimetype_list_resource_name = 'review-request-changes' mimetype_item_resource_name = 'review-request-change' def",
"fields, and the values are details on that particular change",
"that were added, if any. For ``screenshot_captions`` and ``file_captions`` fields:",
"from reviewboard.webapi.base import WebAPIResource from reviewboard.webapi.decorators import webapi_check_local_site from reviewboard.webapi.mixins",
"a public review request. A change includes, optionally, text entered",
"review request. A change includes, optionally, text entered by the",
"from django.utils import six from djblets.util.decorators import augment_method_from from reviewboard.changedescs.models",
"fields: * ``old``: A list of old items. * ``new``:",
"data in six.iteritems(obj.fields_changed): field_cls = get_review_request_field(field_name) field = field_cls(review_request) fields_changed[field.field_id]",
"``file_attachments``, ``screenshots``, ``target_people`` and ``target_groups`` fields: * ``old``: A list",
"diff that was added. For ``bugs_closed`` fields: * ``old``: A",
"MarkdownFieldsMixin.TEXT_TYPES, 'description': 'The mode for the text field.', 'added_in': '2.0',",
"The old caption. * ``new``: The new caption. * ``screenshot``:",
"if any. For ``screenshot_captions`` and ``file_captions`` fields: * ``old``: The",
"on a change to a review request.\"\"\" pass change_resource =",
"'(in YYYY-MM-DD HH:MM:SS format).', }, } uri_object_key = 'change_id' model_parent_key",
"ChangeResource(MarkdownFieldsMixin, WebAPIResource): \"\"\"Provides information on a change made to a",
"*args, **kwargs): return obj.review_request.get().is_accessible_by(request.user) def get_queryset(self, request, *args, **kwargs): review_request",
"change includes, optionally, text entered by the user describing the",
"For ``summary``, ``description``, ``testing_done`` and ``branch`` fields, the following detail",
"= ('GET',) mimetype_list_resource_name = 'review-request-changes' mimetype_item_resource_name = 'review-request-change' def serialize_fields_changed_field(self,",
"model = ChangeDescription name = 'change' fields = { 'id':",
"def get_queryset(self, request, *args, **kwargs): review_request = resources.review_request.get_object( request, *args,",
"that were changed.', }, 'text': { 'type': six.text_type, 'description': 'The",
"('GET',) mimetype_list_resource_name = 'review-request-changes' mimetype_item_resource_name = 'review-request-change' def serialize_fields_changed_field(self, obj,",
"}, 'text_type': { 'type': MarkdownFieldsMixin.TEXT_TYPES, 'description': 'The mode for the",
"* ``old``: The old caption. * ``new``: The new caption.",
"``new``: A list of new bugs. * ``removed``: A list",
"def get_list(self, *args, **kwargs): \"\"\"Returns a list of changes made",
"}, 'text': { 'type': six.text_type, 'description': 'The description of the",
"of fields changed are in ``fields_changed``. The keys are the",
"'The date and time that the change was made '",
"'description': 'The fields that were changed.', }, 'text': { 'type':",
"* ``new``: The new value of the field. For ``diff``",
"request, *args, **kwargs) return review_request.changedescs.filter(public=True) @webapi_check_local_site @augment_method_from(WebAPIResource) def get_list(self, *args,",
"the review request. The list of fields changed are in",
"return obj.review_request.get().is_accessible_by(request.user) def get_queryset(self, request, *args, **kwargs): review_request = resources.review_request.get_object(",
"uri_object_key = 'change_id' model_parent_key = 'review_request' allowed_methods = ('GET',) mimetype_list_resource_name",
"' 'submitter.', 'supports_text_types': True, }, 'text_type': { 'type': MarkdownFieldsMixin.TEXT_TYPES, 'description':",
"* ``new``: A list of new bugs. * ``removed``: A",
"'review_request' allowed_methods = ('GET',) mimetype_list_resource_name = 'review-request-changes' mimetype_item_resource_name = 'review-request-change'",
"from reviewboard.webapi.decorators import webapi_check_local_site from reviewboard.webapi.mixins import MarkdownFieldsMixin from reviewboard.webapi.resources",
"a list of fields that were changed on the review",
"the fields, and the values are details on that particular",
"added. For ``bugs_closed`` fields: * ``old``: A list of old",
"'type': six.text_type, 'description': 'The date and time that the change",
"import MarkdownFieldsMixin from reviewboard.webapi.resources import resources class ChangeResource(MarkdownFieldsMixin, WebAPIResource): \"\"\"Provides",
"and the values are details on that particular change to",
"were added, if any. For ``file_attachments``, ``screenshots``, ``target_people`` and ``target_groups``",
"'description': 'The numeric ID of the change description.', }, 'fields_changed':",
"def get(self, *args, **kwargs): \"\"\"Returns the information on a change",
"removed, if any. * ``added``: A list of items that",
"``testing_done`` and ``branch`` fields, the following detail keys will be",
"__future__ import unicode_literals from django.utils import six from djblets.util.decorators import",
"}, 'timestamp': { 'type': six.text_type, 'description': 'The date and time",
"field. * ``new``: The new value of the field. For",
"be available: * ``old``: The old value of the field.",
"six.text_type, 'description': 'The description of the change written by the",
"items that were removed, if any. * ``added``: A list",
"``old``: A list of old bugs. * ``new``: A list",
"* ``removed``: A list of items that were removed, if",
"the change written by the ' 'submitter.', 'supports_text_types': True, },",
"A list of bugs that were added, if any. For",
"* ``added``: The diff that was added. For ``bugs_closed`` fields:",
"on the review request. The list of fields changed are",
"the ' 'submitter.', 'supports_text_types': True, }, 'text_type': { 'type': MarkdownFieldsMixin.TEXT_TYPES,",
"import six from djblets.util.decorators import augment_method_from from reviewboard.changedescs.models import ChangeDescription",
"import augment_method_from from reviewboard.changedescs.models import ChangeDescription from reviewboard.reviews.fields import get_review_request_field",
"from __future__ import unicode_literals from django.utils import six from djblets.util.decorators",
"on a change made to a public review request. A",
"field_cls(review_request) fields_changed[field.field_id] = field.serialize_change_entry(obj) return fields_changed def has_access_permissions(self, request, obj,",
"' '(in YYYY-MM-DD HH:MM:SS format).', }, } uri_object_key = 'change_id'",
"items. * ``removed``: A list of items that were removed,",
"'added_in': '2.0', }, 'timestamp': { 'type': six.text_type, 'description': 'The date",
"change to the field. For ``summary``, ``description``, ``testing_done`` and ``branch``",
"request, obj, *args, **kwargs): return obj.review_request.get().is_accessible_by(request.user) def get_queryset(self, request, *args,",
"changed are in ``fields_changed``. The keys are the names of",
"* ``old``: A list of old bugs. * ``new``: A",
"name = 'change' fields = { 'id': { 'type': int,",
"model_parent_key = 'review_request' allowed_methods = ('GET',) mimetype_list_resource_name = 'review-request-changes' mimetype_item_resource_name",
"A list of new bugs. * ``removed``: A list of",
"'change' fields = { 'id': { 'type': int, 'description': 'The",
"old items. * ``new``: A list of new items. *",
"'2.0', }, 'timestamp': { 'type': six.text_type, 'description': 'The date and",
"* ``added``: A list of bugs that were added, if",
"that particular change to the field. For ``summary``, ``description``, ``testing_done``",
"resources.review_request.get_object( request, *args, **kwargs) return review_request.changedescs.filter(public=True) @webapi_check_local_site @augment_method_from(WebAPIResource) def get_list(self,",
"{ 'id': { 'type': int, 'description': 'The numeric ID of",
"of the field. * ``new``: The new value of the",
"that were removed, if any. * ``added``: A list of",
"on that particular change to the field. For ``summary``, ``description``,",
"A list of old bugs. * ``new``: A list of",
"of old items. * ``new``: A list of new items.",
"a change to a review request.\"\"\" pass change_resource = ChangeResource()",
"field.', 'added_in': '2.0', }, 'timestamp': { 'type': six.text_type, 'description': 'The",
"*args, **kwargs): review_request = resources.review_request.get_object( request, *args, **kwargs) return review_request.changedescs.filter(public=True)",
"``file_captions`` fields: * ``old``: The old caption. * ``new``: The",
"added, if any. For ``file_attachments``, ``screenshots``, ``target_people`` and ``target_groups`` fields:",
"request. A change includes, optionally, text entered by the user",
"'change_id' model_parent_key = 'review_request' allowed_methods = ('GET',) mimetype_list_resource_name = 'review-request-changes'",
"= obj.review_request.get() fields_changed = {} for field_name, data in six.iteritems(obj.fields_changed):",
"detail keys will be available: * ``old``: The old value",
"import ChangeDescription from reviewboard.reviews.fields import get_review_request_field from reviewboard.webapi.base import WebAPIResource",
"field. For ``summary``, ``description``, ``testing_done`` and ``branch`` fields, the following",
"description.', }, 'fields_changed': { 'type': dict, 'description': 'The fields that",
"by the ' 'submitter.', 'supports_text_types': True, }, 'text_type': { 'type':",
"and ``file_captions`` fields: * ``old``: The old caption. * ``new``:",
"'The fields that were changed.', }, 'text': { 'type': six.text_type,",
"change, and also includes a list of fields that were",
"six.iteritems(obj.fields_changed): field_cls = get_review_request_field(field_name) field = field_cls(review_request) fields_changed[field.field_id] = field.serialize_change_entry(obj)",
"change made to a public review request. A change includes,",
"The new caption. * ``screenshot``: The screenshot that was updated.",
"that was added. For ``bugs_closed`` fields: * ``old``: A list",
"were added, if any. For ``screenshot_captions`` and ``file_captions`` fields: *",
"'text_type': { 'type': MarkdownFieldsMixin.TEXT_TYPES, 'description': 'The mode for the text",
"{ 'type': dict, 'description': 'The fields that were changed.', },",
"added, if any. For ``screenshot_captions`` and ``file_captions`` fields: * ``old``:",
"fields changed are in ``fields_changed``. The keys are the names",
"text field.', 'added_in': '2.0', }, 'timestamp': { 'type': six.text_type, 'description':",
"}, 'fields_changed': { 'type': dict, 'description': 'The fields that were",
"get_review_request_field(field_name) field = field_cls(review_request) fields_changed[field.field_id] = field.serialize_change_entry(obj) return fields_changed def",
"of the fields, and the values are details on that",
"bugs that were removed, if any. * ``added``: A list",
"obj.review_request.get() fields_changed = {} for field_name, data in six.iteritems(obj.fields_changed): field_cls",
"were changed on the review request. The list of fields",
"get_queryset(self, request, *args, **kwargs): review_request = resources.review_request.get_object( request, *args, **kwargs)",
"any. For ``file_attachments``, ``screenshots``, ``target_people`` and ``target_groups`` fields: * ``old``:",
"names of the fields, and the values are details on",
"was added. For ``bugs_closed`` fields: * ``old``: A list of",
"``new``: A list of new items. * ``removed``: A list",
"review_request = obj.review_request.get() fields_changed = {} for field_name, data in",
"screenshot that was updated. \"\"\" added_in = '1.6' model =",
"new value of the field. For ``diff`` fields: * ``added``:",
"*args, **kwargs): \"\"\"Returns a list of changes made on a",
"bugs. * ``removed``: A list of bugs that were removed,",
"of changes made on a review request.\"\"\" pass @webapi_check_local_site @augment_method_from(WebAPIResource)",
"A change includes, optionally, text entered by the user describing",
"``added``: A list of items that were added, if any.",
"available: * ``old``: The old value of the field. *",
"'The numeric ID of the change description.', }, 'fields_changed': {",
"A list of items that were added, if any. For",
"WebAPIResource from reviewboard.webapi.decorators import webapi_check_local_site from reviewboard.webapi.mixins import MarkdownFieldsMixin from",
"\"\"\"Provides information on a change made to a public review",
"list of items that were added, if any. For ``screenshot_captions``",
"list of fields changed are in ``fields_changed``. The keys are",
"class ChangeResource(MarkdownFieldsMixin, WebAPIResource): \"\"\"Provides information on a change made to",
"any. * ``added``: A list of bugs that were added,",
"field.serialize_change_entry(obj) return fields_changed def has_access_permissions(self, request, obj, *args, **kwargs): return",
"added_in = '1.6' model = ChangeDescription name = 'change' fields",
"{ 'type': int, 'description': 'The numeric ID of the change",
"int, 'description': 'The numeric ID of the change description.', },",
"to a public review request. A change includes, optionally, text",
"following detail keys will be available: * ``old``: The old",
"optionally, text entered by the user describing the change, and",
"that were changed on the review request. The list of",
"import WebAPIResource from reviewboard.webapi.decorators import webapi_check_local_site from reviewboard.webapi.mixins import MarkdownFieldsMixin",
"the names of the fields, and the values are details",
"time that the change was made ' '(in YYYY-MM-DD HH:MM:SS",
"that were added, if any. For ``file_attachments``, ``screenshots``, ``target_people`` and",
"``old``: A list of old items. * ``new``: A list",
"**kwargs): \"\"\"Returns the information on a change to a review",
"and also includes a list of fields that were changed",
"has_access_permissions(self, request, obj, *args, **kwargs): return obj.review_request.get().is_accessible_by(request.user) def get_queryset(self, request,",
"that was updated. \"\"\" added_in = '1.6' model = ChangeDescription",
"= { 'id': { 'type': int, 'description': 'The numeric ID",
"of the change written by the ' 'submitter.', 'supports_text_types': True,",
"if any. * ``added``: A list of bugs that were",
"a review request.\"\"\" pass @webapi_check_local_site @augment_method_from(WebAPIResource) def get(self, *args, **kwargs):",
"field. For ``diff`` fields: * ``added``: The diff that was",
"and ``target_groups`` fields: * ``old``: A list of old items.",
"mode for the text field.', 'added_in': '2.0', }, 'timestamp': {",
"bugs that were added, if any. For ``file_attachments``, ``screenshots``, ``target_people``",
"import webapi_check_local_site from reviewboard.webapi.mixins import MarkdownFieldsMixin from reviewboard.webapi.resources import resources",
"fields that were changed on the review request. The list",
"{ 'type': six.text_type, 'description': 'The date and time that the",
"of the change description.', }, 'fields_changed': { 'type': dict, 'description':",
"entered by the user describing the change, and also includes",
"For ``screenshot_captions`` and ``file_captions`` fields: * ``old``: The old caption.",
"'type': int, 'description': 'The numeric ID of the change description.',",
"list of new items. * ``removed``: A list of items",
"request. The list of fields changed are in ``fields_changed``. The",
"fields_changed[field.field_id] = field.serialize_change_entry(obj) return fields_changed def has_access_permissions(self, request, obj, *args,",
"``old``: The old caption. * ``new``: The new caption. *",
"fields that were changed.', }, 'text': { 'type': six.text_type, 'description':",
"were changed.', }, 'text': { 'type': six.text_type, 'description': 'The description",
"``screenshot_captions`` and ``file_captions`` fields: * ``old``: The old caption. *",
"if any. For ``file_attachments``, ``screenshots``, ``target_people`` and ``target_groups`` fields: *",
"A list of new items. * ``removed``: A list of",
"reviewboard.webapi.resources import resources class ChangeResource(MarkdownFieldsMixin, WebAPIResource): \"\"\"Provides information on a",
"@webapi_check_local_site @augment_method_from(WebAPIResource) def get(self, *args, **kwargs): \"\"\"Returns the information on",
"of bugs that were added, if any. For ``file_attachments``, ``screenshots``,",
"obj, *args, **kwargs): return obj.review_request.get().is_accessible_by(request.user) def get_queryset(self, request, *args, **kwargs):",
"on a review request.\"\"\" pass @webapi_check_local_site @augment_method_from(WebAPIResource) def get(self, *args,",
"**kwargs): review_request = obj.review_request.get() fields_changed = {} for field_name, data",
"import resources class ChangeResource(MarkdownFieldsMixin, WebAPIResource): \"\"\"Provides information on a change",
"``new``: The new caption. * ``screenshot``: The screenshot that was",
"'review-request-changes' mimetype_item_resource_name = 'review-request-change' def serialize_fields_changed_field(self, obj, **kwargs): review_request =",
"changed.', }, 'text': { 'type': six.text_type, 'description': 'The description of",
"reviewboard.webapi.mixins import MarkdownFieldsMixin from reviewboard.webapi.resources import resources class ChangeResource(MarkdownFieldsMixin, WebAPIResource):",
"values are details on that particular change to the field.",
"import get_review_request_field from reviewboard.webapi.base import WebAPIResource from reviewboard.webapi.decorators import webapi_check_local_site",
"The diff that was added. For ``bugs_closed`` fields: * ``old``:",
"``added``: The diff that was added. For ``bugs_closed`` fields: *",
"djblets.util.decorators import augment_method_from from reviewboard.changedescs.models import ChangeDescription from reviewboard.reviews.fields import",
"*args, **kwargs): \"\"\"Returns the information on a change to a",
"``removed``: A list of items that were removed, if any.",
"'The description of the change written by the ' 'submitter.',",
"The keys are the names of the fields, and the",
"from reviewboard.changedescs.models import ChangeDescription from reviewboard.reviews.fields import get_review_request_field from reviewboard.webapi.base",
"from djblets.util.decorators import augment_method_from from reviewboard.changedescs.models import ChangeDescription from reviewboard.reviews.fields",
"fields: * ``added``: The diff that was added. For ``bugs_closed``",
"<reponame>mnoorenberghe/reviewboard from __future__ import unicode_literals from django.utils import six from",
"to the field. For ``summary``, ``description``, ``testing_done`` and ``branch`` fields,",
"the field. * ``new``: The new value of the field.",
"True, }, 'text_type': { 'type': MarkdownFieldsMixin.TEXT_TYPES, 'description': 'The mode for",
"unicode_literals from django.utils import six from djblets.util.decorators import augment_method_from from",
"will be available: * ``old``: The old value of the",
"'description': 'The date and time that the change was made",
"**kwargs): review_request = resources.review_request.get_object( request, *args, **kwargs) return review_request.changedescs.filter(public=True) @webapi_check_local_site",
"any. For ``screenshot_captions`` and ``file_captions`` fields: * ``old``: The old",
"caption. * ``screenshot``: The screenshot that was updated. \"\"\" added_in",
"the values are details on that particular change to the",
"old bugs. * ``new``: A list of new bugs. *",
"``removed``: A list of bugs that were removed, if any.",
"from reviewboard.webapi.resources import resources class ChangeResource(MarkdownFieldsMixin, WebAPIResource): \"\"\"Provides information on",
"'submitter.', 'supports_text_types': True, }, 'text_type': { 'type': MarkdownFieldsMixin.TEXT_TYPES, 'description': 'The",
"``bugs_closed`` fields: * ``old``: A list of old bugs. *",
"``diff`` fields: * ``added``: The diff that was added. For",
"removed, if any. * ``added``: A list of bugs that",
"'description': 'The mode for the text field.', 'added_in': '2.0', },",
"in six.iteritems(obj.fields_changed): field_cls = get_review_request_field(field_name) field = field_cls(review_request) fields_changed[field.field_id] =",
"of the field. For ``diff`` fields: * ``added``: The diff",
"resources class ChangeResource(MarkdownFieldsMixin, WebAPIResource): \"\"\"Provides information on a change made",
"changed on the review request. The list of fields changed",
"change written by the ' 'submitter.', 'supports_text_types': True, }, 'text_type':",
"``old``: The old value of the field. * ``new``: The",
"the text field.', 'added_in': '2.0', }, 'timestamp': { 'type': six.text_type,",
"fields_changed def has_access_permissions(self, request, obj, *args, **kwargs): return obj.review_request.get().is_accessible_by(request.user) def",
"text entered by the user describing the change, and also",
"The new value of the field. For ``diff`` fields: *",
"'type': six.text_type, 'description': 'The description of the change written by",
"@augment_method_from(WebAPIResource) def get(self, *args, **kwargs): \"\"\"Returns the information on a",
"= resources.review_request.get_object( request, *args, **kwargs) return review_request.changedescs.filter(public=True) @webapi_check_local_site @augment_method_from(WebAPIResource) def",
"``new``: The new value of the field. For ``diff`` fields:",
"was updated. \"\"\" added_in = '1.6' model = ChangeDescription name",
"old value of the field. * ``new``: The new value",
"of fields that were changed on the review request. The",
"items. * ``new``: A list of new items. * ``removed``:",
"'timestamp': { 'type': six.text_type, 'description': 'The date and time that",
"made to a public review request. A change includes, optionally,",
"WebAPIResource): \"\"\"Provides information on a change made to a public",
"= 'review-request-change' def serialize_fields_changed_field(self, obj, **kwargs): review_request = obj.review_request.get() fields_changed",
"\"\"\" added_in = '1.6' model = ChangeDescription name = 'change'",
"'1.6' model = ChangeDescription name = 'change' fields = {",
"'supports_text_types': True, }, 'text_type': { 'type': MarkdownFieldsMixin.TEXT_TYPES, 'description': 'The mode",
"= 'change' fields = { 'id': { 'type': int, 'description':",
"{ 'type': six.text_type, 'description': 'The description of the change written",
"the user describing the change, and also includes a list",
"YYYY-MM-DD HH:MM:SS format).', }, } uri_object_key = 'change_id' model_parent_key =",
"ChangeDescription name = 'change' fields = { 'id': { 'type':",
"'review-request-change' def serialize_fields_changed_field(self, obj, **kwargs): review_request = obj.review_request.get() fields_changed =",
"``screenshots``, ``target_people`` and ``target_groups`` fields: * ``old``: A list of",
"includes, optionally, text entered by the user describing the change,",
"list of bugs that were added, if any. For ``file_attachments``,",
"the field. For ``diff`` fields: * ``added``: The diff that",
"* ``screenshot``: The screenshot that was updated. \"\"\" added_in =",
"'The mode for the text field.', 'added_in': '2.0', }, 'timestamp':",
"**kwargs): return obj.review_request.get().is_accessible_by(request.user) def get_queryset(self, request, *args, **kwargs): review_request =",
"A list of items that were removed, if any. *",
"*args, **kwargs) return review_request.changedescs.filter(public=True) @webapi_check_local_site @augment_method_from(WebAPIResource) def get_list(self, *args, **kwargs):",
"= get_review_request_field(field_name) field = field_cls(review_request) fields_changed[field.field_id] = field.serialize_change_entry(obj) return fields_changed",
"{ 'type': MarkdownFieldsMixin.TEXT_TYPES, 'description': 'The mode for the text field.',",
"list of fields that were changed on the review request.",
"the change was made ' '(in YYYY-MM-DD HH:MM:SS format).', },",
"that the change was made ' '(in YYYY-MM-DD HH:MM:SS format).',",
"obj.review_request.get().is_accessible_by(request.user) def get_queryset(self, request, *args, **kwargs): review_request = resources.review_request.get_object( request,",
"bugs. * ``new``: A list of new bugs. * ``removed``:",
"``fields_changed``. The keys are the names of the fields, and",
"the change description.', }, 'fields_changed': { 'type': dict, 'description': 'The",
"ChangeDescription from reviewboard.reviews.fields import get_review_request_field from reviewboard.webapi.base import WebAPIResource from",
"of old bugs. * ``new``: A list of new bugs.",
"For ``file_attachments``, ``screenshots``, ``target_people`` and ``target_groups`` fields: * ``old``: A",
"fields: * ``old``: The old caption. * ``new``: The new",
"were removed, if any. * ``added``: A list of items",
"review_request = resources.review_request.get_object( request, *args, **kwargs) return review_request.changedescs.filter(public=True) @webapi_check_local_site @augment_method_from(WebAPIResource)",
"reviewboard.webapi.decorators import webapi_check_local_site from reviewboard.webapi.mixins import MarkdownFieldsMixin from reviewboard.webapi.resources import"
] |
[
"invalid!', }, 400 # Everything is fine # Insert new",
"# POST Method @login_required(app='users') def post(self): # The required models",
"= Forms(data) # Valid form data if form.validate(): # Collect",
"{ 'error': '<i class=\"fas fa-exclamation-triangle mr-1\"></i> Form data is invalid!',",
"# The required models user = Users().read(where={'username':get_session('user')}).first() notes = Notes()",
"Forms(data) # Valid form data if form.validate(): # Collect form",
"import Controller, View, Forms from models import Users, Notes from",
"new note into the database data = { 'user_id': user['id'],",
"Users().read(where={'username':get_session('user')}).first() notes = Notes().read(where={'user_id':user['id']}, order_by={'id':'DESC'}).all() form = Forms() return View('create',",
"Controller, View, Forms from models import Users, Notes from aurora.security",
"# Return the result return { 'success': '<i class=\"fas fa-check-circle",
"data = { 'user_id': user['id'], 'title': title, 'content': content, #",
"# Invalid form data else: # Return the result return",
"aurora.security import login_required, get_session from flask import request from datetime",
"NewNote(Controller): # POST Method @login_required(app='users') def post(self): # The required",
"notes = Notes() # Form data data = request.form form",
"View, Forms from models import Users, Notes from aurora.security import",
"= { 'user_id': user['id'], 'title': title, 'content': content, # 'date':",
"400 # GET Method @login_required(app='users') def get(self): # The required",
"models user = Users().read(where={'username':get_session('user')}).first() notes = Notes() # Form data",
"'title': title, 'content': content, # 'date': datetime.now().strftime(\"%m-%d-%Y\") } notes.create(data=data) #",
"created successfully!', }, 200 # Invalid form data else: #",
"Forms from models import Users, Notes from aurora.security import login_required,",
"mr-1\"></i> The new note created successfully!', }, 200 # Invalid",
"}, 200 # Invalid form data else: # Return the",
"200 # Invalid form data else: # Return the result",
"data is invalid!', }, 400 # GET Method @login_required(app='users') def",
"data else: # Return the result return { 'error': '<i",
"return { 'error': '<i class=\"fas fa-exclamation-triangle mr-1\"></i> Form data is",
"class=\"fas fa-check-circle mr-1\"></i> The new note created successfully!', }, 200",
"Notes() # Form data data = request.form form = Forms(data)",
"aurora import Controller, View, Forms from models import Users, Notes",
"post(self): # The required models user = Users().read(where={'username':get_session('user')}).first() notes =",
"def post(self): # The required models user = Users().read(where={'username':get_session('user')}).first() notes",
"'user_id': user['id'], 'title': title, 'content': content, # 'date': datetime.now().strftime(\"%m-%d-%Y\") }",
"from aurora import Controller, View, Forms from models import Users,",
"import datetime # The controller class class NewNote(Controller): # POST",
"class=\"fas fa-exclamation-triangle mr-1\"></i> Form data is invalid!', }, 400 #",
"Return the result return { 'error': '<i class=\"fas fa-exclamation-triangle mr-1\"></i>",
"return { 'success': '<i class=\"fas fa-check-circle mr-1\"></i> The new note",
"Users, Notes from aurora.security import login_required, get_session from flask import",
"'<i class=\"fas fa-check-circle mr-1\"></i> The new note created successfully!', },",
"controller class class NewNote(Controller): # POST Method @login_required(app='users') def post(self):",
"= Notes().read(where={'user_id':user['id']}, order_by={'id':'DESC'}).all() form = Forms() return View('create', user=user, form=form)",
"content, # 'date': datetime.now().strftime(\"%m-%d-%Y\") } notes.create(data=data) # Return the result",
"'error': '<i class=\"fas fa-exclamation-triangle mr-1\"></i> Form data is invalid!', },",
"fa-exclamation-triangle mr-1\"></i> Form data is invalid!', }, 400 # Everything",
"fields if not title or not content: return { 'error':",
"is invalid!', }, 400 # Everything is fine # Insert",
"the database data = { 'user_id': user['id'], 'title': title, 'content':",
"if not title or not content: return { 'error': '<i",
"# Form data data = request.form form = Forms(data) #",
"form data if form.validate(): # Collect form inputs title =",
"{ 'user_id': user['id'], 'title': title, 'content': content, # 'date': datetime.now().strftime(\"%m-%d-%Y\")",
"is invalid!', }, 400 # GET Method @login_required(app='users') def get(self):",
"datetime import datetime # The controller class class NewNote(Controller): #",
"Notes from aurora.security import login_required, get_session from flask import request",
"# Insert new note into the database data = {",
"form.validate(): # Collect form inputs title = data.get('title') content =",
"Everything is fine # Insert new note into the database",
"# Return the result return { 'error': '<i class=\"fas fa-exclamation-triangle",
"content: return { 'error': '<i class=\"fas fa-exclamation-triangle mr-1\"></i> Form data",
"POST Method @login_required(app='users') def post(self): # The required models user",
"data data = request.form form = Forms(data) # Valid form",
"mr-1\"></i> Form data is invalid!', }, 400 # GET Method",
"{ 'success': '<i class=\"fas fa-check-circle mr-1\"></i> The new note created",
"request.form form = Forms(data) # Valid form data if form.validate():",
"models user = Users().read(where={'username':get_session('user')}).first() notes = Notes().read(where={'user_id':user['id']}, order_by={'id':'DESC'}).all() form =",
"= data.get('content') # Required fields if not title or not",
"Method @login_required(app='users') def get(self): # The required models user =",
"Collect form inputs title = data.get('title') content = data.get('content') #",
"# Collect form inputs title = data.get('title') content = data.get('content')",
"user = Users().read(where={'username':get_session('user')}).first() notes = Notes() # Form data data",
"class NewNote(Controller): # POST Method @login_required(app='users') def post(self): # The",
"}, 400 # Everything is fine # Insert new note",
"fa-check-circle mr-1\"></i> The new note created successfully!', }, 200 #",
"into the database data = { 'user_id': user['id'], 'title': title,",
"notes.create(data=data) # Return the result return { 'success': '<i class=\"fas",
"= request.form form = Forms(data) # Valid form data if",
"datetime # The controller class class NewNote(Controller): # POST Method",
"'success': '<i class=\"fas fa-check-circle mr-1\"></i> The new note created successfully!',",
"note into the database data = { 'user_id': user['id'], 'title':",
"Users().read(where={'username':get_session('user')}).first() notes = Notes() # Form data data = request.form",
"form = Forms(data) # Valid form data if form.validate(): #",
"required models user = Users().read(where={'username':get_session('user')}).first() notes = Notes() # Form",
"Form data is invalid!', }, 400 # Everything is fine",
"# Required fields if not title or not content: return",
"400 # Everything is fine # Insert new note into",
"form data else: # Return the result return { 'error':",
"Method @login_required(app='users') def post(self): # The required models user =",
"datetime.now().strftime(\"%m-%d-%Y\") } notes.create(data=data) # Return the result return { 'success':",
"# The controller class class NewNote(Controller): # POST Method @login_required(app='users')",
"@login_required(app='users') def post(self): # The required models user = Users().read(where={'username':get_session('user')}).first()",
"title, 'content': content, # 'date': datetime.now().strftime(\"%m-%d-%Y\") } notes.create(data=data) # Return",
"def get(self): # The required models user = Users().read(where={'username':get_session('user')}).first() notes",
"= Users().read(where={'username':get_session('user')}).first() notes = Notes() # Form data data =",
"models import Users, Notes from aurora.security import login_required, get_session from",
"data.get('title') content = data.get('content') # Required fields if not title",
"get_session from flask import request from datetime import datetime #",
"Insert new note into the database data = { 'user_id':",
"Form data is invalid!', }, 400 # GET Method @login_required(app='users')",
"= data.get('title') content = data.get('content') # Required fields if not",
"# Everything is fine # Insert new note into the",
"result return { 'error': '<i class=\"fas fa-exclamation-triangle mr-1\"></i> Form data",
"request from datetime import datetime # The controller class class",
"Return the result return { 'success': '<i class=\"fas fa-check-circle mr-1\"></i>",
"the result return { 'success': '<i class=\"fas fa-check-circle mr-1\"></i> The",
"form inputs title = data.get('title') content = data.get('content') # Required",
"# The required models user = Users().read(where={'username':get_session('user')}).first() notes = Notes().read(where={'user_id':user['id']},",
"from datetime import datetime # The controller class class NewNote(Controller):",
"Form data data = request.form form = Forms(data) # Valid",
"Required fields if not title or not content: return {",
"# GET Method @login_required(app='users') def get(self): # The required models",
"title = data.get('title') content = data.get('content') # Required fields if",
"GET Method @login_required(app='users') def get(self): # The required models user",
"from models import Users, Notes from aurora.security import login_required, get_session",
"'content': content, # 'date': datetime.now().strftime(\"%m-%d-%Y\") } notes.create(data=data) # Return the",
"data = request.form form = Forms(data) # Valid form data",
"from flask import request from datetime import datetime # The",
"is fine # Insert new note into the database data",
"Invalid form data else: # Return the result return {",
"class class NewNote(Controller): # POST Method @login_required(app='users') def post(self): #",
"@login_required(app='users') def get(self): # The required models user = Users().read(where={'username':get_session('user')}).first()",
"data if form.validate(): # Collect form inputs title = data.get('title')",
"result return { 'success': '<i class=\"fas fa-check-circle mr-1\"></i> The new",
"the result return { 'error': '<i class=\"fas fa-exclamation-triangle mr-1\"></i> Form",
"fine # Insert new note into the database data =",
"Dependencies from aurora import Controller, View, Forms from models import",
"} notes.create(data=data) # Return the result return { 'success': '<i",
"}, 400 # GET Method @login_required(app='users') def get(self): # The",
"data is invalid!', }, 400 # Everything is fine #",
"not content: return { 'error': '<i class=\"fas fa-exclamation-triangle mr-1\"></i> Form",
"flask import request from datetime import datetime # The controller",
"if form.validate(): # Collect form inputs title = data.get('title') content",
"database data = { 'user_id': user['id'], 'title': title, 'content': content,",
"import request from datetime import datetime # The controller class",
"not title or not content: return { 'error': '<i class=\"fas",
"'date': datetime.now().strftime(\"%m-%d-%Y\") } notes.create(data=data) # Return the result return {",
"= Users().read(where={'username':get_session('user')}).first() notes = Notes().read(where={'user_id':user['id']}, order_by={'id':'DESC'}).all() form = Forms() return",
"# Valid form data if form.validate(): # Collect form inputs",
"# 'date': datetime.now().strftime(\"%m-%d-%Y\") } notes.create(data=data) # Return the result return",
"new note created successfully!', }, 200 # Invalid form data",
"user = Users().read(where={'username':get_session('user')}).first() notes = Notes().read(where={'user_id':user['id']}, order_by={'id':'DESC'}).all() form = Forms()",
"required models user = Users().read(where={'username':get_session('user')}).first() notes = Notes().read(where={'user_id':user['id']}, order_by={'id':'DESC'}).all() form",
"fa-exclamation-triangle mr-1\"></i> Form data is invalid!', }, 400 # GET",
"Valid form data if form.validate(): # Collect form inputs title",
"content = data.get('content') # Required fields if not title or",
"title or not content: return { 'error': '<i class=\"fas fa-exclamation-triangle",
"or not content: return { 'error': '<i class=\"fas fa-exclamation-triangle mr-1\"></i>",
"mr-1\"></i> Form data is invalid!', }, 400 # Everything is",
"data.get('content') # Required fields if not title or not content:",
"The required models user = Users().read(where={'username':get_session('user')}).first() notes = Notes() #",
"get(self): # The required models user = Users().read(where={'username':get_session('user')}).first() notes =",
"# Dependencies from aurora import Controller, View, Forms from models",
"= Notes() # Form data data = request.form form =",
"The controller class class NewNote(Controller): # POST Method @login_required(app='users') def",
"successfully!', }, 200 # Invalid form data else: # Return",
"else: # Return the result return { 'error': '<i class=\"fas",
"user['id'], 'title': title, 'content': content, # 'date': datetime.now().strftime(\"%m-%d-%Y\") } notes.create(data=data)",
"invalid!', }, 400 # GET Method @login_required(app='users') def get(self): #",
"from aurora.security import login_required, get_session from flask import request from",
"inputs title = data.get('title') content = data.get('content') # Required fields",
"The required models user = Users().read(where={'username':get_session('user')}).first() notes = Notes().read(where={'user_id':user['id']}, order_by={'id':'DESC'}).all()",
"import Users, Notes from aurora.security import login_required, get_session from flask",
"import login_required, get_session from flask import request from datetime import",
"note created successfully!', }, 200 # Invalid form data else:",
"notes = Notes().read(where={'user_id':user['id']}, order_by={'id':'DESC'}).all() form = Forms() return View('create', user=user,",
"'<i class=\"fas fa-exclamation-triangle mr-1\"></i> Form data is invalid!', }, 400",
"login_required, get_session from flask import request from datetime import datetime",
"The new note created successfully!', }, 200 # Invalid form"
] |
[
"x.replace('$','')) d=data['Price'].value_counts() print(d) data['Price']=data['Price'].astype(float) #le=LabelEncoder() #data['Installs'] = le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating",
"#Code starts here data = pd.read_csv(path) data['Rating'].hist() data = data[data['Rating']<=5]",
"ends here # -------------- # code starts here total_null =",
"data = data.dropna() total_null_1 = data.isnull().sum() percent_null_1 = (total_null_1/data.isnull().count())*100 missing_data_1",
"Updated Days']=data['Last Updated Days'].dt.days sns.regplot(data=data,x='Last Updated Days',y='Rating').set_title('Rating vs Last Updated",
"as plt import seaborn as sns #Code starts here data",
"x : x.replace(',','')).apply(lambda x : x.replace('+','')) data['Installs'] =data['Installs'].astype(int) print(data['Installs']) data['Installs']",
"#Code ends heree # -------------- #Code starts here import seaborn",
"= pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1) # code ends here # -------------- #Code",
"= sns.catplot(x='Category',y='Rating',data=data, kind=\"box\", height = 10) a.set_xticklabels(rotation=90) a.set_titles('Rating vs Category",
"as sns data['Last Updated'] = pd.to_datetime(data['Last Updated']) print(data['Last Updated'].max()) max_date=data['Last",
"-------------- #Code starts here a = sns.catplot(x='Category',y='Rating',data=data, kind=\"box\", height =",
"= data['Installs'].apply(lambda x : x.replace(',','')).apply(lambda x : x.replace('+','')) data['Installs'] =data['Installs'].astype(int)",
"a = sns.regplot(x=\"Installs\", y=\"Rating\" , data=data) a.set_title('Rating vs Installs [RegPlot]')",
": x.replace('$','')) d=data['Price'].value_counts() print(d) data['Price']=data['Price'].astype(float) #le=LabelEncoder() #data['Installs'] = le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating')",
"from sklearn.preprocessing import MinMaxScaler, LabelEncoder import seaborn as sns #Code",
"ends heree # -------------- #Code starts here import seaborn as",
"ends here # -------------- #Code starts here a = sns.catplot(x='Category',y='Rating',data=data,",
"data['Installs'] =data['Installs'].astype(int) print(data['Installs']) data['Installs'] = le.fit_transform(data['Installs']) a = sns.regplot(x=\"Installs\", y=\"Rating\"",
"Updated Days'].dt.days sns.regplot(data=data,x='Last Updated Days',y='Rating').set_title('Rating vs Last Updated [RegPlot]') #Code",
"= pd.to_datetime(data['Last Updated']) print(data['Last Updated'].max()) max_date=data['Last Updated'].max() data['Last Updated Days']=max_date-data['Last",
"# -------------- #Code starts here a = sns.catplot(x='Category',y='Rating',data=data, kind=\"box\", height",
"y.set_title('Rating vs Installs [RegPlot]') #Code ends here # -------------- #Code",
"pd.to_datetime(data['Last Updated']) print(data['Last Updated'].max()) max_date=data['Last Updated'].max() data['Last Updated Days']=max_date-data['Last Updated']",
"sns #Code starts here data = pd.read_csv(path) data['Rating'].hist() data =",
"data.isnull().sum() percent_null_1 = (total_null_1/data.isnull().count())*100 missing_data_1 = pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1) # code",
"#Code starts here a = sns.catplot(x='Category',y='Rating',data=data, kind=\"box\", height = 10)",
"import seaborn as sns #Code starts here d=data['Price'].value_counts() print(d) data['Price']=data['Price'].apply(lambda",
"import MinMaxScaler, LabelEncoder import seaborn as sns #Code starts here",
"import MinMaxScaler, LabelEncoder #Code starts here le = LabelEncoder() #data['Installs']",
"MinMaxScaler, LabelEncoder #Code starts here le = LabelEncoder() #data['Installs'] =",
"y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating vs Installs [RegPlot]') #Code ends here # --------------",
"#Importing header files import pandas as pd import matplotlib.pyplot as",
"here d=data['Price'].value_counts() print(d) data['Price']=data['Price'].apply(lambda x : x.replace('$','')) d=data['Price'].value_counts() print(d) data['Price']=data['Price'].astype(float)",
"= pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data) data = data.dropna() total_null_1 = data.isnull().sum() percent_null_1",
"gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:]) #Code ends heree # -------------- #Code starts",
"= le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating vs Installs [RegPlot]') #Code ends here",
"#Code ends here # -------------- #Code starts here data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres'])",
"print(gr_mean)#,gr_mean[-1,:]) #Code ends heree # -------------- #Code starts here import",
"starts here data = pd.read_csv(path) data['Rating'].hist() data = data[data['Rating']<=5] data['Rating'].hist()",
"-------------- #Importing header files import pandas as pd import matplotlib.pyplot",
"#print(data['Genres']) df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:]) #Code ends heree #",
"print(missing_data_1) # code ends here # -------------- #Code starts here",
"# -------------- #Code starts here data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres']) df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating'])",
"Updated'] data['Last Updated Days']=data['Last Updated Days'].dt.days sns.regplot(data=data,x='Last Updated Days',y='Rating').set_title('Rating vs",
"as pd import matplotlib.pyplot as plt import seaborn as sns",
"= LabelEncoder() #data['Installs'] = data['Installs'].str.replace(',','').str.replace('+','') data['Installs'] = data['Installs'].apply(lambda x :",
"here # -------------- #Importing header files from sklearn.preprocessing import MinMaxScaler,",
"missing_data_1 = pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1) # code ends here # --------------",
"(total_null_1/data.isnull().count())*100 missing_data_1 = pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1) # code ends here #",
"=data['Installs'].astype(int) print(data['Installs']) data['Installs'] = le.fit_transform(data['Installs']) a = sns.regplot(x=\"Installs\", y=\"Rating\" ,",
"header files from sklearn.preprocessing import MinMaxScaler, LabelEncoder #Code starts here",
"= le.fit_transform(data['Installs']) a = sns.regplot(x=\"Installs\", y=\"Rating\" , data=data) a.set_title('Rating vs",
"print(data['Last Updated'].max()) max_date=data['Last Updated'].max() data['Last Updated Days']=max_date-data['Last Updated'] data['Last Updated",
"data['Installs'] = data['Installs'].apply(lambda x : x.replace(',','')).apply(lambda x : x.replace('+','')) data['Installs']",
"#Code starts here from sklearn.preprocessing import MinMaxScaler, LabelEncoder import seaborn",
"a.set_xticklabels(rotation=90) a.set_titles('Rating vs Category [BoxPlot]') #Code ends here # --------------",
"starts here import seaborn as sns data['Last Updated'] = pd.to_datetime(data['Last",
"# -------------- #Code starts here from sklearn.preprocessing import MinMaxScaler, LabelEncoder",
"(total_null/data.isnull().count())*100 missing_data = pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data) data = data.dropna() total_null_1 =",
"d=data['Price'].value_counts() print(d) data['Price']=data['Price'].astype(float) #le=LabelEncoder() #data['Installs'] = le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating vs",
"starts here a = sns.catplot(x='Category',y='Rating',data=data, kind=\"box\", height = 10) a.set_xticklabels(rotation=90)",
"starts here d=data['Price'].value_counts() print(d) data['Price']=data['Price'].apply(lambda x : x.replace('$','')) d=data['Price'].value_counts() print(d)",
"= pd.read_csv(path) data['Rating'].hist() data = data[data['Rating']<=5] data['Rating'].hist() #Code ends here",
"here from sklearn.preprocessing import MinMaxScaler, LabelEncoder import seaborn as sns",
"le.fit_transform(data['Installs']) a = sns.regplot(x=\"Installs\", y=\"Rating\" , data=data) a.set_title('Rating vs Installs",
"#Code ends here # -------------- #Code starts here from sklearn.preprocessing",
"10) a.set_xticklabels(rotation=90) a.set_titles('Rating vs Category [BoxPlot]') #Code ends here #",
"sns #Code starts here d=data['Price'].value_counts() print(d) data['Price']=data['Price'].apply(lambda x : x.replace('$',''))",
"Days']=data['Last Updated Days'].dt.days sns.regplot(data=data,x='Last Updated Days',y='Rating').set_title('Rating vs Last Updated [RegPlot]')",
"pandas as pd import matplotlib.pyplot as plt import seaborn as",
"sns.regplot(x=\"Installs\", y=\"Rating\" , data=data) a.set_title('Rating vs Installs [RegPlot]') #Code ends",
"= (total_null/data.isnull().count())*100 missing_data = pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data) data = data.dropna() total_null_1",
"pd import matplotlib.pyplot as plt import seaborn as sns #Code",
"#Code ends here # -------------- # code starts here total_null",
"print(d) data['Price']=data['Price'].apply(lambda x : x.replace('$','')) d=data['Price'].value_counts() print(d) data['Price']=data['Price'].astype(float) #le=LabelEncoder() #data['Installs']",
"kind=\"box\", height = 10) a.set_xticklabels(rotation=90) a.set_titles('Rating vs Category [BoxPlot]') #Code",
"Days'].dt.days sns.regplot(data=data,x='Last Updated Days',y='Rating').set_title('Rating vs Last Updated [RegPlot]') #Code ends",
"total_null = data.isnull().sum() percent_null = (total_null/data.isnull().count())*100 missing_data = pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data)",
"vs Category [BoxPlot]') #Code ends here # -------------- #Importing header",
"ends here # -------------- #Code starts here data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres']) df=data[['Genres','Rating']]",
"Updated Days']=max_date-data['Last Updated'] data['Last Updated Days']=data['Last Updated Days'].dt.days sns.regplot(data=data,x='Last Updated",
"data[data['Rating']<=5] data['Rating'].hist() #Code ends here # -------------- # code starts",
": x.replace('+','')) data['Installs'] =data['Installs'].astype(int) print(data['Installs']) data['Installs'] = le.fit_transform(data['Installs']) a =",
"# -------------- # code starts here total_null = data.isnull().sum() percent_null",
"pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data) data = data.dropna() total_null_1 = data.isnull().sum() percent_null_1 =",
"gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:]) #Code ends heree # -------------- #Code starts here",
"print(missing_data) data = data.dropna() total_null_1 = data.isnull().sum() percent_null_1 = (total_null_1/data.isnull().count())*100",
"= 10) a.set_xticklabels(rotation=90) a.set_titles('Rating vs Category [BoxPlot]') #Code ends here",
"sns.regplot(data=data,x='Last Updated Days',y='Rating').set_title('Rating vs Last Updated [RegPlot]') #Code ends here",
"-------------- #Code starts here import seaborn as sns data['Last Updated']",
"#Code ends here # -------------- #Importing header files from sklearn.preprocessing",
"# code ends here # -------------- #Code starts here a",
"-------------- # code starts here total_null = data.isnull().sum() percent_null =",
"import pandas as pd import matplotlib.pyplot as plt import seaborn",
"[BoxPlot]') #Code ends here # -------------- #Importing header files from",
"seaborn as sns #Code starts here d=data['Price'].value_counts() print(d) data['Price']=data['Price'].apply(lambda x",
"= data[data['Rating']<=5] data['Rating'].hist() #Code ends here # -------------- # code",
"here # -------------- #Code starts here data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres']) df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean()",
"MinMaxScaler, LabelEncoder import seaborn as sns #Code starts here d=data['Price'].value_counts()",
"LabelEncoder import seaborn as sns #Code starts here d=data['Price'].value_counts() print(d)",
"data['Last Updated Days']=data['Last Updated Days'].dt.days sns.regplot(data=data,x='Last Updated Days',y='Rating').set_title('Rating vs Last",
"-------------- #Code starts here from sklearn.preprocessing import MinMaxScaler, LabelEncoder import",
"-------------- #Code starts here data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres']) df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean)",
"#Code starts here data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres']) df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:])",
"total_null_1 = data.isnull().sum() percent_null_1 = (total_null_1/data.isnull().count())*100 missing_data_1 = pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1)",
"a.set_title('Rating vs Installs [RegPlot]') #Code ends here # -------------- #Code",
"starts here from sklearn.preprocessing import MinMaxScaler, LabelEncoder import seaborn as",
"as sns #Code starts here d=data['Price'].value_counts() print(d) data['Price']=data['Price'].apply(lambda x :",
"starts here le = LabelEncoder() #data['Installs'] = data['Installs'].str.replace(',','').str.replace('+','') data['Installs'] =",
"[RegPlot]') #Code ends here # -------------- #Code starts here data['Genres']=data['Genres'].str.split(';').str[0]",
"data['Installs'].str.replace(',','').str.replace('+','') data['Installs'] = data['Installs'].apply(lambda x : x.replace(',','')).apply(lambda x : x.replace('+',''))",
"print(d) data['Price']=data['Price'].astype(float) #le=LabelEncoder() #data['Installs'] = le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating vs Installs",
"here # -------------- #Code starts here from sklearn.preprocessing import MinMaxScaler,",
"x : x.replace('$','')) d=data['Price'].value_counts() print(d) data['Price']=data['Price'].astype(float) #le=LabelEncoder() #data['Installs'] = le.fit_transform(data['Installs'])",
"a = sns.catplot(x='Category',y='Rating',data=data, kind=\"box\", height = 10) a.set_xticklabels(rotation=90) a.set_titles('Rating vs",
"# -------------- #Importing header files from sklearn.preprocessing import MinMaxScaler, LabelEncoder",
"here # -------------- # code starts here total_null = data.isnull().sum()",
"#Importing header files from sklearn.preprocessing import MinMaxScaler, LabelEncoder #Code starts",
"from sklearn.preprocessing import MinMaxScaler, LabelEncoder #Code starts here le =",
"data=data) a.set_title('Rating vs Installs [RegPlot]') #Code ends here # --------------",
"ends here # -------------- #Code starts here from sklearn.preprocessing import",
"#data['Installs'] = le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating vs Installs [RegPlot]') #Code ends",
"print(data['Installs']) data['Installs'] = le.fit_transform(data['Installs']) a = sns.regplot(x=\"Installs\", y=\"Rating\" , data=data)",
"percent_null = (total_null/data.isnull().count())*100 missing_data = pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data) data = data.dropna()",
"ends here # -------------- #Importing header files from sklearn.preprocessing import",
"Updated'].max() data['Last Updated Days']=max_date-data['Last Updated'] data['Last Updated Days']=data['Last Updated Days'].dt.days",
"data = pd.read_csv(path) data['Rating'].hist() data = data[data['Rating']<=5] data['Rating'].hist() #Code ends",
"here # -------------- #Code starts here a = sns.catplot(x='Category',y='Rating',data=data, kind=\"box\",",
"data['Rating'].hist() data = data[data['Rating']<=5] data['Rating'].hist() #Code ends here # --------------",
", data=data) a.set_title('Rating vs Installs [RegPlot]') #Code ends here #",
"sns.catplot(x='Category',y='Rating',data=data, kind=\"box\", height = 10) a.set_xticklabels(rotation=90) a.set_titles('Rating vs Category [BoxPlot]')",
"header files import pandas as pd import matplotlib.pyplot as plt",
"import seaborn as sns #Code starts here data = pd.read_csv(path)",
"LabelEncoder() #data['Installs'] = data['Installs'].str.replace(',','').str.replace('+','') data['Installs'] = data['Installs'].apply(lambda x : x.replace(',','')).apply(lambda",
"data['Installs'].apply(lambda x : x.replace(',','')).apply(lambda x : x.replace('+','')) data['Installs'] =data['Installs'].astype(int) print(data['Installs'])",
"height = 10) a.set_xticklabels(rotation=90) a.set_titles('Rating vs Category [BoxPlot]') #Code ends",
"data['Rating'].hist() #Code ends here # -------------- # code starts here",
"#data['Installs'] = data['Installs'].str.replace(',','').str.replace('+','') data['Installs'] = data['Installs'].apply(lambda x : x.replace(',','')).apply(lambda x",
"= data.isnull().sum() percent_null_1 = (total_null_1/data.isnull().count())*100 missing_data_1 = pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1) #",
"x.replace(',','')).apply(lambda x : x.replace('+','')) data['Installs'] =data['Installs'].astype(int) print(data['Installs']) data['Installs'] = le.fit_transform(data['Installs'])",
"data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres']) df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:]) #Code ends heree",
"df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:]) #Code ends heree # --------------",
"# -------------- #Importing header files import pandas as pd import",
"pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1) # code ends here # -------------- #Code starts",
"seaborn as sns data['Last Updated'] = pd.to_datetime(data['Last Updated']) print(data['Last Updated'].max())",
"= data.isnull().sum() percent_null = (total_null/data.isnull().count())*100 missing_data = pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data) data",
": x.replace(',','')).apply(lambda x : x.replace('+','')) data['Installs'] =data['Installs'].astype(int) print(data['Installs']) data['Installs'] =",
"Category [BoxPlot]') #Code ends here # -------------- #Importing header files",
"x.replace('+','')) data['Installs'] =data['Installs'].astype(int) print(data['Installs']) data['Installs'] = le.fit_transform(data['Installs']) a = sns.regplot(x=\"Installs\",",
"#Code starts here d=data['Price'].value_counts() print(d) data['Price']=data['Price'].apply(lambda x : x.replace('$','')) d=data['Price'].value_counts()",
"# -------------- #Code starts here import seaborn as sns data['Last",
"a.set_titles('Rating vs Category [BoxPlot]') #Code ends here # -------------- #Importing",
"Installs [RegPlot]') #Code ends here # -------------- #Code starts here",
"Days']=max_date-data['Last Updated'] data['Last Updated Days']=data['Last Updated Days'].dt.days sns.regplot(data=data,x='Last Updated Days',y='Rating').set_title('Rating",
"code starts here total_null = data.isnull().sum() percent_null = (total_null/data.isnull().count())*100 missing_data",
"= data['Installs'].str.replace(',','').str.replace('+','') data['Installs'] = data['Installs'].apply(lambda x : x.replace(',','')).apply(lambda x :",
"x : x.replace('+','')) data['Installs'] =data['Installs'].astype(int) print(data['Installs']) data['Installs'] = le.fit_transform(data['Installs']) a",
"starts here total_null = data.isnull().sum() percent_null = (total_null/data.isnull().count())*100 missing_data =",
"data['Last Updated Days']=max_date-data['Last Updated'] data['Last Updated Days']=data['Last Updated Days'].dt.days sns.regplot(data=data,x='Last",
"here data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres']) df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:]) #Code ends",
"here data = pd.read_csv(path) data['Rating'].hist() data = data[data['Rating']<=5] data['Rating'].hist() #Code",
"#Code starts here le = LabelEncoder() #data['Installs'] = data['Installs'].str.replace(',','').str.replace('+','') data['Installs']",
"= (total_null_1/data.isnull().count())*100 missing_data_1 = pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1) # code ends here",
"#Code starts here import seaborn as sns data['Last Updated'] =",
"gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:]) #Code ends heree # -------------- #Code",
"= sns.regplot(x=\"Installs\", y=\"Rating\" , data=data) a.set_title('Rating vs Installs [RegPlot]') #Code",
"LabelEncoder #Code starts here le = LabelEncoder() #data['Installs'] = data['Installs'].str.replace(',','').str.replace('+','')",
"plt import seaborn as sns #Code starts here data =",
"here import seaborn as sns data['Last Updated'] = pd.to_datetime(data['Last Updated'])",
"here a = sns.catplot(x='Category',y='Rating',data=data, kind=\"box\", height = 10) a.set_xticklabels(rotation=90) a.set_titles('Rating",
"#le=LabelEncoder() #data['Installs'] = le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating vs Installs [RegPlot]') #Code",
"data['Price']=data['Price'].apply(lambda x : x.replace('$','')) d=data['Price'].value_counts() print(d) data['Price']=data['Price'].astype(float) #le=LabelEncoder() #data['Installs'] =",
"sklearn.preprocessing import MinMaxScaler, LabelEncoder #Code starts here le = LabelEncoder()",
"here le = LabelEncoder() #data['Installs'] = data['Installs'].str.replace(',','').str.replace('+','') data['Installs'] = data['Installs'].apply(lambda",
"le = LabelEncoder() #data['Installs'] = data['Installs'].str.replace(',','').str.replace('+','') data['Installs'] = data['Installs'].apply(lambda x",
"sklearn.preprocessing import MinMaxScaler, LabelEncoder import seaborn as sns #Code starts",
"matplotlib.pyplot as plt import seaborn as sns #Code starts here",
"max_date=data['Last Updated'].max() data['Last Updated Days']=max_date-data['Last Updated'] data['Last Updated Days']=data['Last Updated",
"missing_data = pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data) data = data.dropna() total_null_1 = data.isnull().sum()",
"-------------- #Importing header files from sklearn.preprocessing import MinMaxScaler, LabelEncoder #Code",
"d=data['Price'].value_counts() print(d) data['Price']=data['Price'].apply(lambda x : x.replace('$','')) d=data['Price'].value_counts() print(d) data['Price']=data['Price'].astype(float) #le=LabelEncoder()",
"pd.read_csv(path) data['Rating'].hist() data = data[data['Rating']<=5] data['Rating'].hist() #Code ends here #",
"percent_null_1 = (total_null_1/data.isnull().count())*100 missing_data_1 = pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage']) print(missing_data_1) # code ends",
"data = data[data['Rating']<=5] data['Rating'].hist() #Code ends here # -------------- #",
"heree # -------------- #Code starts here import seaborn as sns",
"le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating vs Installs [RegPlot]') #Code ends here #",
"Updated'].max()) max_date=data['Last Updated'].max() data['Last Updated Days']=max_date-data['Last Updated'] data['Last Updated Days']=data['Last",
"as sns #Code starts here data = pd.read_csv(path) data['Rating'].hist() data",
"import seaborn as sns data['Last Updated'] = pd.to_datetime(data['Last Updated']) print(data['Last",
"data['Last Updated'] = pd.to_datetime(data['Last Updated']) print(data['Last Updated'].max()) max_date=data['Last Updated'].max() data['Last",
"Updated']) print(data['Last Updated'].max()) max_date=data['Last Updated'].max() data['Last Updated Days']=max_date-data['Last Updated'] data['Last",
"[RegPlot]') #Code ends here # -------------- #Code starts here from",
"y=\"Rating\" , data=data) a.set_title('Rating vs Installs [RegPlot]') #Code ends here",
"here total_null = data.isnull().sum() percent_null = (total_null/data.isnull().count())*100 missing_data = pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage'])",
"starts here data['Genres']=data['Genres'].str.split(';').str[0] #print(data['Genres']) df=data[['Genres','Rating']] gr_mean=df.groupby(['Genres'],as_index=False).mean() gr_mean=gr_mean.sort_values(by=['Rating']) gr_mean=pd.DataFrame(gr_mean) print(gr_mean)#,gr_mean[-1,:]) #Code",
"data.dropna() total_null_1 = data.isnull().sum() percent_null_1 = (total_null_1/data.isnull().count())*100 missing_data_1 = pd.concat([total_null_1,percent_null_1],axis=1,keys=['Total','Percentage'])",
"files from sklearn.preprocessing import MinMaxScaler, LabelEncoder #Code starts here le",
"import matplotlib.pyplot as plt import seaborn as sns #Code starts",
"seaborn as sns #Code starts here data = pd.read_csv(path) data['Rating'].hist()",
"Updated'] = pd.to_datetime(data['Last Updated']) print(data['Last Updated'].max()) max_date=data['Last Updated'].max() data['Last Updated",
"files import pandas as pd import matplotlib.pyplot as plt import",
"vs Installs [RegPlot]') #Code ends here # -------------- #Code starts",
"data.isnull().sum() percent_null = (total_null/data.isnull().count())*100 missing_data = pd.concat([total_null,percent_null],axis=1,keys=['Total','Percentage']) print(missing_data) data =",
"code ends here # -------------- #Code starts here a =",
"= data.dropna() total_null_1 = data.isnull().sum() percent_null_1 = (total_null_1/data.isnull().count())*100 missing_data_1 =",
"data['Installs'] = le.fit_transform(data['Installs']) a = sns.regplot(x=\"Installs\", y=\"Rating\" , data=data) a.set_title('Rating",
"sns data['Last Updated'] = pd.to_datetime(data['Last Updated']) print(data['Last Updated'].max()) max_date=data['Last Updated'].max()",
"data['Price']=data['Price'].astype(float) #le=LabelEncoder() #data['Installs'] = le.fit_transform(data['Installs']) y=sns.regplot(data=data,x='Price',y='Rating') y.set_title('Rating vs Installs [RegPlot]')",
"# code starts here total_null = data.isnull().sum() percent_null = (total_null/data.isnull().count())*100"
] |
[
"the algorithm is to be run. quantity : string (default",
"self.setup(phase=phase) def setup(self, phase=None, quantity='', conductance='', charge_conservation=None, **kwargs): r\"\"\" This",
"Project object Either a network or a project must be",
"optional A unique name to give the object for easier",
"'charge_conservation': 'electroneutrality', 'gui': {'setup': {'phase': None, 'quantity': '', 'conductance': '',",
"object associated with the given *Phase*. charge_conservation : string The",
"conductance if charge_conservation: self.settings['charge_conservation'] = charge_conservation super().setup(**kwargs) def _charge_conservation_eq_source_term(self, e_alg):",
"def __init__(self, settings={}, phase=None, **kwargs): def_set = {'phase': None, 'quantity':",
"= conductance if charge_conservation: self.settings['charge_conservation'] = charge_conservation super().setup(**kwargs) def _charge_conservation_eq_source_term(self,",
"specified name : string, optional A unique name to give",
"calculated. conductance : string (default is ``'throat.diffusive_conductance'``) The name of",
"project must be specified name : string, optional A unique",
"'', 'conductance': '', 'charge_conservation': ''}, 'set_rate_BC': {'pores': None, 'values': None},",
"a network or a project must be specified name :",
"logging.getLogger(__name__) class ChargeConservation(ReactiveTransport): r\"\"\" A class to enforce charge conservation",
"enforce charge conservation when performing ions transport simulations (default is",
"None}, 'set_source': {'pores': None, 'propname': ''} } } super().__init__(**kwargs) self.settings.update(def_set)",
"{'phase': None, 'quantity': '', 'conductance': '', 'charge_conservation': ''}, 'set_rate_BC': {'pores':",
"as gst from openpnm.utils import logging logger = logging.getLogger(__name__) class",
"openpnm.utils import logging logger = logging.getLogger(__name__) class ChargeConservation(ReactiveTransport): r\"\"\" A",
": OpenPNM Network object The network on which this algorithm",
"None, 'quantity': '', 'conductance': '', 'charge_conservation': ''}, 'set_rate_BC': {'pores': None,",
"conservation when performing ions transport simulations (default is \"electroneutrality\"). Notes",
"= charge_conservation super().setup(**kwargs) def _charge_conservation_eq_source_term(self, e_alg): # Source term for",
"name to give the object for easier identification. If not",
"or a project must be specified name : string, optional",
"None}, 'set_value_BC': {'pores': None, 'values': None}, 'set_source': {'pores': None, 'propname':",
"---------- phase : OpenPNM Phase object The phase on which",
"charge_conservation: self.settings['charge_conservation'] = charge_conservation super().setup(**kwargs) def _charge_conservation_eq_source_term(self, e_alg): # Source",
": string The assumption adopted to enforce charge conservation when",
"performing ions transport simulations (default is \"electroneutrality\"). Notes ----- Any",
"np from openpnm.algorithms import ReactiveTransport from openpnm.models.physics import generic_source_term as",
"logging logger = logging.getLogger(__name__) class ChargeConservation(ReactiveTransport): r\"\"\" A class to",
"algorithm operates project : OpenPNM Project object Either a network",
"given, one is generated. \"\"\" def __init__(self, settings={}, phase=None, **kwargs):",
"This method takes several arguments that are essential to running",
"Phase object The phase on which the algorithm is to",
"to be calculated. conductance : string (default is ``'throat.diffusive_conductance'``) The",
"simulations. Parameters ---------- network : OpenPNM Network object The network",
"'', 'charge_conservation': ''}, 'set_rate_BC': {'pores': None, 'values': None}, 'set_value_BC': {'pores':",
"``'throat.diffusive_conductance'``) The name of the pore-scale transport conductance values. These",
"associated with the given *Phase*. charge_conservation : string The assumption",
"Source term for Poisson or charge conservation (electroneutrality) eq phase",
"{'setup': {'phase': None, 'quantity': '', 'conductance': '', 'charge_conservation': ''}, 'set_rate_BC':",
"quantity to be calculated. conductance : string (default is ``'throat.diffusive_conductance'``)",
"calculated by a model attached to a *Physics* object associated",
"\"\"\" def __init__(self, settings={}, phase=None, **kwargs): def_set = {'phase': None,",
"A class to enforce charge conservation in ionic transport simulations.",
"and adds them to the settings. Parameters ---------- phase :",
"conductance values. These are typically calculated by a model attached",
"None: self.setup(phase=phase) def setup(self, phase=None, quantity='', conductance='', charge_conservation=None, **kwargs): r\"\"\"",
"r\"\"\" A class to enforce charge conservation in ionic transport",
"OpenPNM Project object Either a network or a project must",
"attached to a *Physics* object associated with the given *Phase*.",
"The phase on which the algorithm is to be run.",
"(electroneutrality) eq phase = self.project.phases()[self.settings['phase']] Ps = (self['pore.all'] * np.isnan(self['pore.bc_value'])",
"is ``'pore.mole_fraction'``) The name of the physical quantity to be",
"mod = gst.charge_conservation phys = self.project.find_physics(phase=phase) phys[0].add_model(propname='pore.charge_conservation', model=mod, phase=phase, p_alg=self,",
"Poisson or charge conservation (electroneutrality) eq phase = self.project.phases()[self.settings['phase']] Ps",
"quantity : string (default is ``'pore.mole_fraction'``) The name of the",
"name of the pore-scale transport conductance values. These are typically",
"object for easier identification. If not given, one is generated.",
"are added to the ``settings`` dictionary of the object. \"\"\"",
"conductance: self.settings['conductance'] = conductance if charge_conservation: self.settings['charge_conservation'] = charge_conservation super().setup(**kwargs)",
"essential to running the algorithm and adds them to the",
"to running the algorithm and adds them to the settings.",
"(default is ``'throat.diffusive_conductance'``) The name of the pore-scale transport conductance",
": OpenPNM Project object Either a network or a project",
"network : OpenPNM Network object The network on which this",
"if phase is not None: self.setup(phase=phase) def setup(self, phase=None, quantity='',",
"string, optional A unique name to give the object for",
"not given, one is generated. \"\"\" def __init__(self, settings={}, phase=None,",
"\"\"\" if phase: self.settings['phase'] = phase.name if quantity: self.settings['quantity'] =",
"or charge conservation (electroneutrality) eq phase = self.project.phases()[self.settings['phase']] Ps =",
"with the given *Phase*. charge_conservation : string The assumption adopted",
"name of the physical quantity to be calculated. conductance :",
"string (default is ``'pore.mole_fraction'``) The name of the physical quantity",
"numpy as np from openpnm.algorithms import ReactiveTransport from openpnm.models.physics import",
"self.settings.update(settings) if phase is not None: self.setup(phase=phase) def setup(self, phase=None,",
"def setup(self, phase=None, quantity='', conductance='', charge_conservation=None, **kwargs): r\"\"\" This method",
"not None: self.setup(phase=phase) def setup(self, phase=None, quantity='', conductance='', charge_conservation=None, **kwargs):",
"None, 'quantity': 'pore.potential', 'conductance': 'throat.ionic_conductance', 'charge_conservation': 'electroneutrality', 'gui': {'setup': {'phase':",
"conservation in ionic transport simulations. Parameters ---------- network : OpenPNM",
"a *Physics* object associated with the given *Phase*. charge_conservation :",
"object The network on which this algorithm operates project :",
"simulations (default is \"electroneutrality\"). Notes ----- Any additional arguments are",
"must be specified name : string, optional A unique name",
"import numpy as np from openpnm.algorithms import ReactiveTransport from openpnm.models.physics",
"= quantity if conductance: self.settings['conductance'] = conductance if charge_conservation: self.settings['charge_conservation']",
"= (self['pore.all'] * np.isnan(self['pore.bc_value']) * np.isnan(self['pore.bc_rate'])) mod = gst.charge_conservation phys",
"self.settings.update(def_set) self.settings.update(settings) if phase is not None: self.setup(phase=phase) def setup(self,",
"be run. quantity : string (default is ``'pore.mole_fraction'``) The name",
"charge conservation in ionic transport simulations. Parameters ---------- network :",
"'pore.potential', 'conductance': 'throat.ionic_conductance', 'charge_conservation': 'electroneutrality', 'gui': {'setup': {'phase': None, 'quantity':",
"A unique name to give the object for easier identification.",
"np.isnan(self['pore.bc_value']) * np.isnan(self['pore.bc_rate'])) mod = gst.charge_conservation phys = self.project.find_physics(phase=phase) phys[0].add_model(propname='pore.charge_conservation',",
"logger = logging.getLogger(__name__) class ChargeConservation(ReactiveTransport): r\"\"\" A class to enforce",
"{'pores': None, 'values': None}, 'set_value_BC': {'pores': None, 'values': None}, 'set_source':",
"to the ``settings`` dictionary of the object. \"\"\" if phase:",
"*Phase*. charge_conservation : string The assumption adopted to enforce charge",
"enforce charge conservation in ionic transport simulations. Parameters ---------- network",
"if conductance: self.settings['conductance'] = conductance if charge_conservation: self.settings['charge_conservation'] = charge_conservation",
"If not given, one is generated. \"\"\" def __init__(self, settings={},",
"project : OpenPNM Project object Either a network or a",
"from openpnm.utils import logging logger = logging.getLogger(__name__) class ChargeConservation(ReactiveTransport): r\"\"\"",
"generic_source_term as gst from openpnm.utils import logging logger = logging.getLogger(__name__)",
"the pore-scale transport conductance values. These are typically calculated by",
"phys = self.project.find_physics(phase=phase) phys[0].add_model(propname='pore.charge_conservation', model=mod, phase=phase, p_alg=self, e_alg=e_alg, assumption=self.settings['charge_conservation']) self.set_source(propname='pore.charge_conservation',",
"arguments that are essential to running the algorithm and adds",
"transport conductance values. These are typically calculated by a model",
"{'pores': None, 'propname': ''} } } super().__init__(**kwargs) self.settings.update(def_set) self.settings.update(settings) if",
"''} } } super().__init__(**kwargs) self.settings.update(def_set) self.settings.update(settings) if phase is not",
"OpenPNM Network object The network on which this algorithm operates",
"string (default is ``'throat.diffusive_conductance'``) The name of the pore-scale transport",
"the object. \"\"\" if phase: self.settings['phase'] = phase.name if quantity:",
"running the algorithm and adds them to the settings. Parameters",
"'electroneutrality', 'gui': {'setup': {'phase': None, 'quantity': '', 'conductance': '', 'charge_conservation':",
"} } super().__init__(**kwargs) self.settings.update(def_set) self.settings.update(settings) if phase is not None:",
"'quantity': 'pore.potential', 'conductance': 'throat.ionic_conductance', 'charge_conservation': 'electroneutrality', 'gui': {'setup': {'phase': None,",
"= phase.name if quantity: self.settings['quantity'] = quantity if conductance: self.settings['conductance']",
"this algorithm operates project : OpenPNM Project object Either a",
"self.settings['phase'] = phase.name if quantity: self.settings['quantity'] = quantity if conductance:",
"if quantity: self.settings['quantity'] = quantity if conductance: self.settings['conductance'] = conductance",
"added to the ``settings`` dictionary of the object. \"\"\" if",
"OpenPNM Phase object The phase on which the algorithm is",
"'gui': {'setup': {'phase': None, 'quantity': '', 'conductance': '', 'charge_conservation': ''},",
"to enforce charge conservation in ionic transport simulations. Parameters ----------",
"takes several arguments that are essential to running the algorithm",
"if phase: self.settings['phase'] = phase.name if quantity: self.settings['quantity'] = quantity",
"'conductance': '', 'charge_conservation': ''}, 'set_rate_BC': {'pores': None, 'values': None}, 'set_value_BC':",
"The name of the physical quantity to be calculated. conductance",
"_charge_conservation_eq_source_term(self, e_alg): # Source term for Poisson or charge conservation",
"``'pore.mole_fraction'``) The name of the physical quantity to be calculated.",
"quantity='', conductance='', charge_conservation=None, **kwargs): r\"\"\" This method takes several arguments",
"Ps = (self['pore.all'] * np.isnan(self['pore.bc_value']) * np.isnan(self['pore.bc_rate'])) mod = gst.charge_conservation",
"is generated. \"\"\" def __init__(self, settings={}, phase=None, **kwargs): def_set =",
": OpenPNM Phase object The phase on which the algorithm",
"the object for easier identification. If not given, one is",
"conductance='', charge_conservation=None, **kwargs): r\"\"\" This method takes several arguments that",
"be specified name : string, optional A unique name to",
"object The phase on which the algorithm is to be",
"by a model attached to a *Physics* object associated with",
"'set_rate_BC': {'pores': None, 'values': None}, 'set_value_BC': {'pores': None, 'values': None},",
"np.isnan(self['pore.bc_rate'])) mod = gst.charge_conservation phys = self.project.find_physics(phase=phase) phys[0].add_model(propname='pore.charge_conservation', model=mod, phase=phase,",
"**kwargs): def_set = {'phase': None, 'quantity': 'pore.potential', 'conductance': 'throat.ionic_conductance', 'charge_conservation':",
"openpnm.algorithms import ReactiveTransport from openpnm.models.physics import generic_source_term as gst from",
"method takes several arguments that are essential to running the",
"the settings. Parameters ---------- phase : OpenPNM Phase object The",
"(default is ``'pore.mole_fraction'``) The name of the physical quantity to",
"the physical quantity to be calculated. conductance : string (default",
"The name of the pore-scale transport conductance values. These are",
"Notes ----- Any additional arguments are added to the ``settings``",
"for easier identification. If not given, one is generated. \"\"\"",
"charge conservation (electroneutrality) eq phase = self.project.phases()[self.settings['phase']] Ps = (self['pore.all']",
"None, 'values': None}, 'set_source': {'pores': None, 'propname': ''} } }",
"phase = self.project.phases()[self.settings['phase']] Ps = (self['pore.all'] * np.isnan(self['pore.bc_value']) * np.isnan(self['pore.bc_rate']))",
"The network on which this algorithm operates project : OpenPNM",
"= gst.charge_conservation phys = self.project.find_physics(phase=phase) phys[0].add_model(propname='pore.charge_conservation', model=mod, phase=phase, p_alg=self, e_alg=e_alg,",
"Parameters ---------- phase : OpenPNM Phase object The phase on",
"typically calculated by a model attached to a *Physics* object",
"run. quantity : string (default is ``'pore.mole_fraction'``) The name of",
"conductance : string (default is ``'throat.diffusive_conductance'``) The name of the",
"'throat.ionic_conductance', 'charge_conservation': 'electroneutrality', 'gui': {'setup': {'phase': None, 'quantity': '', 'conductance':",
"network or a project must be specified name : string,",
"'conductance': 'throat.ionic_conductance', 'charge_conservation': 'electroneutrality', 'gui': {'setup': {'phase': None, 'quantity': '',",
"dictionary of the object. \"\"\" if phase: self.settings['phase'] = phase.name",
"self.settings['quantity'] = quantity if conductance: self.settings['conductance'] = conductance if charge_conservation:",
"object Either a network or a project must be specified",
"one is generated. \"\"\" def __init__(self, settings={}, phase=None, **kwargs): def_set",
"Any additional arguments are added to the ``settings`` dictionary of",
"ChargeConservation(ReactiveTransport): r\"\"\" A class to enforce charge conservation in ionic",
"(default is \"electroneutrality\"). Notes ----- Any additional arguments are added",
"def _charge_conservation_eq_source_term(self, e_alg): # Source term for Poisson or charge",
"None, 'propname': ''} } } super().__init__(**kwargs) self.settings.update(def_set) self.settings.update(settings) if phase",
"These are typically calculated by a model attached to a",
"import generic_source_term as gst from openpnm.utils import logging logger =",
"Network object The network on which this algorithm operates project",
"def_set = {'phase': None, 'quantity': 'pore.potential', 'conductance': 'throat.ionic_conductance', 'charge_conservation': 'electroneutrality',",
"*Physics* object associated with the given *Phase*. charge_conservation : string",
"conservation (electroneutrality) eq phase = self.project.phases()[self.settings['phase']] Ps = (self['pore.all'] *",
"quantity if conductance: self.settings['conductance'] = conductance if charge_conservation: self.settings['charge_conservation'] =",
"from openpnm.models.physics import generic_source_term as gst from openpnm.utils import logging",
"= {'phase': None, 'quantity': 'pore.potential', 'conductance': 'throat.ionic_conductance', 'charge_conservation': 'electroneutrality', 'gui':",
"'charge_conservation': ''}, 'set_rate_BC': {'pores': None, 'values': None}, 'set_value_BC': {'pores': None,",
"them to the settings. Parameters ---------- phase : OpenPNM Phase",
"physical quantity to be calculated. conductance : string (default is",
"Parameters ---------- network : OpenPNM Network object The network on",
"generated. \"\"\" def __init__(self, settings={}, phase=None, **kwargs): def_set = {'phase':",
"charge_conservation : string The assumption adopted to enforce charge conservation",
"ions transport simulations (default is \"electroneutrality\"). Notes ----- Any additional",
"{'phase': None, 'quantity': 'pore.potential', 'conductance': 'throat.ionic_conductance', 'charge_conservation': 'electroneutrality', 'gui': {'setup':",
"eq phase = self.project.phases()[self.settings['phase']] Ps = (self['pore.all'] * np.isnan(self['pore.bc_value']) *",
"setup(self, phase=None, quantity='', conductance='', charge_conservation=None, **kwargs): r\"\"\" This method takes",
"is ``'throat.diffusive_conductance'``) The name of the pore-scale transport conductance values.",
"The assumption adopted to enforce charge conservation when performing ions",
"to give the object for easier identification. If not given,",
"are essential to running the algorithm and adds them to",
"gst from openpnm.utils import logging logger = logging.getLogger(__name__) class ChargeConservation(ReactiveTransport):",
"which this algorithm operates project : OpenPNM Project object Either",
"name : string, optional A unique name to give the",
"__init__(self, settings={}, phase=None, **kwargs): def_set = {'phase': None, 'quantity': 'pore.potential',",
"'set_source': {'pores': None, 'propname': ''} } } super().__init__(**kwargs) self.settings.update(def_set) self.settings.update(settings)",
"phase=None, quantity='', conductance='', charge_conservation=None, **kwargs): r\"\"\" This method takes several",
"of the physical quantity to be calculated. conductance : string",
"----- Any additional arguments are added to the ``settings`` dictionary",
"the ``settings`` dictionary of the object. \"\"\" if phase: self.settings['phase']",
"is \"electroneutrality\"). Notes ----- Any additional arguments are added to",
"a model attached to a *Physics* object associated with the",
"'values': None}, 'set_source': {'pores': None, 'propname': ''} } } super().__init__(**kwargs)",
"\"electroneutrality\"). Notes ----- Any additional arguments are added to the",
"phase : OpenPNM Phase object The phase on which the",
"arguments are added to the ``settings`` dictionary of the object.",
"self.settings['charge_conservation'] = charge_conservation super().setup(**kwargs) def _charge_conservation_eq_source_term(self, e_alg): # Source term",
"to be run. quantity : string (default is ``'pore.mole_fraction'``) The",
"for Poisson or charge conservation (electroneutrality) eq phase = self.project.phases()[self.settings['phase']]",
"settings={}, phase=None, **kwargs): def_set = {'phase': None, 'quantity': 'pore.potential', 'conductance':",
"on which the algorithm is to be run. quantity :",
"of the object. \"\"\" if phase: self.settings['phase'] = phase.name if",
"e_alg): # Source term for Poisson or charge conservation (electroneutrality)",
"term for Poisson or charge conservation (electroneutrality) eq phase =",
"import logging logger = logging.getLogger(__name__) class ChargeConservation(ReactiveTransport): r\"\"\" A class",
"easier identification. If not given, one is generated. \"\"\" def",
"class to enforce charge conservation in ionic transport simulations. Parameters",
"{'pores': None, 'values': None}, 'set_source': {'pores': None, 'propname': ''} }",
"to enforce charge conservation when performing ions transport simulations (default",
"= logging.getLogger(__name__) class ChargeConservation(ReactiveTransport): r\"\"\" A class to enforce charge",
"unique name to give the object for easier identification. If",
"settings. Parameters ---------- phase : OpenPNM Phase object The phase",
"is to be run. quantity : string (default is ``'pore.mole_fraction'``)",
"self.project.phases()[self.settings['phase']] Ps = (self['pore.all'] * np.isnan(self['pore.bc_value']) * np.isnan(self['pore.bc_rate'])) mod =",
"None, 'values': None}, 'set_value_BC': {'pores': None, 'values': None}, 'set_source': {'pores':",
"openpnm.models.physics import generic_source_term as gst from openpnm.utils import logging logger",
"super().__init__(**kwargs) self.settings.update(def_set) self.settings.update(settings) if phase is not None: self.setup(phase=phase) def",
"are typically calculated by a model attached to a *Physics*",
"assumption adopted to enforce charge conservation when performing ions transport",
"``settings`` dictionary of the object. \"\"\" if phase: self.settings['phase'] =",
"adds them to the settings. Parameters ---------- phase : OpenPNM",
"transport simulations. Parameters ---------- network : OpenPNM Network object The",
"import ReactiveTransport from openpnm.models.physics import generic_source_term as gst from openpnm.utils",
"algorithm is to be run. quantity : string (default is",
"---------- network : OpenPNM Network object The network on which",
"identification. If not given, one is generated. \"\"\" def __init__(self,",
"* np.isnan(self['pore.bc_value']) * np.isnan(self['pore.bc_rate'])) mod = gst.charge_conservation phys = self.project.find_physics(phase=phase)",
"phase is not None: self.setup(phase=phase) def setup(self, phase=None, quantity='', conductance='',",
"operates project : OpenPNM Project object Either a network or",
"adopted to enforce charge conservation when performing ions transport simulations",
"string The assumption adopted to enforce charge conservation when performing",
"object. \"\"\" if phase: self.settings['phase'] = phase.name if quantity: self.settings['quantity']",
"charge conservation when performing ions transport simulations (default is \"electroneutrality\").",
"quantity: self.settings['quantity'] = quantity if conductance: self.settings['conductance'] = conductance if",
"} super().__init__(**kwargs) self.settings.update(def_set) self.settings.update(settings) if phase is not None: self.setup(phase=phase)",
"which the algorithm is to be run. quantity : string",
"class ChargeConservation(ReactiveTransport): r\"\"\" A class to enforce charge conservation in",
"= self.project.phases()[self.settings['phase']] Ps = (self['pore.all'] * np.isnan(self['pore.bc_value']) * np.isnan(self['pore.bc_rate'])) mod",
"in ionic transport simulations. Parameters ---------- network : OpenPNM Network",
"(self['pore.all'] * np.isnan(self['pore.bc_value']) * np.isnan(self['pore.bc_rate'])) mod = gst.charge_conservation phys =",
"* np.isnan(self['pore.bc_rate'])) mod = gst.charge_conservation phys = self.project.find_physics(phase=phase) phys[0].add_model(propname='pore.charge_conservation', model=mod,",
"charge_conservation super().setup(**kwargs) def _charge_conservation_eq_source_term(self, e_alg): # Source term for Poisson",
"= self.project.find_physics(phase=phase) phys[0].add_model(propname='pore.charge_conservation', model=mod, phase=phase, p_alg=self, e_alg=e_alg, assumption=self.settings['charge_conservation']) self.set_source(propname='pore.charge_conservation', pores=Ps)",
"Either a network or a project must be specified name",
"be calculated. conductance : string (default is ``'throat.diffusive_conductance'``) The name",
"to a *Physics* object associated with the given *Phase*. charge_conservation",
"'propname': ''} } } super().__init__(**kwargs) self.settings.update(def_set) self.settings.update(settings) if phase is",
"when performing ions transport simulations (default is \"electroneutrality\"). Notes -----",
"charge_conservation=None, **kwargs): r\"\"\" This method takes several arguments that are",
"**kwargs): r\"\"\" This method takes several arguments that are essential",
"that are essential to running the algorithm and adds them",
"pore-scale transport conductance values. These are typically calculated by a",
"as np from openpnm.algorithms import ReactiveTransport from openpnm.models.physics import generic_source_term",
"model attached to a *Physics* object associated with the given",
"self.settings['conductance'] = conductance if charge_conservation: self.settings['charge_conservation'] = charge_conservation super().setup(**kwargs) def",
"given *Phase*. charge_conservation : string The assumption adopted to enforce",
"give the object for easier identification. If not given, one",
"r\"\"\" This method takes several arguments that are essential to",
"from openpnm.algorithms import ReactiveTransport from openpnm.models.physics import generic_source_term as gst",
"ionic transport simulations. Parameters ---------- network : OpenPNM Network object",
"of the pore-scale transport conductance values. These are typically calculated",
"the given *Phase*. charge_conservation : string The assumption adopted to",
"additional arguments are added to the ``settings`` dictionary of the",
"# Source term for Poisson or charge conservation (electroneutrality) eq",
"on which this algorithm operates project : OpenPNM Project object",
"transport simulations (default is \"electroneutrality\"). Notes ----- Any additional arguments",
"network on which this algorithm operates project : OpenPNM Project",
"ReactiveTransport from openpnm.models.physics import generic_source_term as gst from openpnm.utils import",
"is not None: self.setup(phase=phase) def setup(self, phase=None, quantity='', conductance='', charge_conservation=None,",
"'set_value_BC': {'pores': None, 'values': None}, 'set_source': {'pores': None, 'propname': ''}",
"algorithm and adds them to the settings. Parameters ---------- phase",
"''}, 'set_rate_BC': {'pores': None, 'values': None}, 'set_value_BC': {'pores': None, 'values':",
"the algorithm and adds them to the settings. Parameters ----------",
"phase on which the algorithm is to be run. quantity",
": string (default is ``'throat.diffusive_conductance'``) The name of the pore-scale",
"phase.name if quantity: self.settings['quantity'] = quantity if conductance: self.settings['conductance'] =",
"values. These are typically calculated by a model attached to",
"phase=None, **kwargs): def_set = {'phase': None, 'quantity': 'pore.potential', 'conductance': 'throat.ionic_conductance',",
"if charge_conservation: self.settings['charge_conservation'] = charge_conservation super().setup(**kwargs) def _charge_conservation_eq_source_term(self, e_alg): #",
"gst.charge_conservation phys = self.project.find_physics(phase=phase) phys[0].add_model(propname='pore.charge_conservation', model=mod, phase=phase, p_alg=self, e_alg=e_alg, assumption=self.settings['charge_conservation'])",
"'quantity': '', 'conductance': '', 'charge_conservation': ''}, 'set_rate_BC': {'pores': None, 'values':",
": string (default is ``'pore.mole_fraction'``) The name of the physical",
"super().setup(**kwargs) def _charge_conservation_eq_source_term(self, e_alg): # Source term for Poisson or",
"'values': None}, 'set_value_BC': {'pores': None, 'values': None}, 'set_source': {'pores': None,",
"a project must be specified name : string, optional A",
"phase: self.settings['phase'] = phase.name if quantity: self.settings['quantity'] = quantity if",
"to the settings. Parameters ---------- phase : OpenPNM Phase object",
"several arguments that are essential to running the algorithm and",
": string, optional A unique name to give the object"
] |
[
"opt, arg in opts: if opt in (\"-b\",\"--board\"): jno_dict[\"board\"] =",
"import JnoException from jno.commands.command import Command import getopt from colorama",
"board params arg_list.append(\"--board\") arg_list.append(self.formatBoard(jno_dict[\"board\"],jno_dict)) # add port params arg_list.append(\"--port\") arg_list.append(port)",
"will be displayed during upload.\" def run(self,argv,location): jno_dict = interpret_configs()",
"# add board params arg_list.append(\"--board\") arg_list.append(self.formatBoard(jno_dict[\"board\"],jno_dict)) # add port params",
"create_build_directory(jno_dict) arg_list = self.perform_upload(argv,jno_dict) run_arduino_process(arg_list) # Create argument list for",
"uploads to board. Without arguments, uses board/port defined locally/globally. \"",
"help_usage = \"jno upload [-b, --board=] boardname [-p, --ports=] port",
"[-b, --board=] boardname [-p, --ports=] port [-v, --verbose]\" help_description =",
"during upload.\" def run(self,argv,location): jno_dict = interpret_configs() verify_arduino_dir(jno_dict) create_build_directory(jno_dict) arg_list",
"\"DEFAULT\": raise JnoException(\"no ports available\") raise JnoException(\"port does not exist:",
"uses board/port defined locally/globally. \" \\ \"If port is not",
"displayed during upload.\" def run(self,argv,location): jno_dict = interpret_configs() verify_arduino_dir(jno_dict) create_build_directory(jno_dict)",
"if jno_dict[\"port\"] == \"DEFAULT\": raise JnoException(\"no ports available\") raise JnoException(\"port",
"verify_arduino_dir(jno_dict) create_build_directory(jno_dict) arg_list = self.perform_upload(argv,jno_dict) run_arduino_process(arg_list) # Create argument list",
"jno.util import run_arduino_process from jno.util import create_build_directory from jno.util import",
"assemble command query # GOAL: <arduino exec> --upload <script> --board",
"--board=] boardname [-p, --ports=] port [-v, --verbose]\" help_description = \"Runs",
"\\ \"If port is not defined, uses first available port.",
"<serial> arg_list = [jno_dict[\"EXEC_SCRIPT\"]] # add common params - set",
"jno_dict[\"port\"] == \"DEFAULT\": raise JnoException(\"no ports available\") raise JnoException(\"port does",
"getopt.GetoptError as e: raise JnoException(str(e)) for opt, arg in opts:",
"= self.perform_upload(argv,jno_dict) run_arduino_process(arg_list) # Create argument list for arduino build",
"JnoException from jno.commands.command import Command import getopt from colorama import",
"else: if jno_dict[\"port\"] == \"DEFAULT\": print(\"{1}No port provided, using available",
"get_common_parameters from jno.util import verify_arduino_dir from jno.util import verify_and_get_port from",
"jno.util import verify_arduino_dir from jno.util import verify_and_get_port from jno.util import",
"(\"-v\",\"--verbose\"): arg_list.append(\"--verbose\") # verify port or get first available port",
"first available port = verify_and_get_port(jno_dict[\"port\"]) if not port: if jno_dict[\"port\"]",
"uses first available port. With -v, more info will be",
"verify_and_get_port(jno_dict[\"port\"]) if not port: if jno_dict[\"port\"] == \"DEFAULT\": raise JnoException(\"no",
"Upload(Command): help_name = \"Upload\" help_usage = \"jno upload [-b, --board=]",
"<arduino exec> --upload <script> --board <board> --port <serial> arg_list =",
"for arduino build def perform_upload(self,argv,jno_dict): # assemble command query #",
"jno_dict = interpret_configs() verify_arduino_dir(jno_dict) create_build_directory(jno_dict) arg_list = self.perform_upload(argv,jno_dict) run_arduino_process(arg_list) #",
"# Create argument list for arduino build def perform_upload(self,argv,jno_dict): #",
"- set pref arg_list.extend(get_common_parameters(jno_dict)) # add upload params arg_list.append(\"--upload\") arg_list.append(jno_dict[\"SKETCH_INO\"])",
"With -v, more info will be displayed during upload.\" def",
"try: opts,args = getopt.getopt(argv, 'b:p:v',['board=','port=','verbose']) except getopt.GetoptError as e: raise",
"not port: if jno_dict[\"port\"] == \"DEFAULT\": raise JnoException(\"no ports available\")",
"in opts: if opt in (\"-b\",\"--board\"): jno_dict[\"board\"] = arg.strip() elif",
"arg_list.append(\"--board\") arg_list.append(self.formatBoard(jno_dict[\"board\"],jno_dict)) # add port params arg_list.append(\"--port\") arg_list.append(port) return arg_list",
"arg.strip() elif opt in (\"-v\",\"--verbose\"): arg_list.append(\"--verbose\") # verify port or",
"{}\".format(jno_dict[\"port\"])) else: if jno_dict[\"port\"] == \"DEFAULT\": print(\"{1}No port provided, using",
"defined locally/globally. \" \\ \"If port is not defined, uses",
"build def perform_upload(self,argv,jno_dict): # assemble command query # GOAL: <arduino",
"arg_list = [jno_dict[\"EXEC_SCRIPT\"]] # add common params - set pref",
"help_name = \"Upload\" help_usage = \"jno upload [-b, --board=] boardname",
"arg.strip() elif opt in (\"-p\",\"--port\"): jno_dict[\"port\"] = arg.strip() elif opt",
"be displayed during upload.\" def run(self,argv,location): jno_dict = interpret_configs() verify_arduino_dir(jno_dict)",
"= \"jno upload [-b, --board=] boardname [-p, --ports=] port [-v,",
"jno_dict[\"port\"] = arg.strip() elif opt in (\"-v\",\"--verbose\"): arg_list.append(\"--verbose\") # verify",
"= getopt.getopt(argv, 'b:p:v',['board=','port=','verbose']) except getopt.GetoptError as e: raise JnoException(str(e)) for",
"raise JnoException(\"no ports available\") raise JnoException(\"port does not exist: {}\".format(jno_dict[\"port\"]))",
"import verify_arduino_dir from jno.util import verify_and_get_port from jno.util import JnoException",
"port = verify_and_get_port(jno_dict[\"port\"]) if not port: if jno_dict[\"port\"] == \"DEFAULT\":",
"= arg.strip() elif opt in (\"-p\",\"--port\"): jno_dict[\"port\"] = arg.strip() elif",
"pref arg_list.extend(get_common_parameters(jno_dict)) # add upload params arg_list.append(\"--upload\") arg_list.append(jno_dict[\"SKETCH_INO\"]) try: opts,args",
"jno.commands.command import Command import getopt from colorama import Fore class",
"interpret_configs() verify_arduino_dir(jno_dict) create_build_directory(jno_dict) arg_list = self.perform_upload(argv,jno_dict) run_arduino_process(arg_list) # Create argument",
"info will be displayed during upload.\" def run(self,argv,location): jno_dict =",
"[-v, --verbose]\" help_description = \"Runs build and uploads to board.",
"{0}{2}\".format(port,Fore.YELLOW,Fore.RESET)) # add board params arg_list.append(\"--board\") arg_list.append(self.formatBoard(jno_dict[\"board\"],jno_dict)) # add port",
"Command import getopt from colorama import Fore class Upload(Command): help_name",
"ports available\") raise JnoException(\"port does not exist: {}\".format(jno_dict[\"port\"])) else: if",
"not exist: {}\".format(jno_dict[\"port\"])) else: if jno_dict[\"port\"] == \"DEFAULT\": print(\"{1}No port",
"get first available port = verify_and_get_port(jno_dict[\"port\"]) if not port: if",
"GOAL: <arduino exec> --upload <script> --board <board> --port <serial> arg_list",
"\"DEFAULT\": print(\"{1}No port provided, using available port {0}{2}\".format(port,Fore.YELLOW,Fore.RESET)) # add",
"help_description = \"Runs build and uploads to board. Without arguments,",
"# add common params - set pref arg_list.extend(get_common_parameters(jno_dict)) # add",
"exist: {}\".format(jno_dict[\"port\"])) else: if jno_dict[\"port\"] == \"DEFAULT\": print(\"{1}No port provided,",
"jno.util import verify_and_get_port from jno.util import JnoException from jno.commands.command import",
"elif opt in (\"-v\",\"--verbose\"): arg_list.append(\"--verbose\") # verify port or get",
"from jno.util import create_build_directory from jno.util import get_common_parameters from jno.util",
"(\"-p\",\"--port\"): jno_dict[\"port\"] = arg.strip() elif opt in (\"-v\",\"--verbose\"): arg_list.append(\"--verbose\") #",
"interpret_configs from jno.util import run_arduino_process from jno.util import create_build_directory from",
"opt in (\"-v\",\"--verbose\"): arg_list.append(\"--verbose\") # verify port or get first",
"params arg_list.append(\"--board\") arg_list.append(self.formatBoard(jno_dict[\"board\"],jno_dict)) # add port params arg_list.append(\"--port\") arg_list.append(port) return",
"defined, uses first available port. With -v, more info will",
"except getopt.GetoptError as e: raise JnoException(str(e)) for opt, arg in",
"= \"Runs build and uploads to board. Without arguments, uses",
"from colorama import Fore class Upload(Command): help_name = \"Upload\" help_usage",
"perform_upload(self,argv,jno_dict): # assemble command query # GOAL: <arduino exec> --upload",
"argument list for arduino build def perform_upload(self,argv,jno_dict): # assemble command",
"board. Without arguments, uses board/port defined locally/globally. \" \\ \"If",
"verify_arduino_dir from jno.util import verify_and_get_port from jno.util import JnoException from",
"'b:p:v',['board=','port=','verbose']) except getopt.GetoptError as e: raise JnoException(str(e)) for opt, arg",
"available port {0}{2}\".format(port,Fore.YELLOW,Fore.RESET)) # add board params arg_list.append(\"--board\") arg_list.append(self.formatBoard(jno_dict[\"board\"],jno_dict)) #",
"== \"DEFAULT\": raise JnoException(\"no ports available\") raise JnoException(\"port does not",
"using available port {0}{2}\".format(port,Fore.YELLOW,Fore.RESET)) # add board params arg_list.append(\"--board\") arg_list.append(self.formatBoard(jno_dict[\"board\"],jno_dict))",
"if jno_dict[\"port\"] == \"DEFAULT\": print(\"{1}No port provided, using available port",
"JnoException(str(e)) for opt, arg in opts: if opt in (\"-b\",\"--board\"):",
"def run(self,argv,location): jno_dict = interpret_configs() verify_arduino_dir(jno_dict) create_build_directory(jno_dict) arg_list = self.perform_upload(argv,jno_dict)",
"arg_list = self.perform_upload(argv,jno_dict) run_arduino_process(arg_list) # Create argument list for arduino",
"port [-v, --verbose]\" help_description = \"Runs build and uploads to",
"raise JnoException(str(e)) for opt, arg in opts: if opt in",
"arduino build def perform_upload(self,argv,jno_dict): # assemble command query # GOAL:",
"create_build_directory from jno.util import get_common_parameters from jno.util import verify_arduino_dir from",
"in (\"-v\",\"--verbose\"): arg_list.append(\"--verbose\") # verify port or get first available",
"opts: if opt in (\"-b\",\"--board\"): jno_dict[\"board\"] = arg.strip() elif opt",
"getopt.getopt(argv, 'b:p:v',['board=','port=','verbose']) except getopt.GetoptError as e: raise JnoException(str(e)) for opt,",
"arguments, uses board/port defined locally/globally. \" \\ \"If port is",
"print(\"{1}No port provided, using available port {0}{2}\".format(port,Fore.YELLOW,Fore.RESET)) # add board",
"first available port. With -v, more info will be displayed",
"upload params arg_list.append(\"--upload\") arg_list.append(jno_dict[\"SKETCH_INO\"]) try: opts,args = getopt.getopt(argv, 'b:p:v',['board=','port=','verbose']) except",
"import getopt from colorama import Fore class Upload(Command): help_name =",
"from jno.util import verify_arduino_dir from jno.util import verify_and_get_port from jno.util",
"available port. With -v, more info will be displayed during",
"port or get first available port = verify_and_get_port(jno_dict[\"port\"]) if not",
"verify port or get first available port = verify_and_get_port(jno_dict[\"port\"]) if",
"colorama import Fore class Upload(Command): help_name = \"Upload\" help_usage =",
"= interpret_configs() verify_arduino_dir(jno_dict) create_build_directory(jno_dict) arg_list = self.perform_upload(argv,jno_dict) run_arduino_process(arg_list) # Create",
"<board> --port <serial> arg_list = [jno_dict[\"EXEC_SCRIPT\"]] # add common params",
"opt in (\"-p\",\"--port\"): jno_dict[\"port\"] = arg.strip() elif opt in (\"-v\",\"--verbose\"):",
"= arg.strip() elif opt in (\"-v\",\"--verbose\"): arg_list.append(\"--verbose\") # verify port",
"query # GOAL: <arduino exec> --upload <script> --board <board> --port",
"getopt from colorama import Fore class Upload(Command): help_name = \"Upload\"",
"add common params - set pref arg_list.extend(get_common_parameters(jno_dict)) # add upload",
"class Upload(Command): help_name = \"Upload\" help_usage = \"jno upload [-b,",
"board/port defined locally/globally. \" \\ \"If port is not defined,",
"(\"-b\",\"--board\"): jno_dict[\"board\"] = arg.strip() elif opt in (\"-p\",\"--port\"): jno_dict[\"port\"] =",
"jno_dict[\"port\"] == \"DEFAULT\": print(\"{1}No port provided, using available port {0}{2}\".format(port,Fore.YELLOW,Fore.RESET))",
"import Command import getopt from colorama import Fore class Upload(Command):",
"def perform_upload(self,argv,jno_dict): # assemble command query # GOAL: <arduino exec>",
"in (\"-p\",\"--port\"): jno_dict[\"port\"] = arg.strip() elif opt in (\"-v\",\"--verbose\"): arg_list.append(\"--verbose\")",
"# add upload params arg_list.append(\"--upload\") arg_list.append(jno_dict[\"SKETCH_INO\"]) try: opts,args = getopt.getopt(argv,",
"boardname [-p, --ports=] port [-v, --verbose]\" help_description = \"Runs build",
"import create_build_directory from jno.util import get_common_parameters from jno.util import verify_arduino_dir",
"import Fore class Upload(Command): help_name = \"Upload\" help_usage = \"jno",
"= [jno_dict[\"EXEC_SCRIPT\"]] # add common params - set pref arg_list.extend(get_common_parameters(jno_dict))",
"run_arduino_process(arg_list) # Create argument list for arduino build def perform_upload(self,argv,jno_dict):",
"available\") raise JnoException(\"port does not exist: {}\".format(jno_dict[\"port\"])) else: if jno_dict[\"port\"]",
"port is not defined, uses first available port. With -v,",
"JnoException(\"port does not exist: {}\".format(jno_dict[\"port\"])) else: if jno_dict[\"port\"] == \"DEFAULT\":",
"from jno.util import interpret_configs from jno.util import run_arduino_process from jno.util",
"from jno.util import verify_and_get_port from jno.util import JnoException from jno.commands.command",
"more info will be displayed during upload.\" def run(self,argv,location): jno_dict",
"verify_and_get_port from jno.util import JnoException from jno.commands.command import Command import",
"port {0}{2}\".format(port,Fore.YELLOW,Fore.RESET)) # add board params arg_list.append(\"--board\") arg_list.append(self.formatBoard(jno_dict[\"board\"],jno_dict)) # add",
"= \"Upload\" help_usage = \"jno upload [-b, --board=] boardname [-p,",
"jno.util import create_build_directory from jno.util import get_common_parameters from jno.util import",
"== \"DEFAULT\": print(\"{1}No port provided, using available port {0}{2}\".format(port,Fore.YELLOW,Fore.RESET)) #",
"--port <serial> arg_list = [jno_dict[\"EXEC_SCRIPT\"]] # add common params -",
"elif opt in (\"-p\",\"--port\"): jno_dict[\"port\"] = arg.strip() elif opt in",
"[jno_dict[\"EXEC_SCRIPT\"]] # add common params - set pref arg_list.extend(get_common_parameters(jno_dict)) #",
"common params - set pref arg_list.extend(get_common_parameters(jno_dict)) # add upload params",
"--verbose]\" help_description = \"Runs build and uploads to board. Without",
"arg_list.append(\"--upload\") arg_list.append(jno_dict[\"SKETCH_INO\"]) try: opts,args = getopt.getopt(argv, 'b:p:v',['board=','port=','verbose']) except getopt.GetoptError as",
"if opt in (\"-b\",\"--board\"): jno_dict[\"board\"] = arg.strip() elif opt in",
"provided, using available port {0}{2}\".format(port,Fore.YELLOW,Fore.RESET)) # add board params arg_list.append(\"--board\")",
"raise JnoException(\"port does not exist: {}\".format(jno_dict[\"port\"])) else: if jno_dict[\"port\"] ==",
"from jno.util import run_arduino_process from jno.util import create_build_directory from jno.util",
"as e: raise JnoException(str(e)) for opt, arg in opts: if",
"arg_list.append(\"--verbose\") # verify port or get first available port =",
"arg_list.append(jno_dict[\"SKETCH_INO\"]) try: opts,args = getopt.getopt(argv, 'b:p:v',['board=','port=','verbose']) except getopt.GetoptError as e:",
"and uploads to board. Without arguments, uses board/port defined locally/globally.",
"-v, more info will be displayed during upload.\" def run(self,argv,location):",
"<script> --board <board> --port <serial> arg_list = [jno_dict[\"EXEC_SCRIPT\"]] # add",
"params arg_list.append(\"--upload\") arg_list.append(jno_dict[\"SKETCH_INO\"]) try: opts,args = getopt.getopt(argv, 'b:p:v',['board=','port=','verbose']) except getopt.GetoptError",
"in (\"-b\",\"--board\"): jno_dict[\"board\"] = arg.strip() elif opt in (\"-p\",\"--port\"): jno_dict[\"port\"]",
"# verify port or get first available port = verify_and_get_port(jno_dict[\"port\"])",
"import run_arduino_process from jno.util import create_build_directory from jno.util import get_common_parameters",
"jno_dict[\"board\"] = arg.strip() elif opt in (\"-p\",\"--port\"): jno_dict[\"port\"] = arg.strip()",
"available port = verify_and_get_port(jno_dict[\"port\"]) if not port: if jno_dict[\"port\"] ==",
"add board params arg_list.append(\"--board\") arg_list.append(self.formatBoard(jno_dict[\"board\"],jno_dict)) # add port params arg_list.append(\"--port\")",
"exec> --upload <script> --board <board> --port <serial> arg_list = [jno_dict[\"EXEC_SCRIPT\"]]",
"e: raise JnoException(str(e)) for opt, arg in opts: if opt",
"port provided, using available port {0}{2}\".format(port,Fore.YELLOW,Fore.RESET)) # add board params",
"\"Runs build and uploads to board. Without arguments, uses board/port",
"Without arguments, uses board/port defined locally/globally. \" \\ \"If port",
"opt in (\"-b\",\"--board\"): jno_dict[\"board\"] = arg.strip() elif opt in (\"-p\",\"--port\"):",
"--ports=] port [-v, --verbose]\" help_description = \"Runs build and uploads",
"= verify_and_get_port(jno_dict[\"port\"]) if not port: if jno_dict[\"port\"] == \"DEFAULT\": raise",
"import verify_and_get_port from jno.util import JnoException from jno.commands.command import Command",
"opts,args = getopt.getopt(argv, 'b:p:v',['board=','port=','verbose']) except getopt.GetoptError as e: raise JnoException(str(e))",
"port: if jno_dict[\"port\"] == \"DEFAULT\": raise JnoException(\"no ports available\") raise",
"arg in opts: if opt in (\"-b\",\"--board\"): jno_dict[\"board\"] = arg.strip()",
"list for arduino build def perform_upload(self,argv,jno_dict): # assemble command query",
"is not defined, uses first available port. With -v, more",
"--upload <script> --board <board> --port <serial> arg_list = [jno_dict[\"EXEC_SCRIPT\"]] #",
"import get_common_parameters from jno.util import verify_arduino_dir from jno.util import verify_and_get_port",
"Create argument list for arduino build def perform_upload(self,argv,jno_dict): # assemble",
"\"jno upload [-b, --board=] boardname [-p, --ports=] port [-v, --verbose]\"",
"# GOAL: <arduino exec> --upload <script> --board <board> --port <serial>",
"jno.util import JnoException from jno.commands.command import Command import getopt from",
"Fore class Upload(Command): help_name = \"Upload\" help_usage = \"jno upload",
"set pref arg_list.extend(get_common_parameters(jno_dict)) # add upload params arg_list.append(\"--upload\") arg_list.append(jno_dict[\"SKETCH_INO\"]) try:",
"does not exist: {}\".format(jno_dict[\"port\"])) else: if jno_dict[\"port\"] == \"DEFAULT\": print(\"{1}No",
"port. With -v, more info will be displayed during upload.\"",
"upload.\" def run(self,argv,location): jno_dict = interpret_configs() verify_arduino_dir(jno_dict) create_build_directory(jno_dict) arg_list =",
"\" \\ \"If port is not defined, uses first available",
"not defined, uses first available port. With -v, more info",
"# assemble command query # GOAL: <arduino exec> --upload <script>",
"jno.util import interpret_configs from jno.util import run_arduino_process from jno.util import",
"JnoException(\"no ports available\") raise JnoException(\"port does not exist: {}\".format(jno_dict[\"port\"])) else:",
"from jno.util import JnoException from jno.commands.command import Command import getopt",
"if not port: if jno_dict[\"port\"] == \"DEFAULT\": raise JnoException(\"no ports",
"run_arduino_process from jno.util import create_build_directory from jno.util import get_common_parameters from",
"import interpret_configs from jno.util import run_arduino_process from jno.util import create_build_directory",
"or get first available port = verify_and_get_port(jno_dict[\"port\"]) if not port:",
"jno.util import get_common_parameters from jno.util import verify_arduino_dir from jno.util import",
"upload [-b, --board=] boardname [-p, --ports=] port [-v, --verbose]\" help_description",
"locally/globally. \" \\ \"If port is not defined, uses first",
"params - set pref arg_list.extend(get_common_parameters(jno_dict)) # add upload params arg_list.append(\"--upload\")",
"to board. Without arguments, uses board/port defined locally/globally. \" \\",
"[-p, --ports=] port [-v, --verbose]\" help_description = \"Runs build and",
"\"Upload\" help_usage = \"jno upload [-b, --board=] boardname [-p, --ports=]",
"arg_list.extend(get_common_parameters(jno_dict)) # add upload params arg_list.append(\"--upload\") arg_list.append(jno_dict[\"SKETCH_INO\"]) try: opts,args =",
"self.perform_upload(argv,jno_dict) run_arduino_process(arg_list) # Create argument list for arduino build def",
"\"If port is not defined, uses first available port. With",
"command query # GOAL: <arduino exec> --upload <script> --board <board>",
"build and uploads to board. Without arguments, uses board/port defined",
"from jno.util import get_common_parameters from jno.util import verify_arduino_dir from jno.util",
"add upload params arg_list.append(\"--upload\") arg_list.append(jno_dict[\"SKETCH_INO\"]) try: opts,args = getopt.getopt(argv, 'b:p:v',['board=','port=','verbose'])",
"for opt, arg in opts: if opt in (\"-b\",\"--board\"): jno_dict[\"board\"]",
"--board <board> --port <serial> arg_list = [jno_dict[\"EXEC_SCRIPT\"]] # add common",
"from jno.commands.command import Command import getopt from colorama import Fore",
"run(self,argv,location): jno_dict = interpret_configs() verify_arduino_dir(jno_dict) create_build_directory(jno_dict) arg_list = self.perform_upload(argv,jno_dict) run_arduino_process(arg_list)"
] |
[
"'test_out%s.txt' % suffix), 'w') print(eval_output_dir) k = 0 with torch.no_grad():",
"'return_dict': None, 'use_mixed': False, 'use_head': use_head_2, } out2 = self.model2(**args2)",
"return_dict=None, use_mixed=False, use_head_1=0, use_head_2=0, gate_prob=0.5, ): args1 = {'input_ids': input_ids,",
"'encoder_outputs': encoder_outputs_2, 'past_key_values': past_key_values_2, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': output_attentions,",
"} def load_model(path): args = json.load(open(path)) config_class, model_class = BartConfig,",
"Required parameters parser.add_argument( \"--model_type\", default=None, type=str, help=\"base model, used to",
"f_out.close() tokenizer = BartTokenizer.from_pretrained('facebook/bart-large') model = BartModelCombined(model1, model2, config) eval_dataset",
"json.dump({'gate_prob': args.gate_probability}, f_out) f_out.write('\\n') f_out.close() tokenizer = BartTokenizer.from_pretrained('facebook/bart-large') model =",
"torch.FloatTensor = None past_key_values_1: Optional[Tuple[Tuple[torch.FloatTensor]]] = None past_key_values_2: Optional[Tuple[Tuple[torch.FloatTensor]]] =",
"default=None, type=str, required=True, help=\"Evaluation data file to evaluate the perplexity",
"input_attention_mask[j].unsqueeze(0), 'num_beams': 6, 'length_penalty': 2, 'no_repeat_ngram_size': 3, 'max_length': 200, 'min_length':",
"intermediate steps\", ) parser.add_argument(\"--gate_probability\", type=float, default=None, help=\"gate prob\") args =",
"not None and past_2 is not None: decoder_input_ids = decoder_input_ids[:,",
"# Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s -",
"action=\"store_true\", help=\"Overwrite the cached data sets\", ) # custom flags",
"= load_model(args.model_2_config) model2.to(args.device) f_out = open(os.path.join(args.output_dir, 'model_configs.json'), 'w') json.dump(args1, f_out)",
"args1, args2, tokenizer, 'final') logger.info(\"Training/evaluation parameters %s\", args) if __name__",
"help=\"The maximum total decoder sequence length after tokenization.\", ) parser.add_argument(\"--per_gpu_eval_batch_size\",",
"from typing import Dict, Optional, Tuple from torch.utils.data import DataLoader,",
"1 if k > 1000: break f_out.close() def main(): parser",
"\"--max_seq_length\", default=1024, type=int, help=\"The maximum total input sequence length after",
"action=\"store_true\", help=\"Dump posterior probs at intermediate steps\", ) parser.add_argument(\"--gate_probability\", type=float,",
"eval_dataset = train_seq2seq_utils.load_and_cache_examples(args, tokenizer, 'test') evaluate(args, eval_dataset, model, args1, args2,",
"'final') logger.info(\"Training/evaluation parameters %s\", args) if __name__ == \"__main__\": main()",
"use_head_1=0, use_head_2=0, gate_prob=0.5, ): args1 = {'input_ids': input_ids, 'attention_mask': attention_mask,",
"for dev set\", ) parser.add_argument(\"--dump_posteriors\", action=\"store_true\", help=\"Dump posterior probs at",
"config\", ) parser.add_argument( \"--test_data_file\", default=None, type=str, required=True, help=\"Evaluation data file",
"\"past_key_values_2\": past_2, \"decoder_input_ids\": decoder_input_ids, \"attention_mask\": attention_mask, \"head_mask\": head_mask, \"use_cache\": use_cache,",
"parser.add_argument( \"--model_1_config\", default=None, type=str, help=\"Path to model 1 config\", )",
"# cut decoder_input_ids if past is used if past_1 is",
"config = config_class.from_pretrained(args['path']) model = model_class.from_pretrained( args['path'], from_tf=bool(\".ckpt\" in args['path']),",
"argparse.ArgumentParser() # Required parameters parser.add_argument( \"--model_type\", default=None, type=str, help=\"base model,",
"= self.model2(**args2) softmax_1 = torch.exp(out2.logits) softmax_0 = softmax_0 * gate_prob",
"softmax_0 * gate_prob softmax_1 = softmax_1 * (1 - gate_prob)",
"'decoder_start_token_id': tokenizer.bos_token_id, 'num_return_sequences': 1, 'gate_prob': args.gate_probability, 'use_head_1': args1['use_head'], 'use_head_2': args2['use_head']}",
"batch_size=args.eval_batch_size) # Eval! logger.info(\"***** Running evaluation *****\") logger.info(\" Num examples",
"filename=os.path.join(args.output_dir, 'model.log') ) # Set seed model1, args1, config =",
"'top_p': 0.5, 'do_sample': True, 'decoder_start_token_id': tokenizer.bos_token_id, 'num_return_sequences': 1, 'gate_prob': args.gate_probability,",
"f_out = open(os.path.join(eval_output_dir, 'test_out%s.txt' % suffix), 'w') print(eval_output_dir) k =",
"tokenization.\", ) parser.add_argument( \"--max_decoder_length\", default=128, type=int, help=\"The maximum total decoder",
"= DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) # Eval! logger.info(\"***** Running evaluation *****\")",
"Batch size = %d\", args.eval_batch_size) if args.generate: f_out = open(os.path.join(eval_output_dir,",
"ModelOutput from typing import Dict, Optional, Tuple from torch.utils.data import",
"gold = tokenizer.decode(decoder_ids[j], skip_special_tokens=True) input = tokenizer.decode(input_ids[j], skip_special_tokens=True) input_args =",
"= {\"bart_mult_heads_2\": (BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer), } class Seq2SeqLMOutput(ModelOutput): loss: Optional[torch.FloatTensor]",
"= torch.exp(out2.logits) softmax_0 = softmax_0 * gate_prob softmax_1 = softmax_1",
"None, 'use_mixed': False, 'use_head': use_head_2, } out2 = self.model2(**args2) softmax_1",
"Tuple from torch.utils.data import DataLoader, SequentialSampler from transformers.modeling_outputs import Seq2SeqLMOutput",
"past_key_values_1=out1.past_key_values, past_key_values_2=out2.past_key_values) return return_output # unchanged def prepare_inputs_for_generation( self, decoder_input_ids,",
"for j in range(input_ids.shape[0]): gold = tokenizer.decode(decoder_ids[j], skip_special_tokens=True) input =",
"Set seed model1, args1, config = load_model(args.model_1_config) model1.to(args.device) model2, args2,",
"Seq2SeqLMOutput( logits=lm_logits, past_key_values_1=out1.past_key_values, past_key_values_2=out2.past_key_values) return return_output # unchanged def prepare_inputs_for_generation(",
"head_mask=None, use_cache=None, encoder_outputs_1=None, encoder_outputs_2=None, **kwargs ): # cut decoder_input_ids if",
") parser.add_argument(\"--per_gpu_eval_batch_size\", default=32, type=int, help=\"Batch size evaluation.\", ) parser.add_argument(\"--gpu_device\", type=int,",
"device # Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s",
"= logging.getLogger(__name__) MODEL_CLASSES = {\"bart_mult_heads_2\": (BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer), } class",
"% suffix), 'w') print(eval_output_dir) k = 0 with torch.no_grad(): model.eval()",
"help=\"Path to model 1 config\", ) parser.add_argument( \"--model_2_config\", default=None, type=str,",
"args.gate_probability}, f_out) f_out.write('\\n') f_out.close() tokenizer = BartTokenizer.from_pretrained('facebook/bart-large') model = BartModelCombined(model1,",
"at intermediate steps\", ) parser.add_argument(\"--gate_probability\", type=float, default=None, help=\"gate prob\") args",
"defined. input_ids not needed \"encoder_outputs_1\": encoder_outputs_1, \"encoder_outputs_2\": encoder_outputs_2, \"past_key_values_1\": past_1,",
"gen[0] print(gen[0].strip()) f_out.write(input + '\\n') f_out.write(gold + '\\n') for g",
"help=\"The maximum total input sequence length after tokenization.\", ) parser.add_argument(",
"(a text file).\", ) parser.add_argument( \"--output_dir\", default=None, type=str, required=True, help=\"The",
"cross_attn_head_mask, 'encoder_outputs': encoder_outputs_2, 'past_key_values': past_key_values_2, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions':",
"2 config\", ) parser.add_argument( \"--test_data_file\", default=None, type=str, required=True, help=\"Evaluation data",
"be written.\", ) # Other parameters parser.add_argument( \"--max_seq_length\", default=1024, type=int,",
"'\\n') f_out.write('\\n') k += 1 if k > 1000: break",
"model, args1, args2, tokenizer, 'final') logger.info(\"Training/evaluation parameters %s\", args) if",
"gen] # gen = gen[0] print(gen[0].strip()) f_out.write(input + '\\n') f_out.write(gold",
"predictions and checkpoints will be written.\", ) # Other parameters",
"= None past_key_values_1: Optional[Tuple[Tuple[torch.FloatTensor]]] = None past_key_values_2: Optional[Tuple[Tuple[torch.FloatTensor]]] = None",
"200, 'min_length': 12, 'top_k': 30, 'top_p': 0.5, 'do_sample': True, 'decoder_start_token_id':",
"len(eval_dataset)) logger.info(\" Batch size = %d\", args.eval_batch_size) if args.generate: f_out",
"f_out.write(gold + '\\n') for g in gen: f_out.write(g.strip() + '\\n')",
"format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO,",
"import torch from transformers.file_utils import ModelOutput from typing import Dict,",
"input_ids[j].unsqueeze(0), 'attention_mask': input_attention_mask[j].unsqueeze(0), 'num_beams': 6, 'length_penalty': 2, 'no_repeat_ngram_size': 3, 'max_length':",
"'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask, 'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask,",
"not os.path.exists(args.output_dir): os.makedirs(args.output_dir) args.n_gpu = 1 device = torch.device(\"cuda\", args.gpu_device)",
"config = load_model(args.model_1_config) model1.to(args.device) model2, args2, _ = load_model(args.model_2_config) model2.to(args.device)",
"= decoder_input_ids[:, -1:] return { \"input_ids\": None, # encoder_outputs is",
"= torch.exp(out1.logits) args2 = {'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids,",
"logging import os import torch from transformers.file_utils import ModelOutput from",
"Optional[Tuple[Tuple[torch.FloatTensor]]] = None past_key_values_2: Optional[Tuple[Tuple[torch.FloatTensor]]] = None class BartModelCombined(GenerationMixinCustomCombined, nn.Module):",
"args.eval_batch_size) if args.generate: f_out = open(os.path.join(eval_output_dir, 'test_out%s.txt' % suffix), 'w')",
"import GenerationMixinCustomCombined from transformers import ( PreTrainedModel, PreTrainedTokenizer, BartConfig, BartTokenizer",
"logger.info(\" Num examples = %d\", len(eval_dataset)) logger.info(\" Batch size =",
"args.gate_probability, 'use_head_1': args1['use_head'], 'use_head_2': args2['use_head']} gen = model.generate(**input_args) gen =",
"'test') evaluate(args, eval_dataset, model, args1, args2, tokenizer, 'final') logger.info(\"Training/evaluation parameters",
"Optional, Tuple from torch.utils.data import DataLoader, SequentialSampler from transformers.modeling_outputs import",
"Running evaluation *****\") logger.info(\" Num examples = %d\", len(eval_dataset)) logger.info(\"",
"skip_special_tokens=True) input_args = {'input_ids': input_ids[j].unsqueeze(0), 'attention_mask': input_attention_mask[j].unsqueeze(0), 'num_beams': 6, 'length_penalty':",
"if args.generate: f_out = open(os.path.join(eval_output_dir, 'test_out%s.txt' % suffix), 'w') print(eval_output_dir)",
"sequence length after tokenization.\", ) parser.add_argument(\"--per_gpu_eval_batch_size\", default=32, type=int, help=\"Batch size",
"softmax_1) return_output = Seq2SeqLMOutput( logits=lm_logits, past_key_values_1=out1.past_key_values, past_key_values_2=out2.past_key_values) return return_output #",
"Seq2SeqLMOutput import train_seq2seq_utils import single_head_utils import multi_head_utils from torch import",
"gate_prob) lm_logits = torch.log(softmax_0 + softmax_1) return_output = Seq2SeqLMOutput( logits=lm_logits,",
"self, input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs_1=None, encoder_outputs_2=None,",
"*****\") logger.info(\" Num examples = %d\", len(eval_dataset)) logger.info(\" Batch size",
"'min_length': 12, 'top_k': 30, 'top_p': 0.5, 'do_sample': True, 'decoder_start_token_id': tokenizer.bos_token_id,",
"= model_class.from_pretrained( args['path'], from_tf=bool(\".ckpt\" in args['path']), config=config) return model, args,",
"'\\n') f_out.write(gold + '\\n') for g in gen: f_out.write(g.strip() +",
"f_out.write('\\n') json.dump(args2, f_out) f_out.write('\\n') json.dump({'gate_prob': args.gate_probability}, f_out) f_out.write('\\n') f_out.close() tokenizer",
"train_seq2seq_utils.load_and_cache_examples(args, tokenizer, 'test') evaluate(args, eval_dataset, model, args1, args2, tokenizer, 'final')",
"debugging) } def load_model(path): args = json.load(open(path)) config_class, model_class =",
"device\") parser.add_argument(\"--overwrite_cache\", action=\"store_true\", help=\"Overwrite the cached data sets\", ) #",
") parser.add_argument( \"--model_1_config\", default=None, type=str, help=\"Path to model 1 config\",",
"length after tokenization.\", ) parser.add_argument( \"--max_decoder_length\", default=128, type=int, help=\"The maximum",
"from generation_utils_multi_attribute import GenerationMixinCustomCombined from transformers import ( PreTrainedModel, PreTrainedTokenizer,",
"past_key_values_2: Optional[Tuple[Tuple[torch.FloatTensor]]] = None class BartModelCombined(GenerationMixinCustomCombined, nn.Module): def __init__(self, model1,",
"to model 2 config\", ) parser.add_argument( \"--test_data_file\", default=None, type=str, required=True,",
"output_hidden_states, 'return_dict': None, 'use_mixed': False, 'use_head': use_head_2, } out2 =",
"def load_model(path): args = json.load(open(path)) config_class, model_class = BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads",
"= tuple(t.to(args.device) for t in batch) input_ids, input_attention_mask, decoder_ids =",
"'past_key_values': past_key_values_1, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': False, 'output_hidden_states': False,",
"'num_beams': 6, 'length_penalty': 2, 'no_repeat_ngram_size': 3, 'max_length': 200, 'min_length': 12,",
"0 with torch.no_grad(): model.eval() for batch in eval_dataloader: batch =",
"self.device = model2.device def forward( self, input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None,",
"type=int, help=\"The maximum total decoder sequence length after tokenization.\", )",
"default=None, help=\"gate prob\") args = parser.parse_args() if not os.path.exists(args.output_dir): os.makedirs(args.output_dir)",
"if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) args.n_gpu = 1 device = torch.device(\"cuda\",",
"gate_prob=0.5, ): args1 = {'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids,",
"inputs_embeds, 'use_cache': use_cache, 'output_attentions': output_attentions, 'output_hidden_states': output_hidden_states, 'return_dict': None, 'use_mixed':",
"the cached data sets\", ) # custom flags parser.add_argument(\"--generate\", action=\"store_true\",",
"load_model(args.model_1_config) model1.to(args.device) model2, args2, _ = load_model(args.model_2_config) model2.to(args.device) f_out =",
"* gate_prob softmax_1 = softmax_1 * (1 - gate_prob) lm_logits",
"args['path'], from_tf=bool(\".ckpt\" in args['path']), config=config) return model, args, config def",
"'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': output_attentions, 'output_hidden_states': output_hidden_states, 'return_dict': None,",
"'\\n') for g in gen: f_out.write(g.strip() + '\\n') f_out.write('\\n') k",
"from transformers.file_utils import ModelOutput from typing import Dict, Optional, Tuple",
"parser.add_argument(\"--overwrite_cache\", action=\"store_true\", help=\"Overwrite the cached data sets\", ) # custom",
"type=str, help=\"base model, used to load tokenizer\", ) parser.add_argument( \"--model_1_config\",",
"-1:] return { \"input_ids\": None, # encoder_outputs is defined. input_ids",
"parser.add_argument( \"--output_dir\", default=None, type=str, required=True, help=\"The output directory where the",
"# Eval! logger.info(\"***** Running evaluation *****\") logger.info(\" Num examples =",
"BartModelCombined(model1, model2, config) eval_dataset = train_seq2seq_utils.load_and_cache_examples(args, tokenizer, 'test') evaluate(args, eval_dataset,",
"evaluation *****\") logger.info(\" Num examples = %d\", len(eval_dataset)) logger.info(\" Batch",
"\"use_cache\": use_cache, # change this to avoid caching (presumably for",
"directory where the model predictions and checkpoints will be written.\",",
"super().__init__() self.model1 = model1 self.model2 = model2 self.config = config",
"clean_up_tokenization_spaces=True) for g in gen] # gen = gen[0] print(gen[0].strip())",
"%d\", args.eval_batch_size) if args.generate: f_out = open(os.path.join(eval_output_dir, 'test_out%s.txt' % suffix),",
"for g in gen] # gen = gen[0] print(gen[0].strip()) f_out.write(input",
"def __init__(self, model1, model2, config: BartConfig): super().__init__() self.model1 = model1",
"= SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) # Eval! logger.info(\"*****",
"level=logging.INFO, filename=os.path.join(args.output_dir, 'model.log') ) # Set seed model1, args1, config",
"{'input_ids': input_ids[j].unsqueeze(0), 'attention_mask': input_attention_mask[j].unsqueeze(0), 'num_beams': 6, 'length_penalty': 2, 'no_repeat_ngram_size': 3,",
"'w') json.dump(args1, f_out) f_out.write('\\n') json.dump(args2, f_out) f_out.write('\\n') json.dump({'gate_prob': args.gate_probability}, f_out)",
"gate_prob softmax_1 = softmax_1 * (1 - gate_prob) lm_logits =",
"parameters parser.add_argument( \"--model_type\", default=None, type=str, help=\"base model, used to load",
"change this to avoid caching (presumably for debugging) } def",
"%(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO, filename=os.path.join(args.output_dir, 'model.log')",
"use_head_1, } out1 = self.model1(**args1) softmax_0 = torch.exp(out1.logits) args2 =",
"self.config = config self.device = model2.device def forward( self, input_ids=None,",
"head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_2, 'past_key_values': past_key_values_2, 'inputs_embeds':",
"\"head_mask\": head_mask, \"use_cache\": use_cache, # change this to avoid caching",
"'no_repeat_ngram_size': 3, 'max_length': 200, 'min_length': 12, 'top_k': 30, 'top_p': 0.5,",
"transformers.modeling_outputs import Seq2SeqLMOutput import train_seq2seq_utils import single_head_utils import multi_head_utils from",
"attention_mask, 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask, 'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask':",
"written.\", ) # Other parameters parser.add_argument( \"--max_seq_length\", default=1024, type=int, help=\"The",
"multi_head_utils from torch import nn from generation_utils_multi_attribute import GenerationMixinCustomCombined from",
"generation_utils_multi_attribute import GenerationMixinCustomCombined from transformers import ( PreTrainedModel, PreTrainedTokenizer, BartConfig,",
"\"--test_data_file\", default=None, type=str, required=True, help=\"Evaluation data file to evaluate the",
"default=None, type=str, help=\"Path to model 1 config\", ) parser.add_argument( \"--model_2_config\",",
"'encoder_outputs': encoder_outputs_1, 'past_key_values': past_key_values_1, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': False,",
"sequence length after tokenization.\", ) parser.add_argument( \"--max_decoder_length\", default=128, type=int, help=\"The",
"used if past_1 is not None and past_2 is not",
"Seq2SeqLMOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None past_key_values_1:",
"logits=lm_logits, past_key_values_1=out1.past_key_values, past_key_values_2=out2.past_key_values) return return_output # unchanged def prepare_inputs_for_generation( self,",
"parser.add_argument( \"--max_seq_length\", default=1024, type=int, help=\"The maximum total input sequence length",
"def main(): parser = argparse.ArgumentParser() # Required parameters parser.add_argument( \"--model_type\",",
"self.model1(**args1) softmax_0 = torch.exp(out1.logits) args2 = {'input_ids': input_ids, 'attention_mask': attention_mask,",
"= softmax_0 * gate_prob softmax_1 = softmax_1 * (1 -",
"from transformers import ( PreTrainedModel, PreTrainedTokenizer, BartConfig, BartTokenizer ) logger",
") logger = logging.getLogger(__name__) MODEL_CLASSES = {\"bart_mult_heads_2\": (BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer),",
"args2, tokenizer: PreTrainedTokenizer, suffix=\"\") -> Dict: eval_output_dir = args.output_dir if",
"+ '\\n') for g in gen: f_out.write(g.strip() + '\\n') f_out.write('\\n')",
"**kwargs ): # cut decoder_input_ids if past is used if",
"is defined. input_ids not needed \"encoder_outputs_1\": encoder_outputs_1, \"encoder_outputs_2\": encoder_outputs_2, \"past_key_values_1\":",
"= torch.log(softmax_0 + softmax_1) return_output = Seq2SeqLMOutput( logits=lm_logits, past_key_values_1=out1.past_key_values, past_key_values_2=out2.past_key_values)",
"caching (presumably for debugging) } def load_model(path): args = json.load(open(path))",
"use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=None, use_mixed=False, use_head_1=0, use_head_2=0, gate_prob=0.5, ): args1",
"None: decoder_input_ids = decoder_input_ids[:, -1:] return { \"input_ids\": None, #",
"= 1 device = torch.device(\"cuda\", args.gpu_device) args.device = device #",
"output directory where the model predictions and checkpoints will be",
"%H:%M:%S\", level=logging.INFO, filename=os.path.join(args.output_dir, 'model.log') ) # Set seed model1, args1,",
"= None past_key_values_2: Optional[Tuple[Tuple[torch.FloatTensor]]] = None class BartModelCombined(GenerationMixinCustomCombined, nn.Module): def",
"tokenization.\", ) parser.add_argument(\"--per_gpu_eval_batch_size\", default=32, type=int, help=\"Batch size evaluation.\", ) parser.add_argument(\"--gpu_device\",",
"decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_1, 'past_key_values': past_key_values_1, 'inputs_embeds': inputs_embeds, 'use_cache':",
"- gate_prob) lm_logits = torch.log(softmax_0 + softmax_1) return_output = Seq2SeqLMOutput(",
"0.5, 'do_sample': True, 'decoder_start_token_id': tokenizer.bos_token_id, 'num_return_sequences': 1, 'gate_prob': args.gate_probability, 'use_head_1':",
"gen = model.generate(**input_args) gen = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g",
"inputs_embeds=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=None, use_mixed=False, use_head_1=0, use_head_2=0, gate_prob=0.5, ):",
"# Required parameters parser.add_argument( \"--model_type\", default=None, type=str, help=\"base model, used",
"Dict, Optional, Tuple from torch.utils.data import DataLoader, SequentialSampler from transformers.modeling_outputs",
"config self.device = model2.device def forward( self, input_ids=None, attention_mask=None, decoder_input_ids=None,",
"'return_dict': None, 'use_mixed': False, 'use_head': use_head_1, } out1 = self.model1(**args1)",
"\"attention_mask\": attention_mask, \"head_mask\": head_mask, \"use_cache\": use_cache, # change this to",
"config\", ) parser.add_argument( \"--model_2_config\", default=None, type=str, required=True, help=\"Path to model",
"not os.path.exists(eval_output_dir): os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) eval_sampler",
"input_args = {'input_ids': input_ids[j].unsqueeze(0), 'attention_mask': input_attention_mask[j].unsqueeze(0), 'num_beams': 6, 'length_penalty': 2,",
"= {'input_ids': input_ids[j].unsqueeze(0), 'attention_mask': input_attention_mask[j].unsqueeze(0), 'num_beams': 6, 'length_penalty': 2, 'no_repeat_ngram_size':",
"model = model_class.from_pretrained( args['path'], from_tf=bool(\".ckpt\" in args['path']), config=config) return model,",
"Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",",
"import ( PreTrainedModel, PreTrainedTokenizer, BartConfig, BartTokenizer ) logger = logging.getLogger(__name__)",
"): # cut decoder_input_ids if past is used if past_1",
"batch[2] for j in range(input_ids.shape[0]): gold = tokenizer.decode(decoder_ids[j], skip_special_tokens=True) input",
"torch.exp(out1.logits) args2 = {'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask':",
"if past is used if past_1 is not None and",
"default=128, type=int, help=\"The maximum total decoder sequence length after tokenization.\",",
"torch from transformers.file_utils import ModelOutput from typing import Dict, Optional,",
"'model_configs.json'), 'w') json.dump(args1, f_out) f_out.write('\\n') json.dump(args2, f_out) f_out.write('\\n') json.dump({'gate_prob': args.gate_probability},",
"skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in gen] # gen = gen[0]",
"args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader",
") # custom flags parser.add_argument(\"--generate\", action=\"store_true\", help=\"Generate summaries for dev",
"True, 'decoder_start_token_id': tokenizer.bos_token_id, 'num_return_sequences': 1, 'gate_prob': args.gate_probability, 'use_head_1': args1['use_head'], 'use_head_2':",
"past_key_values_1=None, past_key_values_2=None, inputs_embeds=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=None, use_mixed=False, use_head_1=0, use_head_2=0,",
"# custom flags parser.add_argument(\"--generate\", action=\"store_true\", help=\"Generate summaries for dev set\",",
"import logging import os import torch from transformers.file_utils import ModelOutput",
"2, 'no_repeat_ngram_size': 3, 'max_length': 200, 'min_length': 12, 'top_k': 30, 'top_p':",
"model1, args1, config = load_model(args.model_1_config) model1.to(args.device) model2, args2, _ =",
"eval_dataloader: batch = tuple(t.to(args.device) for t in batch) input_ids, input_attention_mask,",
"args['path']), config=config) return model, args, config def evaluate(args, eval_dataset, model:",
"False, 'return_dict': None, 'use_mixed': False, 'use_head': use_head_1, } out1 =",
"parameters parser.add_argument( \"--max_seq_length\", default=1024, type=int, help=\"The maximum total input sequence",
"= train_seq2seq_utils.load_and_cache_examples(args, tokenizer, 'test') evaluate(args, eval_dataset, model, args1, args2, tokenizer,",
"logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\",",
"'model.log') ) # Set seed model1, args1, config = load_model(args.model_1_config)",
"BartConfig): super().__init__() self.model1 = model1 self.model2 = model2 self.config =",
"= model2.device def forward( self, input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None,",
"= args.per_gpu_eval_batch_size * max(1, args.n_gpu) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader =",
"json.dump(args1, f_out) f_out.write('\\n') json.dump(args2, f_out) f_out.write('\\n') json.dump({'gate_prob': args.gate_probability}, f_out) f_out.write('\\n')",
"decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs_1=None, encoder_outputs_2=None, past_key_values_1=None, past_key_values_2=None, inputs_embeds=None,",
"type=str, help=\"Path to model 1 config\", ) parser.add_argument( \"--model_2_config\", default=None,",
"t in batch) input_ids, input_attention_mask, decoder_ids = batch[0], batch[1], batch[2]",
"PreTrainedModel, args1, args2, tokenizer: PreTrainedTokenizer, suffix=\"\") -> Dict: eval_output_dir =",
"for debugging) } def load_model(path): args = json.load(open(path)) config_class, model_class",
"1 config\", ) parser.add_argument( \"--model_2_config\", default=None, type=str, required=True, help=\"Path to",
"suffix=\"\") -> Dict: eval_output_dir = args.output_dir if not os.path.exists(eval_output_dir): os.makedirs(eval_output_dir)",
"if past_1 is not None and past_2 is not None:",
"encoder_outputs_1, 'past_key_values': past_key_values_1, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': False, 'output_hidden_states':",
"self.model1 = model1 self.model2 = model2 self.config = config self.device",
"tokenizer = BartTokenizer.from_pretrained('facebook/bart-large') model = BartModelCombined(model1, model2, config) eval_dataset =",
"'use_head': use_head_2, } out2 = self.model2(**args2) softmax_1 = torch.exp(out2.logits) softmax_0",
"output_hidden_states=False, return_dict=None, use_mixed=False, use_head_1=0, use_head_2=0, gate_prob=0.5, ): args1 = {'input_ids':",
"custom flags parser.add_argument(\"--generate\", action=\"store_true\", help=\"Generate summaries for dev set\", )",
"= None class BartModelCombined(GenerationMixinCustomCombined, nn.Module): def __init__(self, model1, model2, config:",
"= args.output_dir if not os.path.exists(eval_output_dir): os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size *",
"evaluate(args, eval_dataset, model: PreTrainedModel, args1, args2, tokenizer: PreTrainedTokenizer, suffix=\"\") ->",
"dev set\", ) parser.add_argument(\"--dump_posteriors\", action=\"store_true\", help=\"Dump posterior probs at intermediate",
"args.device = device # Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s",
"help=\"Evaluation data file to evaluate the perplexity on (a text",
"os import torch from transformers.file_utils import ModelOutput from typing import",
"train_seq2seq_utils import single_head_utils import multi_head_utils from torch import nn from",
"def forward( self, input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None,",
"for batch in eval_dataloader: batch = tuple(t.to(args.device) for t in",
"on (a text file).\", ) parser.add_argument( \"--output_dir\", default=None, type=str, required=True,",
"if not os.path.exists(eval_output_dir): os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)",
"\"--max_decoder_length\", default=128, type=int, help=\"The maximum total decoder sequence length after",
"maximum total decoder sequence length after tokenization.\", ) parser.add_argument(\"--per_gpu_eval_batch_size\", default=32,",
"type=str, required=True, help=\"The output directory where the model predictions and",
"def evaluate(args, eval_dataset, model: PreTrainedModel, args1, args2, tokenizer: PreTrainedTokenizer, suffix=\"\")",
"= tokenizer.decode(input_ids[j], skip_special_tokens=True) input_args = {'input_ids': input_ids[j].unsqueeze(0), 'attention_mask': input_attention_mask[j].unsqueeze(0), 'num_beams':",
"attention_mask=None, head_mask=None, use_cache=None, encoder_outputs_1=None, encoder_outputs_2=None, **kwargs ): # cut decoder_input_ids",
"'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_2, 'past_key_values': past_key_values_2,",
"encoder_outputs_2=None, past_key_values_1=None, past_key_values_2=None, inputs_embeds=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=None, use_mixed=False, use_head_1=0,",
"input_ids, input_attention_mask, decoder_ids = batch[0], batch[1], batch[2] for j in",
"'use_mixed': False, 'use_head': use_head_2, } out2 = self.model2(**args2) softmax_1 =",
"with torch.no_grad(): model.eval() for batch in eval_dataloader: batch = tuple(t.to(args.device)",
"model2.device def forward( self, input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None,",
"'decoder_attention_mask': decoder_attention_mask, 'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_2,",
"= parser.parse_args() if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) args.n_gpu = 1 device",
"json.dump(args2, f_out) f_out.write('\\n') json.dump({'gate_prob': args.gate_probability}, f_out) f_out.write('\\n') f_out.close() tokenizer =",
"tokenizer\", ) parser.add_argument( \"--model_1_config\", default=None, type=str, help=\"Path to model 1",
"args, config def evaluate(args, eval_dataset, model: PreTrainedModel, args1, args2, tokenizer:",
"gen = gen[0] print(gen[0].strip()) f_out.write(input + '\\n') f_out.write(gold + '\\n')",
"( PreTrainedModel, PreTrainedTokenizer, BartConfig, BartTokenizer ) logger = logging.getLogger(__name__) MODEL_CLASSES",
"output_attentions=False, output_hidden_states=False, return_dict=None, use_mixed=False, use_head_1=0, use_head_2=0, gate_prob=0.5, ): args1 =",
"transformers.file_utils import ModelOutput from typing import Dict, Optional, Tuple from",
") # Set seed model1, args1, config = load_model(args.model_1_config) model1.to(args.device)",
"# change this to avoid caching (presumably for debugging) }",
"softmax_1 = softmax_1 * (1 - gate_prob) lm_logits = torch.log(softmax_0",
"nn from generation_utils_multi_attribute import GenerationMixinCustomCombined from transformers import ( PreTrainedModel,",
"encoder_outputs_2=None, **kwargs ): # cut decoder_input_ids if past is used",
"range(input_ids.shape[0]): gold = tokenizer.decode(decoder_ids[j], skip_special_tokens=True) input = tokenizer.decode(input_ids[j], skip_special_tokens=True) input_args",
"decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs_1=None, encoder_outputs_2=None, past_key_values_1=None, past_key_values_2=None, inputs_embeds=None, use_cache=None, output_attentions=False, output_hidden_states=False,",
"%d\", len(eval_dataset)) logger.info(\" Batch size = %d\", args.eval_batch_size) if args.generate:",
"3, 'max_length': 200, 'min_length': 12, 'top_k': 30, 'top_p': 0.5, 'do_sample':",
"f_out.write('\\n') k += 1 if k > 1000: break f_out.close()",
"torch.utils.data import DataLoader, SequentialSampler from transformers.modeling_outputs import Seq2SeqLMOutput import train_seq2seq_utils",
"# Other parameters parser.add_argument( \"--max_seq_length\", default=1024, type=int, help=\"The maximum total",
"type=str, required=True, help=\"Evaluation data file to evaluate the perplexity on",
"= model1 self.model2 = model2 self.config = config self.device =",
"past_1 is not None and past_2 is not None: decoder_input_ids",
"to model 1 config\", ) parser.add_argument( \"--model_2_config\", default=None, type=str, required=True,",
"{'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask, 'head_mask': head_mask,",
"batch[1], batch[2] for j in range(input_ids.shape[0]): gold = tokenizer.decode(decoder_ids[j], skip_special_tokens=True)",
"PreTrainedTokenizer, BartConfig, BartTokenizer ) logger = logging.getLogger(__name__) MODEL_CLASSES = {\"bart_mult_heads_2\":",
"args1 = {'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask,",
"past is used if past_1 is not None and past_2",
"= model.generate(**input_args) gen = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in",
") parser.add_argument(\"--gate_probability\", type=float, default=None, help=\"gate prob\") args = parser.parse_args() if",
"single_head_utils import multi_head_utils from torch import nn from generation_utils_multi_attribute import",
"'length_penalty': 2, 'no_repeat_ngram_size': 3, 'max_length': 200, 'min_length': 12, 'top_k': 30,",
"+= 1 if k > 1000: break f_out.close() def main():",
"not None: decoder_input_ids = decoder_input_ids[:, -1:] return { \"input_ids\": None,",
"help=\"Path to model 2 config\", ) parser.add_argument( \"--test_data_file\", default=None, type=str,",
"total decoder sequence length after tokenization.\", ) parser.add_argument(\"--per_gpu_eval_batch_size\", default=32, type=int,",
"(1 - gate_prob) lm_logits = torch.log(softmax_0 + softmax_1) return_output =",
"lm_logits = torch.log(softmax_0 + softmax_1) return_output = Seq2SeqLMOutput( logits=lm_logits, past_key_values_1=out1.past_key_values,",
"the model predictions and checkpoints will be written.\", ) #",
"+ '\\n') f_out.write(gold + '\\n') for g in gen: f_out.write(g.strip()",
"BartTokenizer.from_pretrained('facebook/bart-large') model = BartModelCombined(model1, model2, config) eval_dataset = train_seq2seq_utils.load_and_cache_examples(args, tokenizer,",
"None past_key_values_2: Optional[Tuple[Tuple[torch.FloatTensor]]] = None class BartModelCombined(GenerationMixinCustomCombined, nn.Module): def __init__(self,",
"args = parser.parse_args() if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) args.n_gpu = 1",
") parser.add_argument(\"--gpu_device\", type=int, default=0, help=\"gpu device\") parser.add_argument(\"--overwrite_cache\", action=\"store_true\", help=\"Overwrite the",
"avoid caching (presumably for debugging) } def load_model(path): args =",
"use_cache, # change this to avoid caching (presumably for debugging)",
"in gen: f_out.write(g.strip() + '\\n') f_out.write('\\n') k += 1 if",
"import DataLoader, SequentialSampler from transformers.modeling_outputs import Seq2SeqLMOutput import train_seq2seq_utils import",
"30, 'top_p': 0.5, 'do_sample': True, 'decoder_start_token_id': tokenizer.bos_token_id, 'num_return_sequences': 1, 'gate_prob':",
"action=\"store_true\", help=\"Generate summaries for dev set\", ) parser.add_argument(\"--dump_posteriors\", action=\"store_true\", help=\"Dump",
"= [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in gen] # gen",
"forward( self, input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs_1=None,",
"encoder_outputs_2, 'past_key_values': past_key_values_2, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': output_attentions, 'output_hidden_states':",
"softmax_0 = softmax_0 * gate_prob softmax_1 = softmax_1 * (1",
"past_1=None, past_2=None, attention_mask=None, head_mask=None, use_cache=None, encoder_outputs_1=None, encoder_outputs_2=None, **kwargs ): #",
"seed model1, args1, config = load_model(args.model_1_config) model1.to(args.device) model2, args2, _",
"12, 'top_k': 30, 'top_p': 0.5, 'do_sample': True, 'decoder_start_token_id': tokenizer.bos_token_id, 'num_return_sequences':",
"cross_attn_head_mask, 'encoder_outputs': encoder_outputs_1, 'past_key_values': past_key_values_1, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions':",
"default=32, type=int, help=\"Batch size evaluation.\", ) parser.add_argument(\"--gpu_device\", type=int, default=0, help=\"gpu",
"model2, args2, _ = load_model(args.model_2_config) model2.to(args.device) f_out = open(os.path.join(args.output_dir, 'model_configs.json'),",
"model2, config) eval_dataset = train_seq2seq_utils.load_and_cache_examples(args, tokenizer, 'test') evaluate(args, eval_dataset, model,",
"tokenizer, 'final') logger.info(\"Training/evaluation parameters %s\", args) if __name__ == \"__main__\":",
"\"input_ids\": None, # encoder_outputs is defined. input_ids not needed \"encoder_outputs_1\":",
"+ softmax_1) return_output = Seq2SeqLMOutput( logits=lm_logits, past_key_values_1=out1.past_key_values, past_key_values_2=out2.past_key_values) return return_output",
"} out2 = self.model2(**args2) softmax_1 = torch.exp(out2.logits) softmax_0 = softmax_0",
"f_out.write(g.strip() + '\\n') f_out.write('\\n') k += 1 if k >",
"past_2 is not None: decoder_input_ids = decoder_input_ids[:, -1:] return {",
"model 1 config\", ) parser.add_argument( \"--model_2_config\", default=None, type=str, required=True, help=\"Path",
"past_key_values_2=None, inputs_embeds=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=None, use_mixed=False, use_head_1=0, use_head_2=0, gate_prob=0.5,",
"'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_2, 'past_key_values': past_key_values_2, 'inputs_embeds': inputs_embeds,",
"return { \"input_ids\": None, # encoder_outputs is defined. input_ids not",
"main(): parser = argparse.ArgumentParser() # Required parameters parser.add_argument( \"--model_type\", default=None,",
"past_key_values_2, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': output_attentions, 'output_hidden_states': output_hidden_states, 'return_dict':",
"'w') print(eval_output_dir) k = 0 with torch.no_grad(): model.eval() for batch",
"import argparse import json import logging import os import torch",
"= %d\", args.eval_batch_size) if args.generate: f_out = open(os.path.join(eval_output_dir, 'test_out%s.txt' %",
"model 2 config\", ) parser.add_argument( \"--test_data_file\", default=None, type=str, required=True, help=\"Evaluation",
"MODEL_CLASSES = {\"bart_mult_heads_2\": (BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer), } class Seq2SeqLMOutput(ModelOutput): loss:",
"torch.device(\"cuda\", args.gpu_device) args.device = device # Setup logging logging.basicConfig( format=\"%(asctime)s",
"- %(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO, filename=os.path.join(args.output_dir,",
"- %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO, filename=os.path.join(args.output_dir, 'model.log') ) # Set",
"encoder_outputs_1=None, encoder_outputs_2=None, **kwargs ): # cut decoder_input_ids if past is",
"= tokenizer.decode(decoder_ids[j], skip_special_tokens=True) input = tokenizer.decode(input_ids[j], skip_special_tokens=True) input_args = {'input_ids':",
"tokenizer: PreTrainedTokenizer, suffix=\"\") -> Dict: eval_output_dir = args.output_dir if not",
"args.generate: f_out = open(os.path.join(eval_output_dir, 'test_out%s.txt' % suffix), 'w') print(eval_output_dir) k",
"unchanged def prepare_inputs_for_generation( self, decoder_input_ids, past_1=None, past_2=None, attention_mask=None, head_mask=None, use_cache=None,",
"model = BartModelCombined(model1, model2, config) eval_dataset = train_seq2seq_utils.load_and_cache_examples(args, tokenizer, 'test')",
"logger = logging.getLogger(__name__) MODEL_CLASSES = {\"bart_mult_heads_2\": (BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer), }",
"args1, config = load_model(args.model_1_config) model1.to(args.device) model2, args2, _ = load_model(args.model_2_config)",
"torch.no_grad(): model.eval() for batch in eval_dataloader: batch = tuple(t.to(args.device) for",
"use_cache, 'output_attentions': False, 'output_hidden_states': False, 'return_dict': None, 'use_mixed': False, 'use_head':",
"and past_2 is not None: decoder_input_ids = decoder_input_ids[:, -1:] return",
"in eval_dataloader: batch = tuple(t.to(args.device) for t in batch) input_ids,",
"} class Seq2SeqLMOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor =",
"default=1024, type=int, help=\"The maximum total input sequence length after tokenization.\",",
"cached data sets\", ) # custom flags parser.add_argument(\"--generate\", action=\"store_true\", help=\"Generate",
"decoder_attention_mask, 'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_2, 'past_key_values':",
"use_cache, 'output_attentions': output_attentions, 'output_hidden_states': output_hidden_states, 'return_dict': None, 'use_mixed': False, 'use_head':",
"prob\") args = parser.parse_args() if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) args.n_gpu =",
"decoder_input_ids[:, -1:] return { \"input_ids\": None, # encoder_outputs is defined.",
"model predictions and checkpoints will be written.\", ) # Other",
"for g in gen: f_out.write(g.strip() + '\\n') f_out.write('\\n') k +=",
"is not None: decoder_input_ids = decoder_input_ids[:, -1:] return { \"input_ids\":",
"not needed \"encoder_outputs_1\": encoder_outputs_1, \"encoder_outputs_2\": encoder_outputs_2, \"past_key_values_1\": past_1, \"past_key_values_2\": past_2,",
"= config_class.from_pretrained(args['path']) model = model_class.from_pretrained( args['path'], from_tf=bool(\".ckpt\" in args['path']), config=config)",
"* (1 - gate_prob) lm_logits = torch.log(softmax_0 + softmax_1) return_output",
"transformers import ( PreTrainedModel, PreTrainedTokenizer, BartConfig, BartTokenizer ) logger =",
"self.model2(**args2) softmax_1 = torch.exp(out2.logits) softmax_0 = softmax_0 * gate_prob softmax_1",
"decoder_input_ids, \"attention_mask\": attention_mask, \"head_mask\": head_mask, \"use_cache\": use_cache, # change this",
"'output_attentions': False, 'output_hidden_states': False, 'return_dict': None, 'use_mixed': False, 'use_head': use_head_1,",
"to avoid caching (presumably for debugging) } def load_model(path): args",
"will be written.\", ) # Other parameters parser.add_argument( \"--max_seq_length\", default=1024,",
"type=str, required=True, help=\"Path to model 2 config\", ) parser.add_argument( \"--test_data_file\",",
"'use_head_2': args2['use_head']} gen = model.generate(**input_args) gen = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True)",
"config=config) return model, args, config def evaluate(args, eval_dataset, model: PreTrainedModel,",
"argparse import json import logging import os import torch from",
"= BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads config = config_class.from_pretrained(args['path']) model = model_class.from_pretrained( args['path'],",
"steps\", ) parser.add_argument(\"--gate_probability\", type=float, default=None, help=\"gate prob\") args = parser.parse_args()",
"open(os.path.join(eval_output_dir, 'test_out%s.txt' % suffix), 'w') print(eval_output_dir) k = 0 with",
"config) eval_dataset = train_seq2seq_utils.load_and_cache_examples(args, tokenizer, 'test') evaluate(args, eval_dataset, model, args1,",
"eval_dataset, model, args1, args2, tokenizer, 'final') logger.info(\"Training/evaluation parameters %s\", args)",
"- %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO, filename=os.path.join(args.output_dir, 'model.log') )",
"suffix), 'w') print(eval_output_dir) k = 0 with torch.no_grad(): model.eval() for",
"use_head_2, } out2 = self.model2(**args2) softmax_1 = torch.exp(out2.logits) softmax_0 =",
"eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) # Eval! logger.info(\"***** Running evaluation",
"= gen[0] print(gen[0].strip()) f_out.write(input + '\\n') f_out.write(gold + '\\n') for",
"config: BartConfig): super().__init__() self.model1 = model1 self.model2 = model2 self.config",
"tuple(t.to(args.device) for t in batch) input_ids, input_attention_mask, decoder_ids = batch[0],",
"return_output = Seq2SeqLMOutput( logits=lm_logits, past_key_values_1=out1.past_key_values, past_key_values_2=out2.past_key_values) return return_output # unchanged",
"= %d\", len(eval_dataset)) logger.info(\" Batch size = %d\", args.eval_batch_size) if",
"= 0 with torch.no_grad(): model.eval() for batch in eval_dataloader: batch",
"total input sequence length after tokenization.\", ) parser.add_argument( \"--max_decoder_length\", default=128,",
"model2.to(args.device) f_out = open(os.path.join(args.output_dir, 'model_configs.json'), 'w') json.dump(args1, f_out) f_out.write('\\n') json.dump(args2,",
"None past_key_values_1: Optional[Tuple[Tuple[torch.FloatTensor]]] = None past_key_values_2: Optional[Tuple[Tuple[torch.FloatTensor]]] = None class",
"posterior probs at intermediate steps\", ) parser.add_argument(\"--gate_probability\", type=float, default=None, help=\"gate",
"= {'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask, 'head_mask':",
"out1 = self.model1(**args1) softmax_0 = torch.exp(out1.logits) args2 = {'input_ids': input_ids,",
"batch) input_ids, input_attention_mask, decoder_ids = batch[0], batch[1], batch[2] for j",
"'use_head_1': args1['use_head'], 'use_head_2': args2['use_head']} gen = model.generate(**input_args) gen = [tokenizer.decode(g,",
"batch in eval_dataloader: batch = tuple(t.to(args.device) for t in batch)",
"%(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO, filename=os.path.join(args.output_dir, 'model.log') ) # Set seed",
"g in gen] # gen = gen[0] print(gen[0].strip()) f_out.write(input +",
"input_ids, 'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask, 'head_mask': head_mask, 'decoder_head_mask':",
"device = torch.device(\"cuda\", args.gpu_device) args.device = device # Setup logging",
"examples = %d\", len(eval_dataset)) logger.info(\" Batch size = %d\", args.eval_batch_size)",
"decoder_ids = batch[0], batch[1], batch[2] for j in range(input_ids.shape[0]): gold",
"'output_hidden_states': False, 'return_dict': None, 'use_mixed': False, 'use_head': use_head_1, } out1",
"(presumably for debugging) } def load_model(path): args = json.load(open(path)) config_class,",
"tokenizer.decode(input_ids[j], skip_special_tokens=True) input_args = {'input_ids': input_ids[j].unsqueeze(0), 'attention_mask': input_attention_mask[j].unsqueeze(0), 'num_beams': 6,",
"SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) # Eval! logger.info(\"***** Running",
"in batch) input_ids, input_attention_mask, decoder_ids = batch[0], batch[1], batch[2] for",
"nn.Module): def __init__(self, model1, model2, config: BartConfig): super().__init__() self.model1 =",
"decoder_input_ids if past is used if past_1 is not None",
"encoder_outputs is defined. input_ids not needed \"encoder_outputs_1\": encoder_outputs_1, \"encoder_outputs_2\": encoder_outputs_2,",
"1000: break f_out.close() def main(): parser = argparse.ArgumentParser() # Required",
"\"encoder_outputs_1\": encoder_outputs_1, \"encoder_outputs_2\": encoder_outputs_2, \"past_key_values_1\": past_1, \"past_key_values_2\": past_2, \"decoder_input_ids\": decoder_input_ids,",
"Dict: eval_output_dir = args.output_dir if not os.path.exists(eval_output_dir): os.makedirs(eval_output_dir) args.eval_batch_size =",
"evaluate the perplexity on (a text file).\", ) parser.add_argument( \"--output_dir\",",
"multi_head_utils.ConditionalGenerationCustomBartMultHeads config = config_class.from_pretrained(args['path']) model = model_class.from_pretrained( args['path'], from_tf=bool(\".ckpt\" in",
"data sets\", ) # custom flags parser.add_argument(\"--generate\", action=\"store_true\", help=\"Generate summaries",
"import os import torch from transformers.file_utils import ModelOutput from typing",
"file to evaluate the perplexity on (a text file).\", )",
"torch.exp(out2.logits) softmax_0 = softmax_0 * gate_prob softmax_1 = softmax_1 *",
"# unchanged def prepare_inputs_for_generation( self, decoder_input_ids, past_1=None, past_2=None, attention_mask=None, head_mask=None,",
"past_2, \"decoder_input_ids\": decoder_input_ids, \"attention_mask\": attention_mask, \"head_mask\": head_mask, \"use_cache\": use_cache, #",
"None and past_2 is not None: decoder_input_ids = decoder_input_ids[:, -1:]",
"f_out.write('\\n') f_out.close() tokenizer = BartTokenizer.from_pretrained('facebook/bart-large') model = BartModelCombined(model1, model2, config)",
"decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs_1=None, encoder_outputs_2=None, past_key_values_1=None, past_key_values_2=None, inputs_embeds=None, use_cache=None,",
"after tokenization.\", ) parser.add_argument( \"--max_decoder_length\", default=128, type=int, help=\"The maximum total",
"summaries for dev set\", ) parser.add_argument(\"--dump_posteriors\", action=\"store_true\", help=\"Dump posterior probs",
"> 1000: break f_out.close() def main(): parser = argparse.ArgumentParser() #",
"args = json.load(open(path)) config_class, model_class = BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads config =",
"= model2 self.config = config self.device = model2.device def forward(",
"size evaluation.\", ) parser.add_argument(\"--gpu_device\", type=int, default=0, help=\"gpu device\") parser.add_argument(\"--overwrite_cache\", action=\"store_true\",",
"'decoder_attention_mask': decoder_attention_mask, 'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_1,",
"'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_1, 'past_key_values': past_key_values_1, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache,",
"{ \"input_ids\": None, # encoder_outputs is defined. input_ids not needed",
"break f_out.close() def main(): parser = argparse.ArgumentParser() # Required parameters",
"output_attentions, 'output_hidden_states': output_hidden_states, 'return_dict': None, 'use_mixed': False, 'use_head': use_head_2, }",
"return return_output # unchanged def prepare_inputs_for_generation( self, decoder_input_ids, past_1=None, past_2=None,",
"prepare_inputs_for_generation( self, decoder_input_ids, past_1=None, past_2=None, attention_mask=None, head_mask=None, use_cache=None, encoder_outputs_1=None, encoder_outputs_2=None,",
"needed \"encoder_outputs_1\": encoder_outputs_1, \"encoder_outputs_2\": encoder_outputs_2, \"past_key_values_1\": past_1, \"past_key_values_2\": past_2, \"decoder_input_ids\":",
"cut decoder_input_ids if past is used if past_1 is not",
"load_model(args.model_2_config) model2.to(args.device) f_out = open(os.path.join(args.output_dir, 'model_configs.json'), 'w') json.dump(args1, f_out) f_out.write('\\n')",
"past_1, \"past_key_values_2\": past_2, \"decoder_input_ids\": decoder_input_ids, \"attention_mask\": attention_mask, \"head_mask\": head_mask, \"use_cache\":",
"g in gen: f_out.write(g.strip() + '\\n') f_out.write('\\n') k += 1",
"= BartTokenizer.from_pretrained('facebook/bart-large') model = BartModelCombined(model1, model2, config) eval_dataset = train_seq2seq_utils.load_and_cache_examples(args,",
"f_out) f_out.write('\\n') f_out.close() tokenizer = BartTokenizer.from_pretrained('facebook/bart-large') model = BartModelCombined(model1, model2,",
"config def evaluate(args, eval_dataset, model: PreTrainedModel, args1, args2, tokenizer: PreTrainedTokenizer,",
"sampler=eval_sampler, batch_size=args.eval_batch_size) # Eval! logger.info(\"***** Running evaluation *****\") logger.info(\" Num",
"config_class.from_pretrained(args['path']) model = model_class.from_pretrained( args['path'], from_tf=bool(\".ckpt\" in args['path']), config=config) return",
"k > 1000: break f_out.close() def main(): parser = argparse.ArgumentParser()",
"__init__(self, model1, model2, config: BartConfig): super().__init__() self.model1 = model1 self.model2",
"tokenizer, 'test') evaluate(args, eval_dataset, model, args1, args2, tokenizer, 'final') logger.info(\"Training/evaluation",
"config_class, model_class = BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads config = config_class.from_pretrained(args['path']) model =",
"f_out.close() def main(): parser = argparse.ArgumentParser() # Required parameters parser.add_argument(",
"return_output # unchanged def prepare_inputs_for_generation( self, decoder_input_ids, past_1=None, past_2=None, attention_mask=None,",
"# encoder_outputs is defined. input_ids not needed \"encoder_outputs_1\": encoder_outputs_1, \"encoder_outputs_2\":",
"BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads config = config_class.from_pretrained(args['path']) model = model_class.from_pretrained( args['path'], from_tf=bool(\".ckpt\"",
"parser.parse_args() if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) args.n_gpu = 1 device =",
"args2, tokenizer, 'final') logger.info(\"Training/evaluation parameters %s\", args) if __name__ ==",
"is not None and past_2 is not None: decoder_input_ids =",
"False, 'use_head': use_head_1, } out1 = self.model1(**args1) softmax_0 = torch.exp(out1.logits)",
"os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) eval_sampler = SequentialSampler(eval_dataset)",
"parser.add_argument( \"--model_type\", default=None, type=str, help=\"base model, used to load tokenizer\",",
"load tokenizer\", ) parser.add_argument( \"--model_1_config\", default=None, type=str, help=\"Path to model",
"parser.add_argument( \"--test_data_file\", default=None, type=str, required=True, help=\"Evaluation data file to evaluate",
"parser.add_argument(\"--gpu_device\", type=int, default=0, help=\"gpu device\") parser.add_argument(\"--overwrite_cache\", action=\"store_true\", help=\"Overwrite the cached",
"BartModelCombined(GenerationMixinCustomCombined, nn.Module): def __init__(self, model1, model2, config: BartConfig): super().__init__() self.model1",
"cross_attn_head_mask=None, encoder_outputs_1=None, encoder_outputs_2=None, past_key_values_1=None, past_key_values_2=None, inputs_embeds=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=None,",
"'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask, 'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask,",
"= softmax_1 * (1 - gate_prob) lm_logits = torch.log(softmax_0 +",
"model2, config: BartConfig): super().__init__() self.model1 = model1 self.model2 = model2",
"in gen] # gen = gen[0] print(gen[0].strip()) f_out.write(input + '\\n')",
"where the model predictions and checkpoints will be written.\", )",
"parser.add_argument(\"--per_gpu_eval_batch_size\", default=32, type=int, help=\"Batch size evaluation.\", ) parser.add_argument(\"--gpu_device\", type=int, default=0,",
"'gate_prob': args.gate_probability, 'use_head_1': args1['use_head'], 'use_head_2': args2['use_head']} gen = model.generate(**input_args) gen",
"file).\", ) parser.add_argument( \"--output_dir\", default=None, type=str, required=True, help=\"The output directory",
"* max(1, args.n_gpu) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler,",
"1 device = torch.device(\"cuda\", args.gpu_device) args.device = device # Setup",
"encoder_outputs_1=None, encoder_outputs_2=None, past_key_values_1=None, past_key_values_2=None, inputs_embeds=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=None, use_mixed=False,",
"torch.log(softmax_0 + softmax_1) return_output = Seq2SeqLMOutput( logits=lm_logits, past_key_values_1=out1.past_key_values, past_key_values_2=out2.past_key_values) return",
"'use_mixed': False, 'use_head': use_head_1, } out1 = self.model1(**args1) softmax_0 =",
"input_ids not needed \"encoder_outputs_1\": encoder_outputs_1, \"encoder_outputs_2\": encoder_outputs_2, \"past_key_values_1\": past_1, \"past_key_values_2\":",
"help=\"Generate summaries for dev set\", ) parser.add_argument(\"--dump_posteriors\", action=\"store_true\", help=\"Dump posterior",
"os.path.exists(args.output_dir): os.makedirs(args.output_dir) args.n_gpu = 1 device = torch.device(\"cuda\", args.gpu_device) args.device",
"): args1 = {'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask':",
"eval_output_dir = args.output_dir if not os.path.exists(eval_output_dir): os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size",
"= self.model1(**args1) softmax_0 = torch.exp(out1.logits) args2 = {'input_ids': input_ids, 'attention_mask':",
"open(os.path.join(args.output_dir, 'model_configs.json'), 'w') json.dump(args1, f_out) f_out.write('\\n') json.dump(args2, f_out) f_out.write('\\n') json.dump({'gate_prob':",
"\"--model_2_config\", default=None, type=str, required=True, help=\"Path to model 2 config\", )",
"decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_2, 'past_key_values': past_key_values_2, 'inputs_embeds': inputs_embeds, 'use_cache':",
"f_out) f_out.write('\\n') json.dump({'gate_prob': args.gate_probability}, f_out) f_out.write('\\n') f_out.close() tokenizer = BartTokenizer.from_pretrained('facebook/bart-large')",
"= None logits: torch.FloatTensor = None past_key_values_1: Optional[Tuple[Tuple[torch.FloatTensor]]] = None",
") parser.add_argument(\"--dump_posteriors\", action=\"store_true\", help=\"Dump posterior probs at intermediate steps\", )",
"None, 'use_mixed': False, 'use_head': use_head_1, } out1 = self.model1(**args1) softmax_0",
"args2 = {'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids': decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask,",
"model.generate(**input_args) gen = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in gen]",
"import Seq2SeqLMOutput import train_seq2seq_utils import single_head_utils import multi_head_utils from torch",
"if k > 1000: break f_out.close() def main(): parser =",
"use_head_2=0, gate_prob=0.5, ): args1 = {'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids':",
"past_key_values_2=out2.past_key_values) return return_output # unchanged def prepare_inputs_for_generation( self, decoder_input_ids, past_1=None,",
"= Seq2SeqLMOutput( logits=lm_logits, past_key_values_1=out1.past_key_values, past_key_values_2=out2.past_key_values) return return_output # unchanged def",
"decoder_input_ids, 'decoder_attention_mask': decoder_attention_mask, 'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs':",
"for t in batch) input_ids, input_attention_mask, decoder_ids = batch[0], batch[1],",
"past_key_values_1, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': False, 'output_hidden_states': False, 'return_dict':",
"tokenizer.bos_token_id, 'num_return_sequences': 1, 'gate_prob': args.gate_probability, 'use_head_1': args1['use_head'], 'use_head_2': args2['use_head']} gen",
"Other parameters parser.add_argument( \"--max_seq_length\", default=1024, type=int, help=\"The maximum total input",
"type=int, help=\"The maximum total input sequence length after tokenization.\", )",
"max(1, args.n_gpu) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)",
"args1['use_head'], 'use_head_2': args2['use_head']} gen = model.generate(**input_args) gen = [tokenizer.decode(g, skip_special_tokens=True,",
"help=\"gpu device\") parser.add_argument(\"--overwrite_cache\", action=\"store_true\", help=\"Overwrite the cached data sets\", )",
"parser.add_argument(\"--dump_posteriors\", action=\"store_true\", help=\"Dump posterior probs at intermediate steps\", ) parser.add_argument(\"--gate_probability\",",
"return model, args, config def evaluate(args, eval_dataset, model: PreTrainedModel, args1,",
"[tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in gen] # gen =",
"help=\"Batch size evaluation.\", ) parser.add_argument(\"--gpu_device\", type=int, default=0, help=\"gpu device\") parser.add_argument(\"--overwrite_cache\",",
"parser.add_argument(\"--gate_probability\", type=float, default=None, help=\"gate prob\") args = parser.parse_args() if not",
"BartTokenizer), } class Seq2SeqLMOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor",
"= config self.device = model2.device def forward( self, input_ids=None, attention_mask=None,",
"'use_cache': use_cache, 'output_attentions': output_attentions, 'output_hidden_states': output_hidden_states, 'return_dict': None, 'use_mixed': False,",
"help=\"Dump posterior probs at intermediate steps\", ) parser.add_argument(\"--gate_probability\", type=float, default=None,",
"datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO, filename=os.path.join(args.output_dir, 'model.log') ) # Set seed model1,",
"= json.load(open(path)) config_class, model_class = BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads config = config_class.from_pretrained(args['path'])",
"model.eval() for batch in eval_dataloader: batch = tuple(t.to(args.device) for t",
"import train_seq2seq_utils import single_head_utils import multi_head_utils from torch import nn",
"Num examples = %d\", len(eval_dataset)) logger.info(\" Batch size = %d\",",
"None class BartModelCombined(GenerationMixinCustomCombined, nn.Module): def __init__(self, model1, model2, config: BartConfig):",
"eval_dataset, model: PreTrainedModel, args1, args2, tokenizer: PreTrainedTokenizer, suffix=\"\") -> Dict:",
"type=float, default=None, help=\"gate prob\") args = parser.parse_args() if not os.path.exists(args.output_dir):",
"= BartModelCombined(model1, model2, config) eval_dataset = train_seq2seq_utils.load_and_cache_examples(args, tokenizer, 'test') evaluate(args,",
"gen: f_out.write(g.strip() + '\\n') f_out.write('\\n') k += 1 if k",
"from torch import nn from generation_utils_multi_attribute import GenerationMixinCustomCombined from transformers",
"decoder_input_ids = decoder_input_ids[:, -1:] return { \"input_ids\": None, # encoder_outputs",
"in args['path']), config=config) return model, args, config def evaluate(args, eval_dataset,",
"checkpoints will be written.\", ) # Other parameters parser.add_argument( \"--max_seq_length\",",
"import Dict, Optional, Tuple from torch.utils.data import DataLoader, SequentialSampler from",
"os.makedirs(args.output_dir) args.n_gpu = 1 device = torch.device(\"cuda\", args.gpu_device) args.device =",
"'output_attentions': output_attentions, 'output_hidden_states': output_hidden_states, 'return_dict': None, 'use_mixed': False, 'use_head': use_head_2,",
"'do_sample': True, 'decoder_start_token_id': tokenizer.bos_token_id, 'num_return_sequences': 1, 'gate_prob': args.gate_probability, 'use_head_1': args1['use_head'],",
"softmax_1 * (1 - gate_prob) lm_logits = torch.log(softmax_0 + softmax_1)",
"Eval! logger.info(\"***** Running evaluation *****\") logger.info(\" Num examples = %d\",",
"\"past_key_values_1\": past_1, \"past_key_values_2\": past_2, \"decoder_input_ids\": decoder_input_ids, \"attention_mask\": attention_mask, \"head_mask\": head_mask,",
"1, 'gate_prob': args.gate_probability, 'use_head_1': args1['use_head'], 'use_head_2': args2['use_head']} gen = model.generate(**input_args)",
"default=None, type=str, help=\"base model, used to load tokenizer\", ) parser.add_argument(",
"evaluation.\", ) parser.add_argument(\"--gpu_device\", type=int, default=0, help=\"gpu device\") parser.add_argument(\"--overwrite_cache\", action=\"store_true\", help=\"Overwrite",
"to load tokenizer\", ) parser.add_argument( \"--model_1_config\", default=None, type=str, help=\"Path to",
"size = %d\", args.eval_batch_size) if args.generate: f_out = open(os.path.join(eval_output_dir, 'test_out%s.txt'",
"'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_1, 'past_key_values': past_key_values_1,",
"typing import Dict, Optional, Tuple from torch.utils.data import DataLoader, SequentialSampler",
"from transformers.modeling_outputs import Seq2SeqLMOutput import train_seq2seq_utils import single_head_utils import multi_head_utils",
"help=\"Overwrite the cached data sets\", ) # custom flags parser.add_argument(\"--generate\",",
"encoder_outputs_2, \"past_key_values_1\": past_1, \"past_key_values_2\": past_2, \"decoder_input_ids\": decoder_input_ids, \"attention_mask\": attention_mask, \"head_mask\":",
"= load_model(args.model_1_config) model1.to(args.device) model2, args2, _ = load_model(args.model_2_config) model2.to(args.device) f_out",
"'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_2, 'past_key_values': past_key_values_2, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache,",
"help=\"base model, used to load tokenizer\", ) parser.add_argument( \"--model_1_config\", default=None,",
"input_attention_mask, decoder_ids = batch[0], batch[1], batch[2] for j in range(input_ids.shape[0]):",
"%(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO, filename=os.path.join(args.output_dir, 'model.log') ) #",
"import ModelOutput from typing import Dict, Optional, Tuple from torch.utils.data",
"'use_head': use_head_1, } out1 = self.model1(**args1) softmax_0 = torch.exp(out1.logits) args2",
"SequentialSampler from transformers.modeling_outputs import Seq2SeqLMOutput import train_seq2seq_utils import single_head_utils import",
"'output_hidden_states': output_hidden_states, 'return_dict': None, 'use_mixed': False, 'use_head': use_head_2, } out2",
"PreTrainedTokenizer, suffix=\"\") -> Dict: eval_output_dir = args.output_dir if not os.path.exists(eval_output_dir):",
"length after tokenization.\", ) parser.add_argument(\"--per_gpu_eval_batch_size\", default=32, type=int, help=\"Batch size evaluation.\",",
"\"--output_dir\", default=None, type=str, required=True, help=\"The output directory where the model",
"model, used to load tokenizer\", ) parser.add_argument( \"--model_1_config\", default=None, type=str,",
"logger.info(\"***** Running evaluation *****\") logger.info(\" Num examples = %d\", len(eval_dataset))",
"self.model2 = model2 self.config = config self.device = model2.device def",
"default=None, type=str, required=True, help=\"Path to model 2 config\", ) parser.add_argument(",
"use_mixed=False, use_head_1=0, use_head_2=0, gate_prob=0.5, ): args1 = {'input_ids': input_ids, 'attention_mask':",
"data file to evaluate the perplexity on (a text file).\",",
"class BartModelCombined(GenerationMixinCustomCombined, nn.Module): def __init__(self, model1, model2, config: BartConfig): super().__init__()",
"perplexity on (a text file).\", ) parser.add_argument( \"--output_dir\", default=None, type=str,",
"gen = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in gen] #",
"'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_1, 'past_key_values': past_key_values_1, 'inputs_embeds': inputs_embeds,",
"'max_length': 200, 'min_length': 12, 'top_k': 30, 'top_p': 0.5, 'do_sample': True,",
"import json import logging import os import torch from transformers.file_utils",
"k = 0 with torch.no_grad(): model.eval() for batch in eval_dataloader:",
"help=\"The output directory where the model predictions and checkpoints will",
"parser.add_argument( \"--model_2_config\", default=None, type=str, required=True, help=\"Path to model 2 config\",",
"input = tokenizer.decode(input_ids[j], skip_special_tokens=True) input_args = {'input_ids': input_ids[j].unsqueeze(0), 'attention_mask': input_attention_mask[j].unsqueeze(0),",
"help=\"gate prob\") args = parser.parse_args() if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) args.n_gpu",
"type=int, default=0, help=\"gpu device\") parser.add_argument(\"--overwrite_cache\", action=\"store_true\", help=\"Overwrite the cached data",
"model1 self.model2 = model2 self.config = config self.device = model2.device",
"= device # Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s -",
"json.load(open(path)) config_class, model_class = BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads config = config_class.from_pretrained(args['path']) model",
"tokenizer.decode(decoder_ids[j], skip_special_tokens=True) input = tokenizer.decode(input_ids[j], skip_special_tokens=True) input_args = {'input_ids': input_ids[j].unsqueeze(0),",
"text file).\", ) parser.add_argument( \"--output_dir\", default=None, type=str, required=True, help=\"The output",
"multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer), } class Seq2SeqLMOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits:",
"head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs_1=None, encoder_outputs_2=None, past_key_values_1=None, past_key_values_2=None, inputs_embeds=None, use_cache=None, output_attentions=False,",
"import nn from generation_utils_multi_attribute import GenerationMixinCustomCombined from transformers import (",
"= open(os.path.join(eval_output_dir, 'test_out%s.txt' % suffix), 'w') print(eval_output_dir) k = 0",
"-> Dict: eval_output_dir = args.output_dir if not os.path.exists(eval_output_dir): os.makedirs(eval_output_dir) args.eval_batch_size",
"'attention_mask': input_attention_mask[j].unsqueeze(0), 'num_beams': 6, 'length_penalty': 2, 'no_repeat_ngram_size': 3, 'max_length': 200,",
") parser.add_argument( \"--max_decoder_length\", default=128, type=int, help=\"The maximum total decoder sequence",
"in range(input_ids.shape[0]): gold = tokenizer.decode(decoder_ids[j], skip_special_tokens=True) input = tokenizer.decode(input_ids[j], skip_special_tokens=True)",
"and checkpoints will be written.\", ) # Other parameters parser.add_argument(",
"\"--model_1_config\", default=None, type=str, help=\"Path to model 1 config\", ) parser.add_argument(",
"\"decoder_input_ids\": decoder_input_ids, \"attention_mask\": attention_mask, \"head_mask\": head_mask, \"use_cache\": use_cache, # change",
"past_key_values_1: Optional[Tuple[Tuple[torch.FloatTensor]]] = None past_key_values_2: Optional[Tuple[Tuple[torch.FloatTensor]]] = None class BartModelCombined(GenerationMixinCustomCombined,",
"model_class = BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads config = config_class.from_pretrained(args['path']) model = model_class.from_pretrained(",
"args.n_gpu = 1 device = torch.device(\"cuda\", args.gpu_device) args.device = device",
"logger.info(\" Batch size = %d\", args.eval_batch_size) if args.generate: f_out =",
"args2, _ = load_model(args.model_2_config) model2.to(args.device) f_out = open(os.path.join(args.output_dir, 'model_configs.json'), 'w')",
"model, args, config def evaluate(args, eval_dataset, model: PreTrainedModel, args1, args2,",
"(BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer), } class Seq2SeqLMOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None",
"False, 'output_hidden_states': False, 'return_dict': None, 'use_mixed': False, 'use_head': use_head_1, }",
"= argparse.ArgumentParser() # Required parameters parser.add_argument( \"--model_type\", default=None, type=str, help=\"base",
"None logits: torch.FloatTensor = None past_key_values_1: Optional[Tuple[Tuple[torch.FloatTensor]]] = None past_key_values_2:",
"self, decoder_input_ids, past_1=None, past_2=None, attention_mask=None, head_mask=None, use_cache=None, encoder_outputs_1=None, encoder_outputs_2=None, **kwargs",
"sets\", ) # custom flags parser.add_argument(\"--generate\", action=\"store_true\", help=\"Generate summaries for",
"k += 1 if k > 1000: break f_out.close() def",
"the perplexity on (a text file).\", ) parser.add_argument( \"--output_dir\", default=None,",
"eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) # Eval!",
"'num_return_sequences': 1, 'gate_prob': args.gate_probability, 'use_head_1': args1['use_head'], 'use_head_2': args2['use_head']} gen =",
"GenerationMixinCustomCombined from transformers import ( PreTrainedModel, PreTrainedTokenizer, BartConfig, BartTokenizer )",
"DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) # Eval! logger.info(\"***** Running evaluation *****\") logger.info(\"",
"def prepare_inputs_for_generation( self, decoder_input_ids, past_1=None, past_2=None, attention_mask=None, head_mask=None, use_cache=None, encoder_outputs_1=None,",
"evaluate(args, eval_dataset, model, args1, args2, tokenizer, 'final') logger.info(\"Training/evaluation parameters %s\",",
"set\", ) parser.add_argument(\"--dump_posteriors\", action=\"store_true\", help=\"Dump posterior probs at intermediate steps\",",
"after tokenization.\", ) parser.add_argument(\"--per_gpu_eval_batch_size\", default=32, type=int, help=\"Batch size evaluation.\", )",
"past_2=None, attention_mask=None, head_mask=None, use_cache=None, encoder_outputs_1=None, encoder_outputs_2=None, **kwargs ): # cut",
"load_model(path): args = json.load(open(path)) config_class, model_class = BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads config",
"Optional[Tuple[Tuple[torch.FloatTensor]]] = None class BartModelCombined(GenerationMixinCustomCombined, nn.Module): def __init__(self, model1, model2,",
"use_cache=None, encoder_outputs_1=None, encoder_outputs_2=None, **kwargs ): # cut decoder_input_ids if past",
"None, # encoder_outputs is defined. input_ids not needed \"encoder_outputs_1\": encoder_outputs_1,",
"f_out.write(input + '\\n') f_out.write(gold + '\\n') for g in gen:",
") parser.add_argument( \"--test_data_file\", default=None, type=str, required=True, help=\"Evaluation data file to",
"encoder_outputs_1, \"encoder_outputs_2\": encoder_outputs_2, \"past_key_values_1\": past_1, \"past_key_values_2\": past_2, \"decoder_input_ids\": decoder_input_ids, \"attention_mask\":",
"f_out) f_out.write('\\n') json.dump(args2, f_out) f_out.write('\\n') json.dump({'gate_prob': args.gate_probability}, f_out) f_out.write('\\n') f_out.close()",
"logging.getLogger(__name__) MODEL_CLASSES = {\"bart_mult_heads_2\": (BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer), } class Seq2SeqLMOutput(ModelOutput):",
"from torch.utils.data import DataLoader, SequentialSampler from transformers.modeling_outputs import Seq2SeqLMOutput import",
"\"--model_type\", default=None, type=str, help=\"base model, used to load tokenizer\", )",
"BartConfig, BartTokenizer ) logger = logging.getLogger(__name__) MODEL_CLASSES = {\"bart_mult_heads_2\": (BartConfig,",
") parser.add_argument( \"--model_2_config\", default=None, type=str, required=True, help=\"Path to model 2",
"to evaluate the perplexity on (a text file).\", ) parser.add_argument(",
"skip_special_tokens=True) input = tokenizer.decode(input_ids[j], skip_special_tokens=True) input_args = {'input_ids': input_ids[j].unsqueeze(0), 'attention_mask':",
"inputs_embeds, 'use_cache': use_cache, 'output_attentions': False, 'output_hidden_states': False, 'return_dict': None, 'use_mixed':",
"required=True, help=\"The output directory where the model predictions and checkpoints",
") # Other parameters parser.add_argument( \"--max_seq_length\", default=1024, type=int, help=\"The maximum",
"required=True, help=\"Path to model 2 config\", ) parser.add_argument( \"--test_data_file\", default=None,",
"class Seq2SeqLMOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None",
"= batch[0], batch[1], batch[2] for j in range(input_ids.shape[0]): gold =",
"input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs_1=None, encoder_outputs_2=None, past_key_values_1=None,",
") parser.add_argument( \"--output_dir\", default=None, type=str, required=True, help=\"The output directory where",
"from_tf=bool(\".ckpt\" in args['path']), config=config) return model, args, config def evaluate(args,",
"default=0, help=\"gpu device\") parser.add_argument(\"--overwrite_cache\", action=\"store_true\", help=\"Overwrite the cached data sets\",",
"BartTokenizer ) logger = logging.getLogger(__name__) MODEL_CLASSES = {\"bart_mult_heads_2\": (BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads,",
"default=None, type=str, required=True, help=\"The output directory where the model predictions",
"loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None past_key_values_1: Optional[Tuple[Tuple[torch.FloatTensor]]]",
"parser = argparse.ArgumentParser() # Required parameters parser.add_argument( \"--model_type\", default=None, type=str,",
"parser.add_argument( \"--max_decoder_length\", default=128, type=int, help=\"The maximum total decoder sequence length",
"attention_mask, \"head_mask\": head_mask, \"use_cache\": use_cache, # change this to avoid",
"'top_k': 30, 'top_p': 0.5, 'do_sample': True, 'decoder_start_token_id': tokenizer.bos_token_id, 'num_return_sequences': 1,",
"= torch.device(\"cuda\", args.gpu_device) args.device = device # Setup logging logging.basicConfig(",
"print(gen[0].strip()) f_out.write(input + '\\n') f_out.write(gold + '\\n') for g in",
"logits: torch.FloatTensor = None past_key_values_1: Optional[Tuple[Tuple[torch.FloatTensor]]] = None past_key_values_2: Optional[Tuple[Tuple[torch.FloatTensor]]]",
"attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs_1=None, encoder_outputs_2=None, past_key_values_1=None, past_key_values_2=None,",
"\"encoder_outputs_2\": encoder_outputs_2, \"past_key_values_1\": past_1, \"past_key_values_2\": past_2, \"decoder_input_ids\": decoder_input_ids, \"attention_mask\": attention_mask,",
"head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_1, 'past_key_values': past_key_values_1, 'inputs_embeds':",
"model2 self.config = config self.device = model2.device def forward( self,",
"json import logging import os import torch from transformers.file_utils import",
"args.output_dir if not os.path.exists(eval_output_dir): os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1,",
"f_out = open(os.path.join(args.output_dir, 'model_configs.json'), 'w') json.dump(args1, f_out) f_out.write('\\n') json.dump(args2, f_out)",
"args.n_gpu) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) #",
"args.per_gpu_eval_batch_size * max(1, args.n_gpu) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset,",
"# Set seed model1, args1, config = load_model(args.model_1_config) model1.to(args.device) model2,",
"model1.to(args.device) model2, args2, _ = load_model(args.model_2_config) model2.to(args.device) f_out = open(os.path.join(args.output_dir,",
"PreTrainedModel, PreTrainedTokenizer, BartConfig, BartTokenizer ) logger = logging.getLogger(__name__) MODEL_CLASSES =",
"6, 'length_penalty': 2, 'no_repeat_ngram_size': 3, 'max_length': 200, 'min_length': 12, 'top_k':",
"probs at intermediate steps\", ) parser.add_argument(\"--gate_probability\", type=float, default=None, help=\"gate prob\")",
"= open(os.path.join(args.output_dir, 'model_configs.json'), 'w') json.dump(args1, f_out) f_out.write('\\n') json.dump(args2, f_out) f_out.write('\\n')",
"_ = load_model(args.model_2_config) model2.to(args.device) f_out = open(os.path.join(args.output_dir, 'model_configs.json'), 'w') json.dump(args1,",
"head_mask, \"use_cache\": use_cache, # change this to avoid caching (presumably",
"'use_cache': use_cache, 'output_attentions': False, 'output_hidden_states': False, 'return_dict': None, 'use_mixed': False,",
"flags parser.add_argument(\"--generate\", action=\"store_true\", help=\"Generate summaries for dev set\", ) parser.add_argument(\"--dump_posteriors\",",
"out2 = self.model2(**args2) softmax_1 = torch.exp(out2.logits) softmax_0 = softmax_0 *",
"model1, model2, config: BartConfig): super().__init__() self.model1 = model1 self.model2 =",
"softmax_0 = torch.exp(out1.logits) args2 = {'input_ids': input_ids, 'attention_mask': attention_mask, 'decoder_input_ids':",
"maximum total input sequence length after tokenization.\", ) parser.add_argument( \"--max_decoder_length\",",
"input sequence length after tokenization.\", ) parser.add_argument( \"--max_decoder_length\", default=128, type=int,",
"torch import nn from generation_utils_multi_attribute import GenerationMixinCustomCombined from transformers import",
"os.path.exists(eval_output_dir): os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) eval_sampler =",
"this to avoid caching (presumably for debugging) } def load_model(path):",
"decoder_attention_mask, 'head_mask': head_mask, 'decoder_head_mask': decoder_head_mask, 'cross_attn_head_mask': cross_attn_head_mask, 'encoder_outputs': encoder_outputs_1, 'past_key_values':",
"is used if past_1 is not None and past_2 is",
"model_class.from_pretrained( args['path'], from_tf=bool(\".ckpt\" in args['path']), config=config) return model, args, config",
"+ '\\n') f_out.write('\\n') k += 1 if k > 1000:",
"args.gpu_device) args.device = device # Setup logging logging.basicConfig( format=\"%(asctime)s -",
"args1, args2, tokenizer: PreTrainedTokenizer, suffix=\"\") -> Dict: eval_output_dir = args.output_dir",
"} out1 = self.model1(**args1) softmax_0 = torch.exp(out1.logits) args2 = {'input_ids':",
"Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None past_key_values_1: Optional[Tuple[Tuple[torch.FloatTensor]]] =",
"import single_head_utils import multi_head_utils from torch import nn from generation_utils_multi_attribute",
"args2['use_head']} gen = model.generate(**input_args) gen = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for",
"batch[0], batch[1], batch[2] for j in range(input_ids.shape[0]): gold = tokenizer.decode(decoder_ids[j],",
"# gen = gen[0] print(gen[0].strip()) f_out.write(input + '\\n') f_out.write(gold +",
"print(eval_output_dir) k = 0 with torch.no_grad(): model.eval() for batch in",
"'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': False, 'output_hidden_states': False, 'return_dict': None,",
"used to load tokenizer\", ) parser.add_argument( \"--model_1_config\", default=None, type=str, help=\"Path",
"decoder sequence length after tokenization.\", ) parser.add_argument(\"--per_gpu_eval_batch_size\", default=32, type=int, help=\"Batch",
"False, 'use_head': use_head_2, } out2 = self.model2(**args2) softmax_1 = torch.exp(out2.logits)",
"batch = tuple(t.to(args.device) for t in batch) input_ids, input_attention_mask, decoder_ids",
"j in range(input_ids.shape[0]): gold = tokenizer.decode(decoder_ids[j], skip_special_tokens=True) input = tokenizer.decode(input_ids[j],",
"f_out.write('\\n') json.dump({'gate_prob': args.gate_probability}, f_out) f_out.write('\\n') f_out.close() tokenizer = BartTokenizer.from_pretrained('facebook/bart-large') model",
"parser.add_argument(\"--generate\", action=\"store_true\", help=\"Generate summaries for dev set\", ) parser.add_argument(\"--dump_posteriors\", action=\"store_true\",",
"model: PreTrainedModel, args1, args2, tokenizer: PreTrainedTokenizer, suffix=\"\") -> Dict: eval_output_dir",
"import multi_head_utils from torch import nn from generation_utils_multi_attribute import GenerationMixinCustomCombined",
"decoder_input_ids, past_1=None, past_2=None, attention_mask=None, head_mask=None, use_cache=None, encoder_outputs_1=None, encoder_outputs_2=None, **kwargs ):",
"type=int, help=\"Batch size evaluation.\", ) parser.add_argument(\"--gpu_device\", type=int, default=0, help=\"gpu device\")",
"softmax_1 = torch.exp(out2.logits) softmax_0 = softmax_0 * gate_prob softmax_1 =",
"DataLoader, SequentialSampler from transformers.modeling_outputs import Seq2SeqLMOutput import train_seq2seq_utils import single_head_utils",
"'past_key_values': past_key_values_2, 'inputs_embeds': inputs_embeds, 'use_cache': use_cache, 'output_attentions': output_attentions, 'output_hidden_states': output_hidden_states,",
"required=True, help=\"Evaluation data file to evaluate the perplexity on (a",
"{\"bart_mult_heads_2\": (BartConfig, multi_head_utils.ConditionalGenerationCustomBartMultHeads, BartTokenizer), } class Seq2SeqLMOutput(ModelOutput): loss: Optional[torch.FloatTensor] =",
"logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y"
] |