code
stringlengths
13
6.09M
order_type
stringclasses
2 values
original_example
dict
step_ids
listlengths
1
5
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print('hello word!') <|reserved_special_token_1|> import ply.lex as lex print('hello word!') <|reserved_special_token_1|> import ply.lex as lex print("hello word!")
flexible
{ "blob_id": "84d0c439fcee4339250ced11dd2264740cc20d9c", "index": 9567, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('hello word!')\n", "step-3": "import ply.lex as lex\nprint('hello word!')\n", "step-4": "import ply.lex as lex\n\nprint(\"hello word!\")\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from django.db import models from django.db.models.base import Model # Create your models here. class Categoria(models.Model): categoria = models.CharField(max_length=40) def __str__(self): return self.categoria class Producto(models.Model): codigo = models.CharField(max_length=40) nombre = models.CharField(max_length=40) precio = models.IntegerField() stock = models.IntegerField() descripcion = models.CharField(max_length=40) categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE) fecha = models.DateField() imagen = models.ImageField(null=True, blank=True) def __str__(self): return self.nombre class Cliente(models.Model): nombre = models.CharField(max_length=41) paterno = models.CharField(max_length=40) rut = models.CharField(max_length=9) direccion = models.CharField(max_length=40) telefono = models.IntegerField() mail = models.CharField(max_length=100) def __str__(self): return self.nombre class Usuario(models.Model): mail = models.CharField(max_length=100) contraseña = models.CharField(max_length=100) rut = models.ForeignKey(Cliente, on_delete=models.CASCADE) def __str__(self): return self.rut class DetalleVenta(models.Model): tipo_comprovante = models.CharField(max_length=100) serie_comprovante = models.CharField(max_length=7) fecha_comprovante = models.DateField(max_length=100) iva = models.IntegerField() total = models.IntegerField() def __str__(self): return self.serie_comprovante class Descuento(models.Model): codigo_descuento = models.CharField(max_length=7) valor_descuento = models.IntegerField() def __str__(self): return self.codigo_descuento class Venta(models.Model): descripcion = models.CharField(max_length=100) total_venta = models.IntegerField() def __str__(self): return self.total_venta class Sucursal(models.Model): direccion = models.CharField(max_length=100) numero_sucursal = models.IntegerField() def __str__(self): return self.numero_sucursal class Comuna(models.Model): direccion = models.CharField(max_length=100) numero_comuna = models.IntegerField() numero_sucursal = models.ForeignKey(Sucursal, on_delete=models.DO_NOTHING) def __ (self): return self.numero_sucursal class Region(models.Model): direccion = models.CharField(max_length=100) numero_region = models.IntegerField() numero_comuna= models.ForeignKey(Comuna,on_delete=models.DO_NOTHING) def __str__(self): return self.numero_region class Pedido(models.Model): numero_pedido = models.IntegerField() fecha_pedido = models.DateField(max_length=100) iva = models.IntegerField() def __int__(self): return self.numero_pedido class Proveedores(models.Model): nombre_proveedor = models.CharField(max_length=40) direccion = models.CharField(max_length=40) telefono = models.IntegerField() mail = models.CharField(max_length=100) numero_pedido = models.ForeignKey(Pedido, on_delete=models.DO_NOTHING) def __str__(self): return self.nombre_proveedor class Suscripcion(models.Model): fecha_suscripcion = models.DateField valor_suscripcion = models.IntegerField() suscrito = models.IntegerField()
normal
{ "blob_id": "0e19d7251db3382c34ad2d38a7984b65325ecfbf", "index": 7584, "step-1": "<mask token>\n\n\nclass Descuento(models.Model):\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.codigo_descuento\n\n\nclass Venta(models.Model):\n descripcion = models.CharField(max_length=100)\n total_venta = models.IntegerField()\n\n def __str__(self):\n return self.total_venta\n\n\nclass Sucursal(models.Model):\n direccion = models.CharField(max_length=100)\n numero_sucursal = models.IntegerField()\n\n def __str__(self):\n return self.numero_sucursal\n\n\nclass Comuna(models.Model):\n direccion = models.CharField(max_length=100)\n numero_comuna = models.IntegerField()\n numero_sucursal = models.ForeignKey(Sucursal, on_delete=models.DO_NOTHING)\n\n def __(self):\n return self.numero_sucursal\n\n\nclass Region(models.Model):\n direccion = models.CharField(max_length=100)\n numero_region = models.IntegerField()\n numero_comuna = models.ForeignKey(Comuna, on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return self.numero_region\n\n\nclass Pedido(models.Model):\n numero_pedido = models.IntegerField()\n fecha_pedido = models.DateField(max_length=100)\n iva = models.IntegerField()\n\n def __int__(self):\n return self.numero_pedido\n\n\nclass Proveedores(models.Model):\n nombre_proveedor = models.CharField(max_length=40)\n direccion = models.CharField(max_length=40)\n telefono = models.IntegerField()\n mail = models.CharField(max_length=100)\n numero_pedido = models.ForeignKey(Pedido, on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return self.nombre_proveedor\n\n\nclass Suscripcion(models.Model):\n fecha_suscripcion = models.DateField\n valor_suscripcion = models.IntegerField()\n suscrito = models.IntegerField()\n", "step-2": "<mask token>\n\n\nclass Usuario(models.Model):\n mail = models.CharField(max_length=100)\n contraseña = models.CharField(max_length=100)\n rut = models.ForeignKey(Cliente, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.rut\n\n\nclass DetalleVenta(models.Model):\n tipo_comprovante = models.CharField(max_length=100)\n serie_comprovante = models.CharField(max_length=7)\n fecha_comprovante = models.DateField(max_length=100)\n iva = models.IntegerField()\n total = models.IntegerField()\n\n def __str__(self):\n return self.serie_comprovante\n\n\nclass Descuento(models.Model):\n codigo_descuento = models.CharField(max_length=7)\n valor_descuento = models.IntegerField()\n\n def __str__(self):\n return self.codigo_descuento\n\n\nclass Venta(models.Model):\n descripcion = models.CharField(max_length=100)\n total_venta = models.IntegerField()\n\n def __str__(self):\n return self.total_venta\n\n\nclass Sucursal(models.Model):\n direccion = models.CharField(max_length=100)\n numero_sucursal = models.IntegerField()\n\n def __str__(self):\n return self.numero_sucursal\n\n\nclass Comuna(models.Model):\n direccion = models.CharField(max_length=100)\n numero_comuna = models.IntegerField()\n numero_sucursal = models.ForeignKey(Sucursal, on_delete=models.DO_NOTHING)\n\n def __(self):\n return self.numero_sucursal\n\n\nclass Region(models.Model):\n direccion = models.CharField(max_length=100)\n numero_region = models.IntegerField()\n numero_comuna = models.ForeignKey(Comuna, on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return self.numero_region\n\n\nclass Pedido(models.Model):\n numero_pedido = models.IntegerField()\n fecha_pedido = models.DateField(max_length=100)\n iva = models.IntegerField()\n\n def __int__(self):\n return self.numero_pedido\n\n\nclass Proveedores(models.Model):\n nombre_proveedor = models.CharField(max_length=40)\n direccion = models.CharField(max_length=40)\n telefono = models.IntegerField()\n mail = models.CharField(max_length=100)\n numero_pedido = models.ForeignKey(Pedido, on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return self.nombre_proveedor\n\n\nclass Suscripcion(models.Model):\n fecha_suscripcion = models.DateField\n valor_suscripcion = models.IntegerField()\n suscrito = models.IntegerField()\n", "step-3": "<mask token>\n\n\nclass Producto(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Cliente(models.Model):\n nombre = models.CharField(max_length=41)\n paterno = models.CharField(max_length=40)\n rut = models.CharField(max_length=9)\n direccion = models.CharField(max_length=40)\n telefono = models.IntegerField()\n mail = models.CharField(max_length=100)\n\n def __str__(self):\n return self.nombre\n\n\nclass Usuario(models.Model):\n mail = models.CharField(max_length=100)\n contraseña = models.CharField(max_length=100)\n rut = models.ForeignKey(Cliente, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.rut\n\n\nclass DetalleVenta(models.Model):\n tipo_comprovante = models.CharField(max_length=100)\n serie_comprovante = models.CharField(max_length=7)\n fecha_comprovante = models.DateField(max_length=100)\n iva = models.IntegerField()\n total = models.IntegerField()\n\n def __str__(self):\n return self.serie_comprovante\n\n\nclass Descuento(models.Model):\n codigo_descuento = models.CharField(max_length=7)\n valor_descuento = models.IntegerField()\n\n def __str__(self):\n return self.codigo_descuento\n\n\nclass Venta(models.Model):\n descripcion = models.CharField(max_length=100)\n total_venta = models.IntegerField()\n\n def __str__(self):\n return self.total_venta\n\n\nclass Sucursal(models.Model):\n direccion = models.CharField(max_length=100)\n numero_sucursal = models.IntegerField()\n\n def __str__(self):\n return self.numero_sucursal\n\n\nclass Comuna(models.Model):\n direccion = models.CharField(max_length=100)\n numero_comuna = models.IntegerField()\n numero_sucursal = models.ForeignKey(Sucursal, on_delete=models.DO_NOTHING)\n\n def __(self):\n return self.numero_sucursal\n\n\nclass Region(models.Model):\n direccion = models.CharField(max_length=100)\n numero_region = models.IntegerField()\n numero_comuna = models.ForeignKey(Comuna, on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return self.numero_region\n\n\nclass Pedido(models.Model):\n numero_pedido = models.IntegerField()\n fecha_pedido = models.DateField(max_length=100)\n iva = models.IntegerField()\n\n def __int__(self):\n return self.numero_pedido\n\n\nclass Proveedores(models.Model):\n nombre_proveedor = models.CharField(max_length=40)\n direccion = models.CharField(max_length=40)\n telefono = models.IntegerField()\n mail = models.CharField(max_length=100)\n numero_pedido = models.ForeignKey(Pedido, on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return self.nombre_proveedor\n\n\nclass Suscripcion(models.Model):\n fecha_suscripcion = models.DateField\n valor_suscripcion = models.IntegerField()\n suscrito = models.IntegerField()\n", "step-4": "<mask token>\n\n\nclass Producto(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.nombre\n\n\nclass Cliente(models.Model):\n nombre = models.CharField(max_length=41)\n paterno = models.CharField(max_length=40)\n rut = models.CharField(max_length=9)\n direccion = models.CharField(max_length=40)\n telefono = models.IntegerField()\n mail = models.CharField(max_length=100)\n\n def __str__(self):\n return self.nombre\n\n\nclass Usuario(models.Model):\n mail = models.CharField(max_length=100)\n contraseña = models.CharField(max_length=100)\n rut = models.ForeignKey(Cliente, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.rut\n\n\nclass DetalleVenta(models.Model):\n tipo_comprovante = models.CharField(max_length=100)\n serie_comprovante = models.CharField(max_length=7)\n fecha_comprovante = models.DateField(max_length=100)\n iva = models.IntegerField()\n total = models.IntegerField()\n\n def __str__(self):\n return self.serie_comprovante\n\n\nclass Descuento(models.Model):\n codigo_descuento = models.CharField(max_length=7)\n valor_descuento = models.IntegerField()\n\n def __str__(self):\n return self.codigo_descuento\n\n\nclass Venta(models.Model):\n descripcion = models.CharField(max_length=100)\n total_venta = models.IntegerField()\n\n def __str__(self):\n return self.total_venta\n\n\nclass Sucursal(models.Model):\n direccion = models.CharField(max_length=100)\n numero_sucursal = models.IntegerField()\n\n def __str__(self):\n return self.numero_sucursal\n\n\nclass Comuna(models.Model):\n direccion = models.CharField(max_length=100)\n numero_comuna = models.IntegerField()\n numero_sucursal = models.ForeignKey(Sucursal, on_delete=models.DO_NOTHING)\n\n def __(self):\n return self.numero_sucursal\n\n\nclass Region(models.Model):\n direccion = models.CharField(max_length=100)\n numero_region = models.IntegerField()\n numero_comuna = models.ForeignKey(Comuna, on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return self.numero_region\n\n\nclass Pedido(models.Model):\n numero_pedido = models.IntegerField()\n fecha_pedido = models.DateField(max_length=100)\n iva = models.IntegerField()\n\n def __int__(self):\n return self.numero_pedido\n\n\nclass Proveedores(models.Model):\n nombre_proveedor = models.CharField(max_length=40)\n direccion = models.CharField(max_length=40)\n telefono = models.IntegerField()\n mail = models.CharField(max_length=100)\n numero_pedido = models.ForeignKey(Pedido, on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return self.nombre_proveedor\n\n\nclass Suscripcion(models.Model):\n fecha_suscripcion = models.DateField\n valor_suscripcion = models.IntegerField()\n suscrito = models.IntegerField()\n", "step-5": "from django.db import models\nfrom django.db.models.base import Model\n\n# Create your models here.\nclass Categoria(models.Model):\n categoria = models.CharField(max_length=40)\n def __str__(self):\n return self.categoria\n\nclass Producto(models.Model):\n codigo = models.CharField(max_length=40)\n nombre = models.CharField(max_length=40)\n precio = models.IntegerField()\n stock = models.IntegerField()\n descripcion = models.CharField(max_length=40)\n categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE)\n fecha = models.DateField()\n imagen = models.ImageField(null=True, blank=True)\n\n\n\n def __str__(self):\n return self.nombre\n\nclass Cliente(models.Model):\n nombre = models.CharField(max_length=41)\n paterno = models.CharField(max_length=40)\n rut = models.CharField(max_length=9)\n direccion = models.CharField(max_length=40)\n telefono = models.IntegerField()\n mail = models.CharField(max_length=100)\n\n def __str__(self):\n return self.nombre\n\nclass Usuario(models.Model):\n mail = models.CharField(max_length=100)\n contraseña = models.CharField(max_length=100)\n rut = models.ForeignKey(Cliente, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.rut\n\nclass DetalleVenta(models.Model):\n tipo_comprovante = models.CharField(max_length=100)\n serie_comprovante = models.CharField(max_length=7)\n fecha_comprovante = models.DateField(max_length=100)\n iva = models.IntegerField()\n total = models.IntegerField()\n\n def __str__(self):\n return self.serie_comprovante\n \nclass Descuento(models.Model):\n codigo_descuento = models.CharField(max_length=7)\n valor_descuento = models.IntegerField()\n\n def __str__(self):\n return self.codigo_descuento\n\nclass Venta(models.Model):\n descripcion = models.CharField(max_length=100)\n total_venta = models.IntegerField()\n\n def __str__(self):\n return self.total_venta\n\nclass Sucursal(models.Model):\n direccion = models.CharField(max_length=100)\n numero_sucursal = models.IntegerField()\n\n def __str__(self):\n return self.numero_sucursal\n\nclass Comuna(models.Model):\n direccion = models.CharField(max_length=100)\n numero_comuna = models.IntegerField()\n numero_sucursal = models.ForeignKey(Sucursal, on_delete=models.DO_NOTHING)\n \n def __ (self):\n return self.numero_sucursal\n\nclass Region(models.Model):\n direccion = models.CharField(max_length=100)\n numero_region = models.IntegerField()\n numero_comuna= models.ForeignKey(Comuna,on_delete=models.DO_NOTHING)\n\n def __str__(self):\n return self.numero_region\n\nclass Pedido(models.Model):\n numero_pedido = models.IntegerField()\n fecha_pedido = models.DateField(max_length=100)\n iva = models.IntegerField()\n\n def __int__(self):\n return self.numero_pedido\n\n\nclass Proveedores(models.Model):\n nombre_proveedor = models.CharField(max_length=40)\n direccion = models.CharField(max_length=40)\n telefono = models.IntegerField()\n mail = models.CharField(max_length=100)\n numero_pedido = models.ForeignKey(Pedido, on_delete=models.DO_NOTHING)\n \n def __str__(self):\n return self.nombre_proveedor\n\nclass Suscripcion(models.Model):\n fecha_suscripcion = models.DateField\n valor_suscripcion = models.IntegerField()\n suscrito = models.IntegerField()", "step-ids": [ 22, 29, 33, 34, 40 ] }
[ 22, 29, 33, 34, 40 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> if __name__ == '__main__': from numpy.distutils.core import setup setup(name='array-sqrt-openmp', description= 'Illustration of Python extensions using OpenMP', author= 'Mihai Duta', author_email='mihai.duta@it.ox.ac.uk', ext_modules=[ c_array_sqrt, f_array_sqrt]) <|reserved_special_token_1|> <|reserved_special_token_0|> c_array_sqrt = Extension(name='c_array_sqrt_omp', sources=[ './src/c_array_sqrt_omp.c'], extra_compile_args=[ '-O2 -ffast-math -std=c99 -fopenmp'], extra_link_args=['-lgomp']) f_array_sqrt = Extension(name='f_array_sqrt_omp', sources=[ './src/f_array_sqrt_omp.f90'], extra_compile_args=[ '-O2 -ffast-math -fopenmp'], extra_link_args=['-lgomp']) if __name__ == '__main__': from numpy.distutils.core import setup setup(name='array-sqrt-openmp', description= 'Illustration of Python extensions using OpenMP', author= 'Mihai Duta', author_email='mihai.duta@it.ox.ac.uk', ext_modules=[ c_array_sqrt, f_array_sqrt]) <|reserved_special_token_1|> from numpy.distutils.core import Extension c_array_sqrt = Extension(name='c_array_sqrt_omp', sources=[ './src/c_array_sqrt_omp.c'], extra_compile_args=[ '-O2 -ffast-math -std=c99 -fopenmp'], extra_link_args=['-lgomp']) f_array_sqrt = Extension(name='f_array_sqrt_omp', sources=[ './src/f_array_sqrt_omp.f90'], extra_compile_args=[ '-O2 -ffast-math -fopenmp'], extra_link_args=['-lgomp']) if __name__ == '__main__': from numpy.distutils.core import setup setup(name='array-sqrt-openmp', description= 'Illustration of Python extensions using OpenMP', author= 'Mihai Duta', author_email='mihai.duta@it.ox.ac.uk', ext_modules=[ c_array_sqrt, f_array_sqrt]) <|reserved_special_token_1|> # # purpose: setup file to install the compiled-language python libraries # usage: python setup.py config_fc --f90flags="-O2 -fopenmp" install --prefix=$PWD # from numpy.distutils.core import Extension c_array_sqrt = Extension (name = "c_array_sqrt_omp", sources = ["./src/c_array_sqrt_omp.c"], extra_compile_args = ["-O2 -ffast-math -std=c99 -fopenmp"], extra_link_args = ["-lgomp"]) f_array_sqrt = Extension (name = "f_array_sqrt_omp", sources = ["./src/f_array_sqrt_omp.f90"], extra_compile_args = ["-O2 -ffast-math -fopenmp"], extra_link_args = ["-lgomp"]) if __name__ == "__main__": from numpy.distutils.core import setup setup ( name = "array-sqrt-openmp", description = "Illustration of Python extensions using OpenMP", author = "Mihai Duta", author_email = "mihai.duta@it.ox.ac.uk", ext_modules = [c_array_sqrt, f_array_sqrt] ) # end
flexible
{ "blob_id": "c24bf42cfeaa1fb8ac188b9e08146762e0e86fed", "index": 1542, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(name='array-sqrt-openmp', description=\n 'Illustration of Python extensions using OpenMP', author=\n 'Mihai Duta', author_email='mihai.duta@it.ox.ac.uk', ext_modules=[\n c_array_sqrt, f_array_sqrt])\n", "step-3": "<mask token>\nc_array_sqrt = Extension(name='c_array_sqrt_omp', sources=[\n './src/c_array_sqrt_omp.c'], extra_compile_args=[\n '-O2 -ffast-math -std=c99 -fopenmp'], extra_link_args=['-lgomp'])\nf_array_sqrt = Extension(name='f_array_sqrt_omp', sources=[\n './src/f_array_sqrt_omp.f90'], extra_compile_args=[\n '-O2 -ffast-math -fopenmp'], extra_link_args=['-lgomp'])\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(name='array-sqrt-openmp', description=\n 'Illustration of Python extensions using OpenMP', author=\n 'Mihai Duta', author_email='mihai.duta@it.ox.ac.uk', ext_modules=[\n c_array_sqrt, f_array_sqrt])\n", "step-4": "from numpy.distutils.core import Extension\nc_array_sqrt = Extension(name='c_array_sqrt_omp', sources=[\n './src/c_array_sqrt_omp.c'], extra_compile_args=[\n '-O2 -ffast-math -std=c99 -fopenmp'], extra_link_args=['-lgomp'])\nf_array_sqrt = Extension(name='f_array_sqrt_omp', sources=[\n './src/f_array_sqrt_omp.f90'], extra_compile_args=[\n '-O2 -ffast-math -fopenmp'], extra_link_args=['-lgomp'])\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(name='array-sqrt-openmp', description=\n 'Illustration of Python extensions using OpenMP', author=\n 'Mihai Duta', author_email='mihai.duta@it.ox.ac.uk', ext_modules=[\n c_array_sqrt, f_array_sqrt])\n", "step-5": "#\n# purpose: setup file to install the compiled-language python libraries\n# usage: python setup.py config_fc --f90flags=\"-O2 -fopenmp\" install --prefix=$PWD\n#\n\nfrom numpy.distutils.core import Extension\n\nc_array_sqrt = Extension (name = \"c_array_sqrt_omp\",\n sources = [\"./src/c_array_sqrt_omp.c\"],\n extra_compile_args = [\"-O2 -ffast-math -std=c99 -fopenmp\"],\n extra_link_args = [\"-lgomp\"])\n\nf_array_sqrt = Extension (name = \"f_array_sqrt_omp\",\n sources = [\"./src/f_array_sqrt_omp.f90\"],\n extra_compile_args = [\"-O2 -ffast-math -fopenmp\"],\n extra_link_args = [\"-lgomp\"])\n\nif __name__ == \"__main__\":\n from numpy.distutils.core import setup\n setup ( name = \"array-sqrt-openmp\",\n description = \"Illustration of Python extensions using OpenMP\",\n author = \"Mihai Duta\",\n author_email = \"mihai.duta@it.ox.ac.uk\",\n ext_modules = [c_array_sqrt, f_array_sqrt]\n )\n\n# end\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from datetime import datetime from app import db class Vocabulary(db.Model): _id = db.Column(db.Integer, primary_key=True) language = db.Column(db.String(64), index=True) word = db.Column(db.String(64), index=True, unique=True) date = db.Column(db.DateTime, index=True, default=datetime.utcnow)
normal
{ "blob_id": "834469f9c6e065fb29dfe1fd3e421fbb752f5094", "index": 7708, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Vocabulary(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Vocabulary(db.Model):\n _id = db.Column(db.Integer, primary_key=True)\n language = db.Column(db.String(64), index=True)\n word = db.Column(db.String(64), index=True, unique=True)\n date = db.Column(db.DateTime, index=True, default=datetime.utcnow)\n", "step-4": "from datetime import datetime\nfrom app import db\n\n\nclass Vocabulary(db.Model):\n _id = db.Column(db.Integer, primary_key=True)\n language = db.Column(db.String(64), index=True)\n word = db.Column(db.String(64), index=True, unique=True)\n date = db.Column(db.DateTime, index=True, default=datetime.utcnow)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import configparser config = configparser.ConfigParser() config.read('config.ini') settings=config['Settings'] colors=config['Colors'] import logging logger = logging.getLogger(__name__) logLevel = settings.getint('log-level') oneLevelUp = 20 #I don't know if this will work before loading the transformers module? #silence transformers outputs when loading model logging.getLogger("transformers.tokenization_utils").setLevel(logLevel+oneLevelUp) logging.getLogger("transformers.modeling_utils").setLevel(logLevel+oneLevelUp) logging.getLogger("transformers.configuration_utils").setLevel(logLevel+oneLevelUp) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %H:%M%S', level=logLevel+oneLevelUp ) logger.setLevel(logLevel)
normal
{ "blob_id": "e4fb932c476ca0222a077a43499bf9164e1f27d0", "index": 8896, "step-1": "<mask token>\n", "step-2": "<mask token>\nconfig.read('config.ini')\n<mask token>\nlogging.getLogger('transformers.tokenization_utils').setLevel(logLevel +\n oneLevelUp)\nlogging.getLogger('transformers.modeling_utils').setLevel(logLevel + oneLevelUp\n )\nlogging.getLogger('transformers.configuration_utils').setLevel(logLevel +\n oneLevelUp)\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M%S', level=logLevel + oneLevelUp)\nlogger.setLevel(logLevel)\n", "step-3": "<mask token>\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nsettings = config['Settings']\ncolors = config['Colors']\n<mask token>\nlogger = logging.getLogger(__name__)\nlogLevel = settings.getint('log-level')\noneLevelUp = 20\nlogging.getLogger('transformers.tokenization_utils').setLevel(logLevel +\n oneLevelUp)\nlogging.getLogger('transformers.modeling_utils').setLevel(logLevel + oneLevelUp\n )\nlogging.getLogger('transformers.configuration_utils').setLevel(logLevel +\n oneLevelUp)\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M%S', level=logLevel + oneLevelUp)\nlogger.setLevel(logLevel)\n", "step-4": "import configparser\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nsettings = config['Settings']\ncolors = config['Colors']\nimport logging\nlogger = logging.getLogger(__name__)\nlogLevel = settings.getint('log-level')\noneLevelUp = 20\nlogging.getLogger('transformers.tokenization_utils').setLevel(logLevel +\n oneLevelUp)\nlogging.getLogger('transformers.modeling_utils').setLevel(logLevel + oneLevelUp\n )\nlogging.getLogger('transformers.configuration_utils').setLevel(logLevel +\n oneLevelUp)\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M%S', level=logLevel + oneLevelUp)\nlogger.setLevel(logLevel)\n", "step-5": "import configparser\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nsettings=config['Settings']\ncolors=config['Colors']\n\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogLevel = settings.getint('log-level')\noneLevelUp = 20\n\n#I don't know if this will work before loading the transformers module?\n#silence transformers outputs when loading model\nlogging.getLogger(\"transformers.tokenization_utils\").setLevel(logLevel+oneLevelUp)\nlogging.getLogger(\"transformers.modeling_utils\").setLevel(logLevel+oneLevelUp)\nlogging.getLogger(\"transformers.configuration_utils\").setLevel(logLevel+oneLevelUp)\n\nlogging.basicConfig(\n format='%(asctime)s - %(levelname)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M%S',\n level=logLevel+oneLevelUp\n)\nlogger.setLevel(logLevel)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class BaseHandler(webapp2.RequestHandler): @webapp2.cached_property def auth(self): """Shortcut to access the auth instance as a property.""" return auth.get_auth() <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> @webapp2.cached_property def session(self): """Shortcut to access the current session.""" return self.session_store.get_session(backend='datastore') def render_template(self, view_filename, params=None): if not params: params = {} user = self.user_info params['user'] = user path = os.path.join(os.path.dirname(__file__), 'views', view_filename) self.response.out.write(template.render(path, params)) <|reserved_special_token_0|> <|reserved_special_token_0|> def dispatch(self): self.session_store = sessions.get_store(request=self.request) try: webapp2.RequestHandler.dispatch(self) finally: self.session_store.save_sessions(self.response) class MainHandler(BaseHandler): def get(self): user = self.user if not user: self.render_template('about.html') else: params = {'balance': user.balance} self.render_template('home.html', params) class AboutHandler(BaseHandler): def get(self): self.render_template('about.html') class TrendingHandler(BaseHandler): def get(self): self.render_template('trending.html') class TipHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): failed = False user = self.user tipReceiver = self.request.get('tipReceiver') tipReceiver = self.user_model.get_by_auth_id(tipReceiver) amount = self.request.get('tip') amount = float(amount) try: tip.tip(user, tipReceiver, amount) except: failed = True self._serve_page(failed) def _serve_page(self, failed=False): params = {'failed': failed} self.render_template('tip.html', params) <|reserved_special_token_0|> class AddCreditsHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): user = self.user credits = self.request.get('credits') credits = float(credits) user.balance += credits user.put() serve_profile_page(self) def _serve_page(self): user = self.user params = {} self.render_template('add_credits.html', params) class LogHandler(BaseHandler): @user_required def get(self): user = self.user keys = tip.TipTransactionLogShardConfig.all_keys(user) logs = keys[0].get() if logs: message = {'logs': logs.logs} else: message = None self.send_json(message) class ProfileHandler(BaseHandler): @user_required def get(self): serve_profile_page(self) class SignupHandler(BaseHandler): def get(self): self.render_template('signup.html') def post(self): user_name = self.request.get('username') email = self.request.get('email') name = self.request.get('name') password = self.request.get('password') last_name = self.request.get('lastname') unique_properties = ['email_address'] user_data = self.user_model.create_user(user_name, unique_properties, email_address=email, name=name, password_raw =password, last_name=last_name, balance=float(0), tip_log_count =0, verified=False) if not user_data[0]: self.display_message( 'Unable to create user for email %s because of duplicate keys %s' % (user_name, user_data[1])) return user = user_data[1] user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='v', user_id= user_id, signup_token=token, _full=True) msg = ( 'Send an email to user in order to verify their address. They will be able to do so by visiting <a href="{url}">{url}</a>' ) self.display_message(msg.format(url=verification_url)) class ForgotPasswordHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') user = self.user_model.get_by_auth_id(username) if not user: logging.info('Could not find any user entry for username %s', username) self._serve_page(not_found=True) return user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='p', user_id= user_id, signup_token=token, _full=True) msg = ( 'Send an email to user in order to reset their password. They will be able to do so by visiting <a href="{url}">{url}</a>' ) self.display_message(msg.format(url=verification_url)) def _serve_page(self, not_found=False): username = self.request.get('username') params = {'username': username, 'not_found': not_found} self.render_template('forgot.html', params) class VerificationHandler(BaseHandler): def get(self, *args, **kwargs): user = None user_id = kwargs['user_id'] signup_token = kwargs['signup_token'] verification_type = kwargs['type'] user, ts = self.user_model.get_by_auth_token(int(user_id), signup_token, 'signup') if not user: logging.info( 'Could not find any user with id "%s" signup token "%s"', user_id, signup_token) self.abort(404) self.auth.set_session(self.auth.store.user_to_dict(user), remember=True ) if verification_type == 'v': self.user_model.delete_signup_token(user.get_id(), signup_token) if not user.verified: user.verified = True user.put() self.display_message('User email address has been verified.') return elif verification_type == 'p': params = {'user': user, 'token': signup_token} self.render_template('resetpassword.html', params) else: logging.info('verification type not supported') self.abort(404) class SetPasswordHandler(BaseHandler): @user_required def post(self): password = self.request.get('password') old_token = self.request.get('t') if not password or password != self.request.get('confirm_password'): self.display_message('passwords do not match') return user = self.user user.set_password(password) user.put() self.user_model.delete_signup_token(user.get_id(), old_token) self.display_message('Password updated') class LoginHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') password = self.request.get('password') try: u = self.auth.get_user_by_password(username, password, remember =True, save_session=True) user = self.user tip.coalesce_balance(user) self.redirect(self.uri_for('home')) except (InvalidAuthIdError, InvalidPasswordError) as e: logging.info('Login failed for user %s because of %s', username, type(e)) self._serve_page(True) def _serve_page(self, failed=False): username = self.request.get('username') params = {'username': username, 'failed': failed} self.render_template('login.html', params) class LogoutHandler(BaseHandler): def get(self): self.auth.unset_session() self.redirect(self.uri_for('home')) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class BaseHandler(webapp2.RequestHandler): @webapp2.cached_property def auth(self): """Shortcut to access the auth instance as a property.""" return auth.get_auth() <|reserved_special_token_0|> @webapp2.cached_property def user(self): """Shortcut to access the current logged in user. Unlike user_info, it fetches information from the persistence layer and returns an instance of the underlying model. :returns The instance of the user model associated to the logged in user. """ u = self.user_info return self.user_model.get_by_id(u['user_id']) if u else None <|reserved_special_token_0|> @webapp2.cached_property def session(self): """Shortcut to access the current session.""" return self.session_store.get_session(backend='datastore') def render_template(self, view_filename, params=None): if not params: params = {} user = self.user_info params['user'] = user path = os.path.join(os.path.dirname(__file__), 'views', view_filename) self.response.out.write(template.render(path, params)) <|reserved_special_token_0|> def display_message(self, message): """Utility function to display a template with a simple message.""" params = {'message': message} self.render_template('message.html', params) def dispatch(self): self.session_store = sessions.get_store(request=self.request) try: webapp2.RequestHandler.dispatch(self) finally: self.session_store.save_sessions(self.response) class MainHandler(BaseHandler): def get(self): user = self.user if not user: self.render_template('about.html') else: params = {'balance': user.balance} self.render_template('home.html', params) class AboutHandler(BaseHandler): def get(self): self.render_template('about.html') class TrendingHandler(BaseHandler): def get(self): self.render_template('trending.html') class TipHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): failed = False user = self.user tipReceiver = self.request.get('tipReceiver') tipReceiver = self.user_model.get_by_auth_id(tipReceiver) amount = self.request.get('tip') amount = float(amount) try: tip.tip(user, tipReceiver, amount) except: failed = True self._serve_page(failed) def _serve_page(self, failed=False): params = {'failed': failed} self.render_template('tip.html', params) <|reserved_special_token_0|> class AddCreditsHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): user = self.user credits = self.request.get('credits') credits = float(credits) user.balance += credits user.put() serve_profile_page(self) def _serve_page(self): user = self.user params = {} self.render_template('add_credits.html', params) class LogHandler(BaseHandler): @user_required def get(self): user = self.user keys = tip.TipTransactionLogShardConfig.all_keys(user) logs = keys[0].get() if logs: message = {'logs': logs.logs} else: message = None self.send_json(message) class ProfileHandler(BaseHandler): @user_required def get(self): serve_profile_page(self) class SignupHandler(BaseHandler): def get(self): self.render_template('signup.html') def post(self): user_name = self.request.get('username') email = self.request.get('email') name = self.request.get('name') password = self.request.get('password') last_name = self.request.get('lastname') unique_properties = ['email_address'] user_data = self.user_model.create_user(user_name, unique_properties, email_address=email, name=name, password_raw =password, last_name=last_name, balance=float(0), tip_log_count =0, verified=False) if not user_data[0]: self.display_message( 'Unable to create user for email %s because of duplicate keys %s' % (user_name, user_data[1])) return user = user_data[1] user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='v', user_id= user_id, signup_token=token, _full=True) msg = ( 'Send an email to user in order to verify their address. They will be able to do so by visiting <a href="{url}">{url}</a>' ) self.display_message(msg.format(url=verification_url)) class ForgotPasswordHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') user = self.user_model.get_by_auth_id(username) if not user: logging.info('Could not find any user entry for username %s', username) self._serve_page(not_found=True) return user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='p', user_id= user_id, signup_token=token, _full=True) msg = ( 'Send an email to user in order to reset their password. They will be able to do so by visiting <a href="{url}">{url}</a>' ) self.display_message(msg.format(url=verification_url)) def _serve_page(self, not_found=False): username = self.request.get('username') params = {'username': username, 'not_found': not_found} self.render_template('forgot.html', params) class VerificationHandler(BaseHandler): def get(self, *args, **kwargs): user = None user_id = kwargs['user_id'] signup_token = kwargs['signup_token'] verification_type = kwargs['type'] user, ts = self.user_model.get_by_auth_token(int(user_id), signup_token, 'signup') if not user: logging.info( 'Could not find any user with id "%s" signup token "%s"', user_id, signup_token) self.abort(404) self.auth.set_session(self.auth.store.user_to_dict(user), remember=True ) if verification_type == 'v': self.user_model.delete_signup_token(user.get_id(), signup_token) if not user.verified: user.verified = True user.put() self.display_message('User email address has been verified.') return elif verification_type == 'p': params = {'user': user, 'token': signup_token} self.render_template('resetpassword.html', params) else: logging.info('verification type not supported') self.abort(404) class SetPasswordHandler(BaseHandler): @user_required def post(self): password = self.request.get('password') old_token = self.request.get('t') if not password or password != self.request.get('confirm_password'): self.display_message('passwords do not match') return user = self.user user.set_password(password) user.put() self.user_model.delete_signup_token(user.get_id(), old_token) self.display_message('Password updated') class LoginHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') password = self.request.get('password') try: u = self.auth.get_user_by_password(username, password, remember =True, save_session=True) user = self.user tip.coalesce_balance(user) self.redirect(self.uri_for('home')) except (InvalidAuthIdError, InvalidPasswordError) as e: logging.info('Login failed for user %s because of %s', username, type(e)) self._serve_page(True) def _serve_page(self, failed=False): username = self.request.get('username') params = {'username': username, 'failed': failed} self.render_template('login.html', params) class LogoutHandler(BaseHandler): def get(self): self.auth.unset_session() self.redirect(self.uri_for('home')) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def user_required(handler): """ Decorator that checks if there's a user associated with the current session. Will also fail if there's no session present. """ def check_login(self, *args, **kwargs): auth = self.auth if not auth.get_user_by_session(): self.redirect(self.uri_for('login'), abort=True) else: return handler(self, *args, **kwargs) return check_login class BaseHandler(webapp2.RequestHandler): @webapp2.cached_property def auth(self): """Shortcut to access the auth instance as a property.""" return auth.get_auth() @webapp2.cached_property def user_info(self): """Shortcut to access a subset of the user attributes that are stored in the session. The list of attributes to store in the session is specified in config['webapp2_extras.auth']['user_attributes']. :returns A dictionary with most user information """ return self.auth.get_user_by_session() @webapp2.cached_property def user(self): """Shortcut to access the current logged in user. Unlike user_info, it fetches information from the persistence layer and returns an instance of the underlying model. :returns The instance of the user model associated to the logged in user. """ u = self.user_info return self.user_model.get_by_id(u['user_id']) if u else None @webapp2.cached_property def user_model(self): """Returns the implementation of the user model. It is consistent with config['webapp2_extras.auth']['user_model'], if set. """ return self.auth.store.user_model @webapp2.cached_property def session(self): """Shortcut to access the current session.""" return self.session_store.get_session(backend='datastore') def render_template(self, view_filename, params=None): if not params: params = {} user = self.user_info params['user'] = user path = os.path.join(os.path.dirname(__file__), 'views', view_filename) self.response.out.write(template.render(path, params)) def send_json(self, message): self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(message)) def display_message(self, message): """Utility function to display a template with a simple message.""" params = {'message': message} self.render_template('message.html', params) def dispatch(self): self.session_store = sessions.get_store(request=self.request) try: webapp2.RequestHandler.dispatch(self) finally: self.session_store.save_sessions(self.response) class MainHandler(BaseHandler): def get(self): user = self.user if not user: self.render_template('about.html') else: params = {'balance': user.balance} self.render_template('home.html', params) class AboutHandler(BaseHandler): def get(self): self.render_template('about.html') class TrendingHandler(BaseHandler): def get(self): self.render_template('trending.html') class TipHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): failed = False user = self.user tipReceiver = self.request.get('tipReceiver') tipReceiver = self.user_model.get_by_auth_id(tipReceiver) amount = self.request.get('tip') amount = float(amount) try: tip.tip(user, tipReceiver, amount) except: failed = True self._serve_page(failed) def _serve_page(self, failed=False): params = {'failed': failed} self.render_template('tip.html', params) def serve_profile_page(self): user = self.user params = {'auth_id': user.auth_ids[0], 'first_name': user.name, 'last_name': user.last_name, 'email_address': user.email_address, 'balance': user.balance} self.render_template('profile.html', params) class AddCreditsHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): user = self.user credits = self.request.get('credits') credits = float(credits) user.balance += credits user.put() serve_profile_page(self) def _serve_page(self): user = self.user params = {} self.render_template('add_credits.html', params) class LogHandler(BaseHandler): @user_required def get(self): user = self.user keys = tip.TipTransactionLogShardConfig.all_keys(user) logs = keys[0].get() if logs: message = {'logs': logs.logs} else: message = None self.send_json(message) class ProfileHandler(BaseHandler): @user_required def get(self): serve_profile_page(self) class SignupHandler(BaseHandler): def get(self): self.render_template('signup.html') def post(self): user_name = self.request.get('username') email = self.request.get('email') name = self.request.get('name') password = self.request.get('password') last_name = self.request.get('lastname') unique_properties = ['email_address'] user_data = self.user_model.create_user(user_name, unique_properties, email_address=email, name=name, password_raw =password, last_name=last_name, balance=float(0), tip_log_count =0, verified=False) if not user_data[0]: self.display_message( 'Unable to create user for email %s because of duplicate keys %s' % (user_name, user_data[1])) return user = user_data[1] user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='v', user_id= user_id, signup_token=token, _full=True) msg = ( 'Send an email to user in order to verify their address. They will be able to do so by visiting <a href="{url}">{url}</a>' ) self.display_message(msg.format(url=verification_url)) class ForgotPasswordHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') user = self.user_model.get_by_auth_id(username) if not user: logging.info('Could not find any user entry for username %s', username) self._serve_page(not_found=True) return user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='p', user_id= user_id, signup_token=token, _full=True) msg = ( 'Send an email to user in order to reset their password. They will be able to do so by visiting <a href="{url}">{url}</a>' ) self.display_message(msg.format(url=verification_url)) def _serve_page(self, not_found=False): username = self.request.get('username') params = {'username': username, 'not_found': not_found} self.render_template('forgot.html', params) class VerificationHandler(BaseHandler): def get(self, *args, **kwargs): user = None user_id = kwargs['user_id'] signup_token = kwargs['signup_token'] verification_type = kwargs['type'] user, ts = self.user_model.get_by_auth_token(int(user_id), signup_token, 'signup') if not user: logging.info( 'Could not find any user with id "%s" signup token "%s"', user_id, signup_token) self.abort(404) self.auth.set_session(self.auth.store.user_to_dict(user), remember=True ) if verification_type == 'v': self.user_model.delete_signup_token(user.get_id(), signup_token) if not user.verified: user.verified = True user.put() self.display_message('User email address has been verified.') return elif verification_type == 'p': params = {'user': user, 'token': signup_token} self.render_template('resetpassword.html', params) else: logging.info('verification type not supported') self.abort(404) class SetPasswordHandler(BaseHandler): @user_required def post(self): password = self.request.get('password') old_token = self.request.get('t') if not password or password != self.request.get('confirm_password'): self.display_message('passwords do not match') return user = self.user user.set_password(password) user.put() self.user_model.delete_signup_token(user.get_id(), old_token) self.display_message('Password updated') class LoginHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') password = self.request.get('password') try: u = self.auth.get_user_by_password(username, password, remember =True, save_session=True) user = self.user tip.coalesce_balance(user) self.redirect(self.uri_for('home')) except (InvalidAuthIdError, InvalidPasswordError) as e: logging.info('Login failed for user %s because of %s', username, type(e)) self._serve_page(True) def _serve_page(self, failed=False): username = self.request.get('username') params = {'username': username, 'failed': failed} self.render_template('login.html', params) class LogoutHandler(BaseHandler): def get(self): self.auth.unset_session() self.redirect(self.uri_for('home')) <|reserved_special_token_0|> logging.getLogger().setLevel(logging.DEBUG) <|reserved_special_token_1|> <|reserved_special_token_0|> def user_required(handler): """ Decorator that checks if there's a user associated with the current session. Will also fail if there's no session present. """ def check_login(self, *args, **kwargs): auth = self.auth if not auth.get_user_by_session(): self.redirect(self.uri_for('login'), abort=True) else: return handler(self, *args, **kwargs) return check_login class BaseHandler(webapp2.RequestHandler): @webapp2.cached_property def auth(self): """Shortcut to access the auth instance as a property.""" return auth.get_auth() @webapp2.cached_property def user_info(self): """Shortcut to access a subset of the user attributes that are stored in the session. The list of attributes to store in the session is specified in config['webapp2_extras.auth']['user_attributes']. :returns A dictionary with most user information """ return self.auth.get_user_by_session() @webapp2.cached_property def user(self): """Shortcut to access the current logged in user. Unlike user_info, it fetches information from the persistence layer and returns an instance of the underlying model. :returns The instance of the user model associated to the logged in user. """ u = self.user_info return self.user_model.get_by_id(u['user_id']) if u else None @webapp2.cached_property def user_model(self): """Returns the implementation of the user model. It is consistent with config['webapp2_extras.auth']['user_model'], if set. """ return self.auth.store.user_model @webapp2.cached_property def session(self): """Shortcut to access the current session.""" return self.session_store.get_session(backend='datastore') def render_template(self, view_filename, params=None): if not params: params = {} user = self.user_info params['user'] = user path = os.path.join(os.path.dirname(__file__), 'views', view_filename) self.response.out.write(template.render(path, params)) def send_json(self, message): self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(message)) def display_message(self, message): """Utility function to display a template with a simple message.""" params = {'message': message} self.render_template('message.html', params) def dispatch(self): self.session_store = sessions.get_store(request=self.request) try: webapp2.RequestHandler.dispatch(self) finally: self.session_store.save_sessions(self.response) class MainHandler(BaseHandler): def get(self): user = self.user if not user: self.render_template('about.html') else: params = {'balance': user.balance} self.render_template('home.html', params) class AboutHandler(BaseHandler): def get(self): self.render_template('about.html') class TrendingHandler(BaseHandler): def get(self): self.render_template('trending.html') class TipHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): failed = False user = self.user tipReceiver = self.request.get('tipReceiver') tipReceiver = self.user_model.get_by_auth_id(tipReceiver) amount = self.request.get('tip') amount = float(amount) try: tip.tip(user, tipReceiver, amount) except: failed = True self._serve_page(failed) def _serve_page(self, failed=False): params = {'failed': failed} self.render_template('tip.html', params) def serve_profile_page(self): user = self.user params = {'auth_id': user.auth_ids[0], 'first_name': user.name, 'last_name': user.last_name, 'email_address': user.email_address, 'balance': user.balance} self.render_template('profile.html', params) class AddCreditsHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): user = self.user credits = self.request.get('credits') credits = float(credits) user.balance += credits user.put() serve_profile_page(self) def _serve_page(self): user = self.user params = {} self.render_template('add_credits.html', params) class LogHandler(BaseHandler): @user_required def get(self): user = self.user keys = tip.TipTransactionLogShardConfig.all_keys(user) logs = keys[0].get() if logs: message = {'logs': logs.logs} else: message = None self.send_json(message) class ProfileHandler(BaseHandler): @user_required def get(self): serve_profile_page(self) class SignupHandler(BaseHandler): def get(self): self.render_template('signup.html') def post(self): user_name = self.request.get('username') email = self.request.get('email') name = self.request.get('name') password = self.request.get('password') last_name = self.request.get('lastname') unique_properties = ['email_address'] user_data = self.user_model.create_user(user_name, unique_properties, email_address=email, name=name, password_raw =password, last_name=last_name, balance=float(0), tip_log_count =0, verified=False) if not user_data[0]: self.display_message( 'Unable to create user for email %s because of duplicate keys %s' % (user_name, user_data[1])) return user = user_data[1] user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='v', user_id= user_id, signup_token=token, _full=True) msg = ( 'Send an email to user in order to verify their address. They will be able to do so by visiting <a href="{url}">{url}</a>' ) self.display_message(msg.format(url=verification_url)) class ForgotPasswordHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') user = self.user_model.get_by_auth_id(username) if not user: logging.info('Could not find any user entry for username %s', username) self._serve_page(not_found=True) return user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='p', user_id= user_id, signup_token=token, _full=True) msg = ( 'Send an email to user in order to reset their password. They will be able to do so by visiting <a href="{url}">{url}</a>' ) self.display_message(msg.format(url=verification_url)) def _serve_page(self, not_found=False): username = self.request.get('username') params = {'username': username, 'not_found': not_found} self.render_template('forgot.html', params) class VerificationHandler(BaseHandler): def get(self, *args, **kwargs): user = None user_id = kwargs['user_id'] signup_token = kwargs['signup_token'] verification_type = kwargs['type'] user, ts = self.user_model.get_by_auth_token(int(user_id), signup_token, 'signup') if not user: logging.info( 'Could not find any user with id "%s" signup token "%s"', user_id, signup_token) self.abort(404) self.auth.set_session(self.auth.store.user_to_dict(user), remember=True ) if verification_type == 'v': self.user_model.delete_signup_token(user.get_id(), signup_token) if not user.verified: user.verified = True user.put() self.display_message('User email address has been verified.') return elif verification_type == 'p': params = {'user': user, 'token': signup_token} self.render_template('resetpassword.html', params) else: logging.info('verification type not supported') self.abort(404) class SetPasswordHandler(BaseHandler): @user_required def post(self): password = self.request.get('password') old_token = self.request.get('t') if not password or password != self.request.get('confirm_password'): self.display_message('passwords do not match') return user = self.user user.set_password(password) user.put() self.user_model.delete_signup_token(user.get_id(), old_token) self.display_message('Password updated') class LoginHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') password = self.request.get('password') try: u = self.auth.get_user_by_password(username, password, remember =True, save_session=True) user = self.user tip.coalesce_balance(user) self.redirect(self.uri_for('home')) except (InvalidAuthIdError, InvalidPasswordError) as e: logging.info('Login failed for user %s because of %s', username, type(e)) self._serve_page(True) def _serve_page(self, failed=False): username = self.request.get('username') params = {'username': username, 'failed': failed} self.render_template('login.html', params) class LogoutHandler(BaseHandler): def get(self): self.auth.unset_session() self.redirect(self.uri_for('home')) config = {'webapp2_extras.auth': {'user_model': 'models.User', 'user_attributes': ['name']}, 'webapp2_extras.sessions': {'secret_key': 'YOUR_SECRET_KEY'}} app = webapp2.WSGIApplication([webapp2.Route('/', MainHandler, name='home'), webapp2.Route('/home', MainHandler, name='home'), webapp2.Route( '/about', AboutHandler, name='about'), webapp2.Route('/trending', TrendingHandler, name='trending'), webapp2.Route('/tip', TipHandler, name='tip'), webapp2.Route('/add_credits', AddCreditsHandler, name= 'add_credits'), webapp2.Route('/get_logs', LogHandler, name='get_logs'), webapp2.Route('/profile', ProfileHandler, name='profile'), webapp2. Route('/signup', SignupHandler), webapp2.Route( '/<type:v|p>/<user_id:\\d+>-<signup_token:.+>', handler= VerificationHandler, name='verification'), webapp2.Route('/password', SetPasswordHandler), webapp2.Route('/forgot', ForgotPasswordHandler, name='forgot'), webapp2.Route('/login', LoginHandler, name='login'), webapp2.Route('/logout', LogoutHandler, name='logout')], debug=True, config=config) logging.getLogger().setLevel(logging.DEBUG) <|reserved_special_token_1|> #!/usr/bin/env python from google.appengine.ext.webapp import template from google.appengine.ext import ndb import logging import os.path import webapp2 import json from webapp2_extras import auth from webapp2_extras import sessions from webapp2_extras.auth import InvalidAuthIdError from webapp2_extras.auth import InvalidPasswordError import tip def user_required(handler): """ Decorator that checks if there's a user associated with the current session. Will also fail if there's no session present. """ def check_login(self, *args, **kwargs): auth = self.auth if not auth.get_user_by_session(): self.redirect(self.uri_for('login'), abort=True) else: return handler(self, *args, **kwargs) return check_login class BaseHandler(webapp2.RequestHandler): @webapp2.cached_property def auth(self): """Shortcut to access the auth instance as a property.""" return auth.get_auth() @webapp2.cached_property def user_info(self): """Shortcut to access a subset of the user attributes that are stored in the session. The list of attributes to store in the session is specified in config['webapp2_extras.auth']['user_attributes']. :returns A dictionary with most user information """ return self.auth.get_user_by_session() @webapp2.cached_property def user(self): """Shortcut to access the current logged in user. Unlike user_info, it fetches information from the persistence layer and returns an instance of the underlying model. :returns The instance of the user model associated to the logged in user. """ u = self.user_info return self.user_model.get_by_id(u['user_id']) if u else None @webapp2.cached_property def user_model(self): """Returns the implementation of the user model. It is consistent with config['webapp2_extras.auth']['user_model'], if set. """ return self.auth.store.user_model @webapp2.cached_property def session(self): """Shortcut to access the current session.""" return self.session_store.get_session(backend="datastore") def render_template(self, view_filename, params=None): if not params: params = {} user = self.user_info params['user'] = user path = os.path.join(os.path.dirname(__file__), 'views', view_filename) self.response.out.write(template.render(path, params)) def send_json(self, message): self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(message)) def display_message(self, message): """Utility function to display a template with a simple message.""" params = { 'message': message } self.render_template('message.html', params) # this is needed for webapp2 sessions to work def dispatch(self): # Get a session store for this request. self.session_store = sessions.get_store(request=self.request) try: # Dispatch the request. webapp2.RequestHandler.dispatch(self) finally: # Save all sessions. self.session_store.save_sessions(self.response) class MainHandler(BaseHandler): def get(self): user = self.user if not user: self.render_template('about.html') else: params = { 'balance': user.balance, } self.render_template('home.html', params) class AboutHandler(BaseHandler): def get(self): self.render_template('about.html') class TrendingHandler(BaseHandler): def get(self): self.render_template('trending.html') class TipHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): failed=False user = self.user tipReceiver = self.request.get('tipReceiver') tipReceiver = self.user_model.get_by_auth_id(tipReceiver) amount = self.request.get('tip') amount = float(amount) try: tip.tip(user, tipReceiver, amount) except: failed=True self._serve_page(failed) def _serve_page(self, failed=False): params = { 'failed': failed } self.render_template('tip.html', params) def serve_profile_page(self): user = self.user params = { 'auth_id': user.auth_ids[0], 'first_name': user.name, 'last_name': user.last_name, 'email_address': user.email_address, 'balance': user.balance, } self.render_template('profile.html', params) class AddCreditsHandler(BaseHandler): @user_required def get(self): self._serve_page() @user_required def post(self): user = self.user credits = self.request.get('credits') credits = float(credits) user.balance += credits user.put() #User a redirect here instead serve_profile_page(self) def _serve_page(self): user = self.user params = { } self.render_template('add_credits.html', params) class LogHandler(BaseHandler): @user_required def get(self): user = self.user keys = tip.TipTransactionLogShardConfig.all_keys(user) logs = keys[0].get() if logs: message = { 'logs': logs.logs } else: message = None self.send_json(message) class ProfileHandler(BaseHandler): @user_required def get(self): serve_profile_page(self) class SignupHandler(BaseHandler): def get(self): self.render_template('signup.html') def post(self): user_name = self.request.get('username') email = self.request.get('email') name = self.request.get('name') password = self.request.get('password') last_name = self.request.get('lastname') unique_properties = ['email_address'] user_data = self.user_model.create_user(user_name, unique_properties, email_address=email, name=name, password_raw=password, last_name=last_name, balance=float(0), tip_log_count=0, verified=False) if not user_data[0]: #user_data is a tuple self.display_message('Unable to create user for email %s because of \ duplicate keys %s' % (user_name, user_data[1])) return user = user_data[1] user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='v', user_id=user_id, signup_token=token, _full=True) msg = 'Send an email to user in order to verify their address. \ They will be able to do so by visiting <a href="{url}">{url}</a>' self.display_message(msg.format(url=verification_url)) class ForgotPasswordHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') user = self.user_model.get_by_auth_id(username) if not user: logging.info('Could not find any user entry for username %s', username) self._serve_page(not_found=True) return user_id = user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='p', user_id=user_id, signup_token=token, _full=True) msg = 'Send an email to user in order to reset their password. \ They will be able to do so by visiting <a href="{url}">{url}</a>' self.display_message(msg.format(url=verification_url)) def _serve_page(self, not_found=False): username = self.request.get('username') params = { 'username': username, 'not_found': not_found } self.render_template('forgot.html', params) class VerificationHandler(BaseHandler): def get(self, *args, **kwargs): user = None user_id = kwargs['user_id'] signup_token = kwargs['signup_token'] verification_type = kwargs['type'] # it should be something more concise like # self.auth.get_user_by_token(user_id, signup_token) # unfortunately the auth interface does not (yet) allow to manipulate # signup tokens concisely user, ts = self.user_model.get_by_auth_token(int(user_id), signup_token, 'signup') if not user: logging.info('Could not find any user with id "%s" signup token "%s"', user_id, signup_token) self.abort(404) # store user data in the session self.auth.set_session(self.auth.store.user_to_dict(user), remember=True) if verification_type == 'v': # remove signup token, we don't want users to come back with an old link self.user_model.delete_signup_token(user.get_id(), signup_token) if not user.verified: user.verified = True user.put() self.display_message('User email address has been verified.') return elif verification_type == 'p': # supply user to the page params = { 'user': user, 'token': signup_token } self.render_template('resetpassword.html', params) else: logging.info('verification type not supported') self.abort(404) class SetPasswordHandler(BaseHandler): @user_required def post(self): password = self.request.get('password') old_token = self.request.get('t') if not password or password != self.request.get('confirm_password'): self.display_message('passwords do not match') return user = self.user user.set_password(password) user.put() # remove signup token, we don't want users to come back with an old link self.user_model.delete_signup_token(user.get_id(), old_token) self.display_message('Password updated') class LoginHandler(BaseHandler): def get(self): self._serve_page() def post(self): username = self.request.get('username') password = self.request.get('password') try: u = self.auth.get_user_by_password(username, password, remember=True, save_session=True) user = self.user tip.coalesce_balance(user) self.redirect(self.uri_for('home')) except (InvalidAuthIdError, InvalidPasswordError) as e: logging.info('Login failed for user %s because of %s', username, type(e)) self._serve_page(True) def _serve_page(self, failed=False): username = self.request.get('username') params = { 'username': username, 'failed': failed } self.render_template('login.html', params) class LogoutHandler(BaseHandler): def get(self): self.auth.unset_session() self.redirect(self.uri_for('home')) config = { 'webapp2_extras.auth': { 'user_model': 'models.User', 'user_attributes': ['name'] }, 'webapp2_extras.sessions': { 'secret_key': 'YOUR_SECRET_KEY' } } app = webapp2.WSGIApplication([ webapp2.Route('/', MainHandler, name='home'), webapp2.Route('/home', MainHandler, name='home'), webapp2.Route('/about', AboutHandler, name='about'), webapp2.Route('/trending', TrendingHandler, name='trending'), webapp2.Route('/tip', TipHandler, name='tip'), webapp2.Route('/add_credits', AddCreditsHandler, name='add_credits'), webapp2.Route('/get_logs', LogHandler, name='get_logs'), webapp2.Route('/profile', ProfileHandler, name='profile'), webapp2.Route('/signup', SignupHandler), webapp2.Route('/<type:v|p>/<user_id:\d+>-<signup_token:.+>', handler=VerificationHandler, name='verification'), webapp2.Route('/password', SetPasswordHandler), webapp2.Route('/forgot', ForgotPasswordHandler, name='forgot'), webapp2.Route('/login', LoginHandler, name='login'), webapp2.Route('/logout', LogoutHandler, name='logout'), ], debug=True, config=config) logging.getLogger().setLevel(logging.DEBUG)
flexible
{ "blob_id": "fe7fb9a4a5ca2bb8dab0acf440eb2fac127264ce", "index": 2631, "step-1": "<mask token>\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n @webapp2.cached_property\n def auth(self):\n \"\"\"Shortcut to access the auth instance as a property.\"\"\"\n return auth.get_auth()\n <mask token>\n <mask token>\n <mask token>\n\n @webapp2.cached_property\n def session(self):\n \"\"\"Shortcut to access the current session.\"\"\"\n return self.session_store.get_session(backend='datastore')\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n user = self.user_info\n params['user'] = user\n path = os.path.join(os.path.dirname(__file__), 'views', view_filename)\n self.response.out.write(template.render(path, params))\n <mask token>\n <mask token>\n\n def dispatch(self):\n self.session_store = sessions.get_store(request=self.request)\n try:\n webapp2.RequestHandler.dispatch(self)\n finally:\n self.session_store.save_sessions(self.response)\n\n\nclass MainHandler(BaseHandler):\n\n def get(self):\n user = self.user\n if not user:\n self.render_template('about.html')\n else:\n params = {'balance': user.balance}\n self.render_template('home.html', params)\n\n\nclass AboutHandler(BaseHandler):\n\n def get(self):\n self.render_template('about.html')\n\n\nclass TrendingHandler(BaseHandler):\n\n def get(self):\n self.render_template('trending.html')\n\n\nclass TipHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n failed = False\n user = self.user\n tipReceiver = self.request.get('tipReceiver')\n tipReceiver = self.user_model.get_by_auth_id(tipReceiver)\n amount = self.request.get('tip')\n amount = float(amount)\n try:\n tip.tip(user, tipReceiver, amount)\n except:\n failed = True\n self._serve_page(failed)\n\n def _serve_page(self, failed=False):\n params = {'failed': failed}\n self.render_template('tip.html', params)\n\n\n<mask token>\n\n\nclass AddCreditsHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n user = self.user\n credits = self.request.get('credits')\n credits = float(credits)\n user.balance += credits\n user.put()\n serve_profile_page(self)\n\n def _serve_page(self):\n user = self.user\n params = {}\n self.render_template('add_credits.html', params)\n\n\nclass LogHandler(BaseHandler):\n\n @user_required\n def get(self):\n user = self.user\n keys = tip.TipTransactionLogShardConfig.all_keys(user)\n logs = keys[0].get()\n if logs:\n message = {'logs': logs.logs}\n else:\n message = None\n self.send_json(message)\n\n\nclass ProfileHandler(BaseHandler):\n\n @user_required\n def get(self):\n serve_profile_page(self)\n\n\nclass SignupHandler(BaseHandler):\n\n def get(self):\n self.render_template('signup.html')\n\n def post(self):\n user_name = self.request.get('username')\n email = self.request.get('email')\n name = self.request.get('name')\n password = self.request.get('password')\n last_name = self.request.get('lastname')\n unique_properties = ['email_address']\n user_data = self.user_model.create_user(user_name,\n unique_properties, email_address=email, name=name, password_raw\n =password, last_name=last_name, balance=float(0), tip_log_count\n =0, verified=False)\n if not user_data[0]:\n self.display_message(\n 'Unable to create user for email %s because of duplicate keys %s'\n % (user_name, user_data[1]))\n return\n user = user_data[1]\n user_id = user.get_id()\n token = self.user_model.create_signup_token(user_id)\n verification_url = self.uri_for('verification', type='v', user_id=\n user_id, signup_token=token, _full=True)\n msg = (\n 'Send an email to user in order to verify their address. They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n )\n self.display_message(msg.format(url=verification_url))\n\n\nclass ForgotPasswordHandler(BaseHandler):\n\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n user = self.user_model.get_by_auth_id(username)\n if not user:\n logging.info('Could not find any user entry for username %s',\n username)\n self._serve_page(not_found=True)\n return\n user_id = user.get_id()\n token = self.user_model.create_signup_token(user_id)\n verification_url = self.uri_for('verification', type='p', user_id=\n user_id, signup_token=token, _full=True)\n msg = (\n 'Send an email to user in order to reset their password. They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n )\n self.display_message(msg.format(url=verification_url))\n\n def _serve_page(self, not_found=False):\n username = self.request.get('username')\n params = {'username': username, 'not_found': not_found}\n self.render_template('forgot.html', params)\n\n\nclass VerificationHandler(BaseHandler):\n\n def get(self, *args, **kwargs):\n user = None\n user_id = kwargs['user_id']\n signup_token = kwargs['signup_token']\n verification_type = kwargs['type']\n user, ts = self.user_model.get_by_auth_token(int(user_id),\n signup_token, 'signup')\n if not user:\n logging.info(\n 'Could not find any user with id \"%s\" signup token \"%s\"',\n user_id, signup_token)\n self.abort(404)\n self.auth.set_session(self.auth.store.user_to_dict(user), remember=True\n )\n if verification_type == 'v':\n self.user_model.delete_signup_token(user.get_id(), signup_token)\n if not user.verified:\n user.verified = True\n user.put()\n self.display_message('User email address has been verified.')\n return\n elif verification_type == 'p':\n params = {'user': user, 'token': signup_token}\n self.render_template('resetpassword.html', params)\n else:\n logging.info('verification type not supported')\n self.abort(404)\n\n\nclass SetPasswordHandler(BaseHandler):\n\n @user_required\n def post(self):\n password = self.request.get('password')\n old_token = self.request.get('t')\n if not password or password != self.request.get('confirm_password'):\n self.display_message('passwords do not match')\n return\n user = self.user\n user.set_password(password)\n user.put()\n self.user_model.delete_signup_token(user.get_id(), old_token)\n self.display_message('Password updated')\n\n\nclass LoginHandler(BaseHandler):\n\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n password = self.request.get('password')\n try:\n u = self.auth.get_user_by_password(username, password, remember\n =True, save_session=True)\n user = self.user\n tip.coalesce_balance(user)\n self.redirect(self.uri_for('home'))\n except (InvalidAuthIdError, InvalidPasswordError) as e:\n logging.info('Login failed for user %s because of %s', username,\n type(e))\n self._serve_page(True)\n\n def _serve_page(self, failed=False):\n username = self.request.get('username')\n params = {'username': username, 'failed': failed}\n self.render_template('login.html', params)\n\n\nclass LogoutHandler(BaseHandler):\n\n def get(self):\n self.auth.unset_session()\n self.redirect(self.uri_for('home'))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n @webapp2.cached_property\n def auth(self):\n \"\"\"Shortcut to access the auth instance as a property.\"\"\"\n return auth.get_auth()\n <mask token>\n\n @webapp2.cached_property\n def user(self):\n \"\"\"Shortcut to access the current logged in user.\n\n Unlike user_info, it fetches information from the persistence layer and\n returns an instance of the underlying model.\n\n :returns\n The instance of the user model associated to the logged in user.\n \"\"\"\n u = self.user_info\n return self.user_model.get_by_id(u['user_id']) if u else None\n <mask token>\n\n @webapp2.cached_property\n def session(self):\n \"\"\"Shortcut to access the current session.\"\"\"\n return self.session_store.get_session(backend='datastore')\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n user = self.user_info\n params['user'] = user\n path = os.path.join(os.path.dirname(__file__), 'views', view_filename)\n self.response.out.write(template.render(path, params))\n <mask token>\n\n def display_message(self, message):\n \"\"\"Utility function to display a template with a simple message.\"\"\"\n params = {'message': message}\n self.render_template('message.html', params)\n\n def dispatch(self):\n self.session_store = sessions.get_store(request=self.request)\n try:\n webapp2.RequestHandler.dispatch(self)\n finally:\n self.session_store.save_sessions(self.response)\n\n\nclass MainHandler(BaseHandler):\n\n def get(self):\n user = self.user\n if not user:\n self.render_template('about.html')\n else:\n params = {'balance': user.balance}\n self.render_template('home.html', params)\n\n\nclass AboutHandler(BaseHandler):\n\n def get(self):\n self.render_template('about.html')\n\n\nclass TrendingHandler(BaseHandler):\n\n def get(self):\n self.render_template('trending.html')\n\n\nclass TipHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n failed = False\n user = self.user\n tipReceiver = self.request.get('tipReceiver')\n tipReceiver = self.user_model.get_by_auth_id(tipReceiver)\n amount = self.request.get('tip')\n amount = float(amount)\n try:\n tip.tip(user, tipReceiver, amount)\n except:\n failed = True\n self._serve_page(failed)\n\n def _serve_page(self, failed=False):\n params = {'failed': failed}\n self.render_template('tip.html', params)\n\n\n<mask token>\n\n\nclass AddCreditsHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n user = self.user\n credits = self.request.get('credits')\n credits = float(credits)\n user.balance += credits\n user.put()\n serve_profile_page(self)\n\n def _serve_page(self):\n user = self.user\n params = {}\n self.render_template('add_credits.html', params)\n\n\nclass LogHandler(BaseHandler):\n\n @user_required\n def get(self):\n user = self.user\n keys = tip.TipTransactionLogShardConfig.all_keys(user)\n logs = keys[0].get()\n if logs:\n message = {'logs': logs.logs}\n else:\n message = None\n self.send_json(message)\n\n\nclass ProfileHandler(BaseHandler):\n\n @user_required\n def get(self):\n serve_profile_page(self)\n\n\nclass SignupHandler(BaseHandler):\n\n def get(self):\n self.render_template('signup.html')\n\n def post(self):\n user_name = self.request.get('username')\n email = self.request.get('email')\n name = self.request.get('name')\n password = self.request.get('password')\n last_name = self.request.get('lastname')\n unique_properties = ['email_address']\n user_data = self.user_model.create_user(user_name,\n unique_properties, email_address=email, name=name, password_raw\n =password, last_name=last_name, balance=float(0), tip_log_count\n =0, verified=False)\n if not user_data[0]:\n self.display_message(\n 'Unable to create user for email %s because of duplicate keys %s'\n % (user_name, user_data[1]))\n return\n user = user_data[1]\n user_id = user.get_id()\n token = self.user_model.create_signup_token(user_id)\n verification_url = self.uri_for('verification', type='v', user_id=\n user_id, signup_token=token, _full=True)\n msg = (\n 'Send an email to user in order to verify their address. They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n )\n self.display_message(msg.format(url=verification_url))\n\n\nclass ForgotPasswordHandler(BaseHandler):\n\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n user = self.user_model.get_by_auth_id(username)\n if not user:\n logging.info('Could not find any user entry for username %s',\n username)\n self._serve_page(not_found=True)\n return\n user_id = user.get_id()\n token = self.user_model.create_signup_token(user_id)\n verification_url = self.uri_for('verification', type='p', user_id=\n user_id, signup_token=token, _full=True)\n msg = (\n 'Send an email to user in order to reset their password. They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n )\n self.display_message(msg.format(url=verification_url))\n\n def _serve_page(self, not_found=False):\n username = self.request.get('username')\n params = {'username': username, 'not_found': not_found}\n self.render_template('forgot.html', params)\n\n\nclass VerificationHandler(BaseHandler):\n\n def get(self, *args, **kwargs):\n user = None\n user_id = kwargs['user_id']\n signup_token = kwargs['signup_token']\n verification_type = kwargs['type']\n user, ts = self.user_model.get_by_auth_token(int(user_id),\n signup_token, 'signup')\n if not user:\n logging.info(\n 'Could not find any user with id \"%s\" signup token \"%s\"',\n user_id, signup_token)\n self.abort(404)\n self.auth.set_session(self.auth.store.user_to_dict(user), remember=True\n )\n if verification_type == 'v':\n self.user_model.delete_signup_token(user.get_id(), signup_token)\n if not user.verified:\n user.verified = True\n user.put()\n self.display_message('User email address has been verified.')\n return\n elif verification_type == 'p':\n params = {'user': user, 'token': signup_token}\n self.render_template('resetpassword.html', params)\n else:\n logging.info('verification type not supported')\n self.abort(404)\n\n\nclass SetPasswordHandler(BaseHandler):\n\n @user_required\n def post(self):\n password = self.request.get('password')\n old_token = self.request.get('t')\n if not password or password != self.request.get('confirm_password'):\n self.display_message('passwords do not match')\n return\n user = self.user\n user.set_password(password)\n user.put()\n self.user_model.delete_signup_token(user.get_id(), old_token)\n self.display_message('Password updated')\n\n\nclass LoginHandler(BaseHandler):\n\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n password = self.request.get('password')\n try:\n u = self.auth.get_user_by_password(username, password, remember\n =True, save_session=True)\n user = self.user\n tip.coalesce_balance(user)\n self.redirect(self.uri_for('home'))\n except (InvalidAuthIdError, InvalidPasswordError) as e:\n logging.info('Login failed for user %s because of %s', username,\n type(e))\n self._serve_page(True)\n\n def _serve_page(self, failed=False):\n username = self.request.get('username')\n params = {'username': username, 'failed': failed}\n self.render_template('login.html', params)\n\n\nclass LogoutHandler(BaseHandler):\n\n def get(self):\n self.auth.unset_session()\n self.redirect(self.uri_for('home'))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef user_required(handler):\n \"\"\"\n Decorator that checks if there's a user associated with the current session.\n Will also fail if there's no session present.\n \"\"\"\n\n def check_login(self, *args, **kwargs):\n auth = self.auth\n if not auth.get_user_by_session():\n self.redirect(self.uri_for('login'), abort=True)\n else:\n return handler(self, *args, **kwargs)\n return check_login\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n @webapp2.cached_property\n def auth(self):\n \"\"\"Shortcut to access the auth instance as a property.\"\"\"\n return auth.get_auth()\n\n @webapp2.cached_property\n def user_info(self):\n \"\"\"Shortcut to access a subset of the user attributes that are stored\n in the session.\n\n The list of attributes to store in the session is specified in\n config['webapp2_extras.auth']['user_attributes'].\n :returns\n A dictionary with most user information\n \"\"\"\n return self.auth.get_user_by_session()\n\n @webapp2.cached_property\n def user(self):\n \"\"\"Shortcut to access the current logged in user.\n\n Unlike user_info, it fetches information from the persistence layer and\n returns an instance of the underlying model.\n\n :returns\n The instance of the user model associated to the logged in user.\n \"\"\"\n u = self.user_info\n return self.user_model.get_by_id(u['user_id']) if u else None\n\n @webapp2.cached_property\n def user_model(self):\n \"\"\"Returns the implementation of the user model.\n\n It is consistent with config['webapp2_extras.auth']['user_model'], if set.\n \"\"\"\n return self.auth.store.user_model\n\n @webapp2.cached_property\n def session(self):\n \"\"\"Shortcut to access the current session.\"\"\"\n return self.session_store.get_session(backend='datastore')\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n user = self.user_info\n params['user'] = user\n path = os.path.join(os.path.dirname(__file__), 'views', view_filename)\n self.response.out.write(template.render(path, params))\n\n def send_json(self, message):\n self.response.headers['Content-Type'] = 'application/json'\n self.response.out.write(json.dumps(message))\n\n def display_message(self, message):\n \"\"\"Utility function to display a template with a simple message.\"\"\"\n params = {'message': message}\n self.render_template('message.html', params)\n\n def dispatch(self):\n self.session_store = sessions.get_store(request=self.request)\n try:\n webapp2.RequestHandler.dispatch(self)\n finally:\n self.session_store.save_sessions(self.response)\n\n\nclass MainHandler(BaseHandler):\n\n def get(self):\n user = self.user\n if not user:\n self.render_template('about.html')\n else:\n params = {'balance': user.balance}\n self.render_template('home.html', params)\n\n\nclass AboutHandler(BaseHandler):\n\n def get(self):\n self.render_template('about.html')\n\n\nclass TrendingHandler(BaseHandler):\n\n def get(self):\n self.render_template('trending.html')\n\n\nclass TipHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n failed = False\n user = self.user\n tipReceiver = self.request.get('tipReceiver')\n tipReceiver = self.user_model.get_by_auth_id(tipReceiver)\n amount = self.request.get('tip')\n amount = float(amount)\n try:\n tip.tip(user, tipReceiver, amount)\n except:\n failed = True\n self._serve_page(failed)\n\n def _serve_page(self, failed=False):\n params = {'failed': failed}\n self.render_template('tip.html', params)\n\n\ndef serve_profile_page(self):\n user = self.user\n params = {'auth_id': user.auth_ids[0], 'first_name': user.name,\n 'last_name': user.last_name, 'email_address': user.email_address,\n 'balance': user.balance}\n self.render_template('profile.html', params)\n\n\nclass AddCreditsHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n user = self.user\n credits = self.request.get('credits')\n credits = float(credits)\n user.balance += credits\n user.put()\n serve_profile_page(self)\n\n def _serve_page(self):\n user = self.user\n params = {}\n self.render_template('add_credits.html', params)\n\n\nclass LogHandler(BaseHandler):\n\n @user_required\n def get(self):\n user = self.user\n keys = tip.TipTransactionLogShardConfig.all_keys(user)\n logs = keys[0].get()\n if logs:\n message = {'logs': logs.logs}\n else:\n message = None\n self.send_json(message)\n\n\nclass ProfileHandler(BaseHandler):\n\n @user_required\n def get(self):\n serve_profile_page(self)\n\n\nclass SignupHandler(BaseHandler):\n\n def get(self):\n self.render_template('signup.html')\n\n def post(self):\n user_name = self.request.get('username')\n email = self.request.get('email')\n name = self.request.get('name')\n password = self.request.get('password')\n last_name = self.request.get('lastname')\n unique_properties = ['email_address']\n user_data = self.user_model.create_user(user_name,\n unique_properties, email_address=email, name=name, password_raw\n =password, last_name=last_name, balance=float(0), tip_log_count\n =0, verified=False)\n if not user_data[0]:\n self.display_message(\n 'Unable to create user for email %s because of duplicate keys %s'\n % (user_name, user_data[1]))\n return\n user = user_data[1]\n user_id = user.get_id()\n token = self.user_model.create_signup_token(user_id)\n verification_url = self.uri_for('verification', type='v', user_id=\n user_id, signup_token=token, _full=True)\n msg = (\n 'Send an email to user in order to verify their address. They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n )\n self.display_message(msg.format(url=verification_url))\n\n\nclass ForgotPasswordHandler(BaseHandler):\n\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n user = self.user_model.get_by_auth_id(username)\n if not user:\n logging.info('Could not find any user entry for username %s',\n username)\n self._serve_page(not_found=True)\n return\n user_id = user.get_id()\n token = self.user_model.create_signup_token(user_id)\n verification_url = self.uri_for('verification', type='p', user_id=\n user_id, signup_token=token, _full=True)\n msg = (\n 'Send an email to user in order to reset their password. They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n )\n self.display_message(msg.format(url=verification_url))\n\n def _serve_page(self, not_found=False):\n username = self.request.get('username')\n params = {'username': username, 'not_found': not_found}\n self.render_template('forgot.html', params)\n\n\nclass VerificationHandler(BaseHandler):\n\n def get(self, *args, **kwargs):\n user = None\n user_id = kwargs['user_id']\n signup_token = kwargs['signup_token']\n verification_type = kwargs['type']\n user, ts = self.user_model.get_by_auth_token(int(user_id),\n signup_token, 'signup')\n if not user:\n logging.info(\n 'Could not find any user with id \"%s\" signup token \"%s\"',\n user_id, signup_token)\n self.abort(404)\n self.auth.set_session(self.auth.store.user_to_dict(user), remember=True\n )\n if verification_type == 'v':\n self.user_model.delete_signup_token(user.get_id(), signup_token)\n if not user.verified:\n user.verified = True\n user.put()\n self.display_message('User email address has been verified.')\n return\n elif verification_type == 'p':\n params = {'user': user, 'token': signup_token}\n self.render_template('resetpassword.html', params)\n else:\n logging.info('verification type not supported')\n self.abort(404)\n\n\nclass SetPasswordHandler(BaseHandler):\n\n @user_required\n def post(self):\n password = self.request.get('password')\n old_token = self.request.get('t')\n if not password or password != self.request.get('confirm_password'):\n self.display_message('passwords do not match')\n return\n user = self.user\n user.set_password(password)\n user.put()\n self.user_model.delete_signup_token(user.get_id(), old_token)\n self.display_message('Password updated')\n\n\nclass LoginHandler(BaseHandler):\n\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n password = self.request.get('password')\n try:\n u = self.auth.get_user_by_password(username, password, remember\n =True, save_session=True)\n user = self.user\n tip.coalesce_balance(user)\n self.redirect(self.uri_for('home'))\n except (InvalidAuthIdError, InvalidPasswordError) as e:\n logging.info('Login failed for user %s because of %s', username,\n type(e))\n self._serve_page(True)\n\n def _serve_page(self, failed=False):\n username = self.request.get('username')\n params = {'username': username, 'failed': failed}\n self.render_template('login.html', params)\n\n\nclass LogoutHandler(BaseHandler):\n\n def get(self):\n self.auth.unset_session()\n self.redirect(self.uri_for('home'))\n\n\n<mask token>\nlogging.getLogger().setLevel(logging.DEBUG)\n", "step-4": "<mask token>\n\n\ndef user_required(handler):\n \"\"\"\n Decorator that checks if there's a user associated with the current session.\n Will also fail if there's no session present.\n \"\"\"\n\n def check_login(self, *args, **kwargs):\n auth = self.auth\n if not auth.get_user_by_session():\n self.redirect(self.uri_for('login'), abort=True)\n else:\n return handler(self, *args, **kwargs)\n return check_login\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n @webapp2.cached_property\n def auth(self):\n \"\"\"Shortcut to access the auth instance as a property.\"\"\"\n return auth.get_auth()\n\n @webapp2.cached_property\n def user_info(self):\n \"\"\"Shortcut to access a subset of the user attributes that are stored\n in the session.\n\n The list of attributes to store in the session is specified in\n config['webapp2_extras.auth']['user_attributes'].\n :returns\n A dictionary with most user information\n \"\"\"\n return self.auth.get_user_by_session()\n\n @webapp2.cached_property\n def user(self):\n \"\"\"Shortcut to access the current logged in user.\n\n Unlike user_info, it fetches information from the persistence layer and\n returns an instance of the underlying model.\n\n :returns\n The instance of the user model associated to the logged in user.\n \"\"\"\n u = self.user_info\n return self.user_model.get_by_id(u['user_id']) if u else None\n\n @webapp2.cached_property\n def user_model(self):\n \"\"\"Returns the implementation of the user model.\n\n It is consistent with config['webapp2_extras.auth']['user_model'], if set.\n \"\"\"\n return self.auth.store.user_model\n\n @webapp2.cached_property\n def session(self):\n \"\"\"Shortcut to access the current session.\"\"\"\n return self.session_store.get_session(backend='datastore')\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n user = self.user_info\n params['user'] = user\n path = os.path.join(os.path.dirname(__file__), 'views', view_filename)\n self.response.out.write(template.render(path, params))\n\n def send_json(self, message):\n self.response.headers['Content-Type'] = 'application/json'\n self.response.out.write(json.dumps(message))\n\n def display_message(self, message):\n \"\"\"Utility function to display a template with a simple message.\"\"\"\n params = {'message': message}\n self.render_template('message.html', params)\n\n def dispatch(self):\n self.session_store = sessions.get_store(request=self.request)\n try:\n webapp2.RequestHandler.dispatch(self)\n finally:\n self.session_store.save_sessions(self.response)\n\n\nclass MainHandler(BaseHandler):\n\n def get(self):\n user = self.user\n if not user:\n self.render_template('about.html')\n else:\n params = {'balance': user.balance}\n self.render_template('home.html', params)\n\n\nclass AboutHandler(BaseHandler):\n\n def get(self):\n self.render_template('about.html')\n\n\nclass TrendingHandler(BaseHandler):\n\n def get(self):\n self.render_template('trending.html')\n\n\nclass TipHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n failed = False\n user = self.user\n tipReceiver = self.request.get('tipReceiver')\n tipReceiver = self.user_model.get_by_auth_id(tipReceiver)\n amount = self.request.get('tip')\n amount = float(amount)\n try:\n tip.tip(user, tipReceiver, amount)\n except:\n failed = True\n self._serve_page(failed)\n\n def _serve_page(self, failed=False):\n params = {'failed': failed}\n self.render_template('tip.html', params)\n\n\ndef serve_profile_page(self):\n user = self.user\n params = {'auth_id': user.auth_ids[0], 'first_name': user.name,\n 'last_name': user.last_name, 'email_address': user.email_address,\n 'balance': user.balance}\n self.render_template('profile.html', params)\n\n\nclass AddCreditsHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n user = self.user\n credits = self.request.get('credits')\n credits = float(credits)\n user.balance += credits\n user.put()\n serve_profile_page(self)\n\n def _serve_page(self):\n user = self.user\n params = {}\n self.render_template('add_credits.html', params)\n\n\nclass LogHandler(BaseHandler):\n\n @user_required\n def get(self):\n user = self.user\n keys = tip.TipTransactionLogShardConfig.all_keys(user)\n logs = keys[0].get()\n if logs:\n message = {'logs': logs.logs}\n else:\n message = None\n self.send_json(message)\n\n\nclass ProfileHandler(BaseHandler):\n\n @user_required\n def get(self):\n serve_profile_page(self)\n\n\nclass SignupHandler(BaseHandler):\n\n def get(self):\n self.render_template('signup.html')\n\n def post(self):\n user_name = self.request.get('username')\n email = self.request.get('email')\n name = self.request.get('name')\n password = self.request.get('password')\n last_name = self.request.get('lastname')\n unique_properties = ['email_address']\n user_data = self.user_model.create_user(user_name,\n unique_properties, email_address=email, name=name, password_raw\n =password, last_name=last_name, balance=float(0), tip_log_count\n =0, verified=False)\n if not user_data[0]:\n self.display_message(\n 'Unable to create user for email %s because of duplicate keys %s'\n % (user_name, user_data[1]))\n return\n user = user_data[1]\n user_id = user.get_id()\n token = self.user_model.create_signup_token(user_id)\n verification_url = self.uri_for('verification', type='v', user_id=\n user_id, signup_token=token, _full=True)\n msg = (\n 'Send an email to user in order to verify their address. They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n )\n self.display_message(msg.format(url=verification_url))\n\n\nclass ForgotPasswordHandler(BaseHandler):\n\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n user = self.user_model.get_by_auth_id(username)\n if not user:\n logging.info('Could not find any user entry for username %s',\n username)\n self._serve_page(not_found=True)\n return\n user_id = user.get_id()\n token = self.user_model.create_signup_token(user_id)\n verification_url = self.uri_for('verification', type='p', user_id=\n user_id, signup_token=token, _full=True)\n msg = (\n 'Send an email to user in order to reset their password. They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n )\n self.display_message(msg.format(url=verification_url))\n\n def _serve_page(self, not_found=False):\n username = self.request.get('username')\n params = {'username': username, 'not_found': not_found}\n self.render_template('forgot.html', params)\n\n\nclass VerificationHandler(BaseHandler):\n\n def get(self, *args, **kwargs):\n user = None\n user_id = kwargs['user_id']\n signup_token = kwargs['signup_token']\n verification_type = kwargs['type']\n user, ts = self.user_model.get_by_auth_token(int(user_id),\n signup_token, 'signup')\n if not user:\n logging.info(\n 'Could not find any user with id \"%s\" signup token \"%s\"',\n user_id, signup_token)\n self.abort(404)\n self.auth.set_session(self.auth.store.user_to_dict(user), remember=True\n )\n if verification_type == 'v':\n self.user_model.delete_signup_token(user.get_id(), signup_token)\n if not user.verified:\n user.verified = True\n user.put()\n self.display_message('User email address has been verified.')\n return\n elif verification_type == 'p':\n params = {'user': user, 'token': signup_token}\n self.render_template('resetpassword.html', params)\n else:\n logging.info('verification type not supported')\n self.abort(404)\n\n\nclass SetPasswordHandler(BaseHandler):\n\n @user_required\n def post(self):\n password = self.request.get('password')\n old_token = self.request.get('t')\n if not password or password != self.request.get('confirm_password'):\n self.display_message('passwords do not match')\n return\n user = self.user\n user.set_password(password)\n user.put()\n self.user_model.delete_signup_token(user.get_id(), old_token)\n self.display_message('Password updated')\n\n\nclass LoginHandler(BaseHandler):\n\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n password = self.request.get('password')\n try:\n u = self.auth.get_user_by_password(username, password, remember\n =True, save_session=True)\n user = self.user\n tip.coalesce_balance(user)\n self.redirect(self.uri_for('home'))\n except (InvalidAuthIdError, InvalidPasswordError) as e:\n logging.info('Login failed for user %s because of %s', username,\n type(e))\n self._serve_page(True)\n\n def _serve_page(self, failed=False):\n username = self.request.get('username')\n params = {'username': username, 'failed': failed}\n self.render_template('login.html', params)\n\n\nclass LogoutHandler(BaseHandler):\n\n def get(self):\n self.auth.unset_session()\n self.redirect(self.uri_for('home'))\n\n\nconfig = {'webapp2_extras.auth': {'user_model': 'models.User',\n 'user_attributes': ['name']}, 'webapp2_extras.sessions': {'secret_key':\n 'YOUR_SECRET_KEY'}}\napp = webapp2.WSGIApplication([webapp2.Route('/', MainHandler, name='home'),\n webapp2.Route('/home', MainHandler, name='home'), webapp2.Route(\n '/about', AboutHandler, name='about'), webapp2.Route('/trending',\n TrendingHandler, name='trending'), webapp2.Route('/tip', TipHandler,\n name='tip'), webapp2.Route('/add_credits', AddCreditsHandler, name=\n 'add_credits'), webapp2.Route('/get_logs', LogHandler, name='get_logs'),\n webapp2.Route('/profile', ProfileHandler, name='profile'), webapp2.\n Route('/signup', SignupHandler), webapp2.Route(\n '/<type:v|p>/<user_id:\\\\d+>-<signup_token:.+>', handler=\n VerificationHandler, name='verification'), webapp2.Route('/password',\n SetPasswordHandler), webapp2.Route('/forgot', ForgotPasswordHandler,\n name='forgot'), webapp2.Route('/login', LoginHandler, name='login'),\n webapp2.Route('/logout', LogoutHandler, name='logout')], debug=True,\n config=config)\nlogging.getLogger().setLevel(logging.DEBUG)\n", "step-5": "#!/usr/bin/env python\n\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext import ndb\n\nimport logging\nimport os.path\nimport webapp2\nimport json\n\nfrom webapp2_extras import auth\nfrom webapp2_extras import sessions\n\nfrom webapp2_extras.auth import InvalidAuthIdError\nfrom webapp2_extras.auth import InvalidPasswordError\n\nimport tip\n\ndef user_required(handler):\n \"\"\"\n Decorator that checks if there's a user associated with the current session.\n Will also fail if there's no session present.\n \"\"\"\n def check_login(self, *args, **kwargs):\n auth = self.auth\n if not auth.get_user_by_session():\n self.redirect(self.uri_for('login'), abort=True)\n else:\n return handler(self, *args, **kwargs)\n\n return check_login\n\nclass BaseHandler(webapp2.RequestHandler):\n @webapp2.cached_property\n def auth(self):\n \"\"\"Shortcut to access the auth instance as a property.\"\"\"\n return auth.get_auth()\n\n @webapp2.cached_property\n def user_info(self):\n \"\"\"Shortcut to access a subset of the user attributes that are stored\n in the session.\n\n The list of attributes to store in the session is specified in\n config['webapp2_extras.auth']['user_attributes'].\n :returns\n A dictionary with most user information\n \"\"\"\n return self.auth.get_user_by_session()\n\n @webapp2.cached_property\n def user(self):\n \"\"\"Shortcut to access the current logged in user.\n\n Unlike user_info, it fetches information from the persistence layer and\n returns an instance of the underlying model.\n\n :returns\n The instance of the user model associated to the logged in user.\n \"\"\"\n u = self.user_info\n return self.user_model.get_by_id(u['user_id']) if u else None\n\n @webapp2.cached_property\n def user_model(self):\n \"\"\"Returns the implementation of the user model.\n\n It is consistent with config['webapp2_extras.auth']['user_model'], if set.\n \"\"\" \n return self.auth.store.user_model\n\n @webapp2.cached_property\n def session(self):\n \"\"\"Shortcut to access the current session.\"\"\"\n return self.session_store.get_session(backend=\"datastore\")\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n user = self.user_info\n params['user'] = user\n path = os.path.join(os.path.dirname(__file__), 'views', view_filename)\n self.response.out.write(template.render(path, params))\n\n def send_json(self, message):\n self.response.headers['Content-Type'] = 'application/json'\n self.response.out.write(json.dumps(message))\n\n def display_message(self, message):\n \"\"\"Utility function to display a template with a simple message.\"\"\"\n params = {\n 'message': message\n }\n self.render_template('message.html', params)\n\n # this is needed for webapp2 sessions to work\n def dispatch(self):\n # Get a session store for this request.\n self.session_store = sessions.get_store(request=self.request)\n\n try:\n # Dispatch the request.\n webapp2.RequestHandler.dispatch(self)\n finally:\n # Save all sessions.\n self.session_store.save_sessions(self.response)\n\nclass MainHandler(BaseHandler):\n def get(self):\n user = self.user\n if not user:\n self.render_template('about.html')\n else:\n params = {\n 'balance': user.balance,\n }\n self.render_template('home.html', params)\n\nclass AboutHandler(BaseHandler):\n def get(self):\n self.render_template('about.html')\n\nclass TrendingHandler(BaseHandler):\n def get(self):\n self.render_template('trending.html')\n\nclass TipHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n failed=False\n user = self.user\n tipReceiver = self.request.get('tipReceiver')\n tipReceiver = self.user_model.get_by_auth_id(tipReceiver)\n amount = self.request.get('tip')\n amount = float(amount)\n\n try:\n tip.tip(user, tipReceiver, amount)\n except:\n failed=True\n\n self._serve_page(failed)\n\n def _serve_page(self, failed=False):\n params = {\n 'failed': failed\n }\n self.render_template('tip.html', params)\n\ndef serve_profile_page(self):\n user = self.user\n params = {\n 'auth_id': user.auth_ids[0],\n 'first_name': user.name,\n 'last_name': user.last_name,\n 'email_address': user.email_address,\n 'balance': user.balance,\n }\n\n self.render_template('profile.html', params)\n\nclass AddCreditsHandler(BaseHandler):\n\n @user_required\n def get(self):\n self._serve_page()\n\n @user_required\n def post(self):\n user = self.user\n credits = self.request.get('credits')\n credits = float(credits)\n user.balance += credits \n user.put()\n\n #User a redirect here instead\n serve_profile_page(self)\n\n def _serve_page(self):\n user = self.user\n params = {\n }\n self.render_template('add_credits.html', params)\n\nclass LogHandler(BaseHandler):\n @user_required\n def get(self):\n user = self.user\n keys = tip.TipTransactionLogShardConfig.all_keys(user)\n logs = keys[0].get()\n if logs:\n message = { 'logs': logs.logs }\n else:\n message = None\n self.send_json(message)\n\nclass ProfileHandler(BaseHandler):\n @user_required\n def get(self):\n serve_profile_page(self)\n\nclass SignupHandler(BaseHandler):\n def get(self):\n self.render_template('signup.html')\n\n def post(self):\n user_name = self.request.get('username')\n email = self.request.get('email')\n name = self.request.get('name')\n password = self.request.get('password')\n last_name = self.request.get('lastname')\n\n unique_properties = ['email_address']\n user_data = self.user_model.create_user(user_name,\n unique_properties,\n email_address=email, name=name, password_raw=password,\n last_name=last_name, balance=float(0), tip_log_count=0, verified=False)\n if not user_data[0]: #user_data is a tuple\n self.display_message('Unable to create user for email %s because of \\\n duplicate keys %s' % (user_name, user_data[1]))\n return\n \n user = user_data[1]\n user_id = user.get_id()\n\n token = self.user_model.create_signup_token(user_id)\n\n verification_url = self.uri_for('verification', type='v', user_id=user_id,\n signup_token=token, _full=True)\n\n msg = 'Send an email to user in order to verify their address. \\\n They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n\n self.display_message(msg.format(url=verification_url))\n\nclass ForgotPasswordHandler(BaseHandler):\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n\n user = self.user_model.get_by_auth_id(username)\n if not user:\n logging.info('Could not find any user entry for username %s', username)\n self._serve_page(not_found=True)\n return\n\n user_id = user.get_id()\n token = self.user_model.create_signup_token(user_id)\n\n verification_url = self.uri_for('verification', type='p', user_id=user_id,\n signup_token=token, _full=True)\n\n msg = 'Send an email to user in order to reset their password. \\\n They will be able to do so by visiting <a href=\"{url}\">{url}</a>'\n\n self.display_message(msg.format(url=verification_url))\n \n def _serve_page(self, not_found=False):\n username = self.request.get('username')\n params = {\n 'username': username,\n 'not_found': not_found\n }\n self.render_template('forgot.html', params)\n\n\nclass VerificationHandler(BaseHandler):\n def get(self, *args, **kwargs):\n user = None\n user_id = kwargs['user_id']\n signup_token = kwargs['signup_token']\n verification_type = kwargs['type']\n\n # it should be something more concise like\n # self.auth.get_user_by_token(user_id, signup_token)\n # unfortunately the auth interface does not (yet) allow to manipulate\n # signup tokens concisely\n user, ts = self.user_model.get_by_auth_token(int(user_id), signup_token,\n 'signup')\n\n if not user:\n logging.info('Could not find any user with id \"%s\" signup token \"%s\"',\n user_id, signup_token)\n self.abort(404)\n \n # store user data in the session\n self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)\n\n if verification_type == 'v':\n # remove signup token, we don't want users to come back with an old link\n self.user_model.delete_signup_token(user.get_id(), signup_token)\n\n if not user.verified:\n user.verified = True\n user.put()\n\n self.display_message('User email address has been verified.')\n return\n elif verification_type == 'p':\n # supply user to the page\n params = {\n 'user': user,\n 'token': signup_token\n }\n self.render_template('resetpassword.html', params)\n else:\n logging.info('verification type not supported')\n self.abort(404)\n\nclass SetPasswordHandler(BaseHandler):\n\n @user_required\n def post(self):\n password = self.request.get('password')\n old_token = self.request.get('t')\n\n if not password or password != self.request.get('confirm_password'):\n self.display_message('passwords do not match')\n return\n\n user = self.user\n user.set_password(password)\n user.put()\n\n # remove signup token, we don't want users to come back with an old link\n self.user_model.delete_signup_token(user.get_id(), old_token)\n \n self.display_message('Password updated')\n\nclass LoginHandler(BaseHandler):\n def get(self):\n self._serve_page()\n\n def post(self):\n username = self.request.get('username')\n password = self.request.get('password')\n try:\n u = self.auth.get_user_by_password(username, password, remember=True,\n save_session=True)\n user = self.user\n tip.coalesce_balance(user)\n self.redirect(self.uri_for('home'))\n except (InvalidAuthIdError, InvalidPasswordError) as e:\n logging.info('Login failed for user %s because of %s', username, type(e))\n self._serve_page(True)\n\n def _serve_page(self, failed=False):\n username = self.request.get('username')\n params = {\n 'username': username,\n 'failed': failed\n }\n self.render_template('login.html', params)\n\nclass LogoutHandler(BaseHandler):\n def get(self):\n self.auth.unset_session()\n self.redirect(self.uri_for('home'))\n\nconfig = {\n 'webapp2_extras.auth': {\n 'user_model': 'models.User',\n 'user_attributes': ['name']\n },\n 'webapp2_extras.sessions': {\n 'secret_key': 'YOUR_SECRET_KEY'\n }\n}\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler, name='home'),\n webapp2.Route('/home', MainHandler, name='home'),\n webapp2.Route('/about', AboutHandler, name='about'),\n webapp2.Route('/trending', TrendingHandler, name='trending'),\n webapp2.Route('/tip', TipHandler, name='tip'),\n webapp2.Route('/add_credits', AddCreditsHandler, name='add_credits'),\n webapp2.Route('/get_logs', LogHandler, name='get_logs'),\n webapp2.Route('/profile', ProfileHandler, name='profile'),\n webapp2.Route('/signup', SignupHandler),\n webapp2.Route('/<type:v|p>/<user_id:\\d+>-<signup_token:.+>',\n handler=VerificationHandler, name='verification'),\n webapp2.Route('/password', SetPasswordHandler),\n webapp2.Route('/forgot', ForgotPasswordHandler, name='forgot'),\n webapp2.Route('/login', LoginHandler, name='login'),\n webapp2.Route('/logout', LogoutHandler, name='logout'),\n], debug=True, config=config)\n\nlogging.getLogger().setLevel(logging.DEBUG)\n", "step-ids": [ 40, 42, 48, 49, 51 ] }
[ 40, 42, 48, 49, 51 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for i in my_list: new_list.append(i ** 2) <|reserved_special_token_0|> print(my_dict) <|reserved_special_token_0|> print(new_list_round) <|reserved_special_token_1|> my_list = [1, 2, 3, 4, 5] new_list = [] for i in my_list: new_list.append(i ** 2) new_list_comp = [(el ** 2) for el in my_list] lines = [line.strip() for line in open('text.txt')] new_list_1 = [el for el in my_list if el % 2 == 0] str_1 = 'abc' str_2 = 'def' str_3 = 'gh' new_list_2 = [(i + j + k) for i in str_1 for j in str_2 for k in str_3] my_set = {(el ** 2) for el in range(10)} my_dict = {el: (el ** 2) for el in range(5)} print(my_dict) my_list_of_floats = [2.4324324, 5.3243234, 6.23424] new_list_round = [round(el, 2) for el in my_list_of_floats] print(new_list_round) <|reserved_special_token_1|> # генераторы списков и словарей # lists my_list = [1, 2, 3, 4, 5] new_list = [] for i in my_list: new_list.append(i**2) new_list_comp = [el**2 for el in my_list] lines = [line.strip() for line in open("text.txt")] new_list_1 = [el for el in my_list if el % 2 == 0] str_1 = 'abc' str_2 = 'def' str_3 = 'gh' new_list_2 = [i+j+k for i in str_1 for j in str_2 for k in str_3] # словари и множества my_set = {el**2 for el in range(10)} my_dict = {el: el**2 for el in range(5)} print(my_dict) my_list_of_floats = [2.4324324, 5.3243234, 6.23424] new_list_round = [round(el, 2) for el in my_list_of_floats] print(new_list_round)
flexible
{ "blob_id": "e54eea2261517a2b15fde23c46b3fe75c0efec64", "index": 7746, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in my_list:\n new_list.append(i ** 2)\n<mask token>\nprint(my_dict)\n<mask token>\nprint(new_list_round)\n", "step-3": "my_list = [1, 2, 3, 4, 5]\nnew_list = []\nfor i in my_list:\n new_list.append(i ** 2)\nnew_list_comp = [(el ** 2) for el in my_list]\nlines = [line.strip() for line in open('text.txt')]\nnew_list_1 = [el for el in my_list if el % 2 == 0]\nstr_1 = 'abc'\nstr_2 = 'def'\nstr_3 = 'gh'\nnew_list_2 = [(i + j + k) for i in str_1 for j in str_2 for k in str_3]\nmy_set = {(el ** 2) for el in range(10)}\nmy_dict = {el: (el ** 2) for el in range(5)}\nprint(my_dict)\nmy_list_of_floats = [2.4324324, 5.3243234, 6.23424]\nnew_list_round = [round(el, 2) for el in my_list_of_floats]\nprint(new_list_round)\n", "step-4": "# генераторы списков и словарей\n\n# lists\nmy_list = [1, 2, 3, 4, 5]\nnew_list = []\nfor i in my_list:\n new_list.append(i**2)\n\nnew_list_comp = [el**2 for el in my_list]\n\nlines = [line.strip() for line in open(\"text.txt\")]\n\nnew_list_1 = [el for el in my_list if el % 2 == 0]\n\nstr_1 = 'abc'\nstr_2 = 'def'\nstr_3 = 'gh'\n\nnew_list_2 = [i+j+k for i in str_1 for j in str_2 for k in str_3]\n\n# словари и множества\nmy_set = {el**2 for el in range(10)}\n\nmy_dict = {el: el**2 for el in range(5)}\nprint(my_dict)\n\nmy_list_of_floats = [2.4324324, 5.3243234, 6.23424]\n\nnew_list_round = [round(el, 2) for el in my_list_of_floats]\nprint(new_list_round)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> class GPTD_fixedGrid: def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]): self.env = env self.gamma = gamma self.sigma0 = sigma0 self.kernel = kernel.kernel if not V_mu: V_mu = lambda s: np.zeros((s.shape[1], 1)) self.V_mu = V_mu self.V_D = self.V_mu(D) self.D = D self.A = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C') self.A[-1, 0] = 1 K = self.kernel(self.D, self.D) self.K_inv = np.linalg.inv(K) self.alpha_ = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C') self.C_ = np.zeros((self.D.shape[1], self.D.shape[1]), dtype=np. float64, order='C') self.diff_alpha_CV_D = np.empty((self.D.shape[1], 1), dtype=np. float64, order='C') def k_(self, x): if len(x.shape) == 1: x = x[:, np.newaxis] assert len(x.shape) == 2, 'Check state dimensions' return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1)) <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class GPTD_fixedGrid: def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]): self.env = env self.gamma = gamma self.sigma0 = sigma0 self.kernel = kernel.kernel if not V_mu: V_mu = lambda s: np.zeros((s.shape[1], 1)) self.V_mu = V_mu self.V_D = self.V_mu(D) self.D = D self.A = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C') self.A[-1, 0] = 1 K = self.kernel(self.D, self.D) self.K_inv = np.linalg.inv(K) self.alpha_ = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C') self.C_ = np.zeros((self.D.shape[1], self.D.shape[1]), dtype=np. float64, order='C') self.diff_alpha_CV_D = np.empty((self.D.shape[1], 1), dtype=np. float64, order='C') def k_(self, x): if len(x.shape) == 1: x = x[:, np.newaxis] assert len(x.shape) == 2, 'Check state dimensions' return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1)) def update(self, state_sequence, reward_sequence): """ Update GP after observing states (state_sequence) and rewards (reward_sequence) """ for i in range(reward_sequence.shape[0]): trajt_1 = state_sequence[:, i][:, np.newaxis] trajt = state_sequence[:, i + 1][:, np.newaxis] k_t_1 = self.kernel(self.D, trajt_1) k_t = self.kernel(self.D, trajt) ktt = self.kernel(trajt, trajt) at = np.dot(self.K_inv, k_t) delk_t_1 = k_t_1 - self.gamma * k_t ct = np.dot(self.C_, delk_t_1) - (self.A - self.gamma * at) st = self.sigma0 ** 2 - np.dot(ct.T, delk_t_1) diff_r = np.dot(delk_t_1.T, self.alpha_)[0, 0] - reward_sequence[i] self.alpha_ = self.alpha_ + ct / st * diff_r self.C_ = self.C_ + np.dot(ct, ct.T) / st self.A = at assert not np.isnan(self.alpha_).any( ), 'Check alpha for NaN values' self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D) <|reserved_special_token_0|> def get_value_function(self, states): if self.D.shape[1] == 0: return self.V_mu(states) else: return self.V_mu(states) + np.dot(self.kernel(self.D, states).T, self.diff_alpha_CV_D) <|reserved_special_token_1|> <|reserved_special_token_0|> class GPTD_fixedGrid: def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]): self.env = env self.gamma = gamma self.sigma0 = sigma0 self.kernel = kernel.kernel if not V_mu: V_mu = lambda s: np.zeros((s.shape[1], 1)) self.V_mu = V_mu self.V_D = self.V_mu(D) self.D = D self.A = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C') self.A[-1, 0] = 1 K = self.kernel(self.D, self.D) self.K_inv = np.linalg.inv(K) self.alpha_ = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C') self.C_ = np.zeros((self.D.shape[1], self.D.shape[1]), dtype=np. float64, order='C') self.diff_alpha_CV_D = np.empty((self.D.shape[1], 1), dtype=np. float64, order='C') def k_(self, x): if len(x.shape) == 1: x = x[:, np.newaxis] assert len(x.shape) == 2, 'Check state dimensions' return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1)) def update(self, state_sequence, reward_sequence): """ Update GP after observing states (state_sequence) and rewards (reward_sequence) """ for i in range(reward_sequence.shape[0]): trajt_1 = state_sequence[:, i][:, np.newaxis] trajt = state_sequence[:, i + 1][:, np.newaxis] k_t_1 = self.kernel(self.D, trajt_1) k_t = self.kernel(self.D, trajt) ktt = self.kernel(trajt, trajt) at = np.dot(self.K_inv, k_t) delk_t_1 = k_t_1 - self.gamma * k_t ct = np.dot(self.C_, delk_t_1) - (self.A - self.gamma * at) st = self.sigma0 ** 2 - np.dot(ct.T, delk_t_1) diff_r = np.dot(delk_t_1.T, self.alpha_)[0, 0] - reward_sequence[i] self.alpha_ = self.alpha_ + ct / st * diff_r self.C_ = self.C_ + np.dot(ct, ct.T) / st self.A = at assert not np.isnan(self.alpha_).any( ), 'Check alpha for NaN values' self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D) def build_posterior(self, policy, num_episodes, max_episode_length, test_every=np.inf, states_V_target=()): """ policy is a function that take state as input and returns an action """ statistics = trange(num_episodes) test_error = np.array([]) for e in statistics: is_terminal = False num_steps = 0 state = self.env.reset() action = policy(state) state_sequence = np.empty((state.shape[0], max_episode_length + 1), dtype=np.float64, order='C') state_sequence[:, 0] = state[:, 0] reward_sequence = np.empty(max_episode_length, dtype=np.float64, order='C') while num_steps < max_episode_length and not is_terminal: num_steps += 1 state, reward, is_terminal = self.env.step(action) action = policy(state) state_sequence[:, num_steps] = state[:, 0] reward_sequence[num_steps - 1] = reward state_sequence = state_sequence[:, 0:num_steps + 1] reward_sequence = reward_sequence[0:num_steps] if self.D.shape[1] == 0: traj = state_sequence[:, 0][:, np.newaxis] self.D = traj self.V_D = self.V_mu(state_sequence[:, 0][:, np.newaxis]) self.K_inv = 1 / self.kernel(traj, traj) self.A = np.array([[1]]) self.alpha_ = np.array([[0]]) self.C_ = np.array([[0]]) self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D) self.update(state_sequence, reward_sequence) statistics.set_postfix(epi_length=num_steps, dict_size=self.D. shape[1], cumm_cost=np.sum(reward_sequence)) if e % test_every == 0 and len(states_V_target) == 2: V = self.get_value_function(states_V_target[0]) test_error = np.concatenate((test_error, np.array([np.mean( np.abs(V - states_V_target[1]))]))) return test_error def get_value_function(self, states): if self.D.shape[1] == 0: return self.V_mu(states) else: return self.V_mu(states) + np.dot(self.kernel(self.D, states).T, self.diff_alpha_CV_D) <|reserved_special_token_1|> from tqdm import trange import numpy as np class GPTD_fixedGrid: def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]): self.env = env self.gamma = gamma self.sigma0 = sigma0 self.kernel = kernel.kernel if not V_mu: V_mu = lambda s: np.zeros((s.shape[1], 1)) self.V_mu = V_mu self.V_D = self.V_mu(D) self.D = D self.A = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C') self.A[-1, 0] = 1 K = self.kernel(self.D, self.D) self.K_inv = np.linalg.inv(K) self.alpha_ = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C') self.C_ = np.zeros((self.D.shape[1], self.D.shape[1]), dtype=np. float64, order='C') self.diff_alpha_CV_D = np.empty((self.D.shape[1], 1), dtype=np. float64, order='C') def k_(self, x): if len(x.shape) == 1: x = x[:, np.newaxis] assert len(x.shape) == 2, 'Check state dimensions' return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1)) def update(self, state_sequence, reward_sequence): """ Update GP after observing states (state_sequence) and rewards (reward_sequence) """ for i in range(reward_sequence.shape[0]): trajt_1 = state_sequence[:, i][:, np.newaxis] trajt = state_sequence[:, i + 1][:, np.newaxis] k_t_1 = self.kernel(self.D, trajt_1) k_t = self.kernel(self.D, trajt) ktt = self.kernel(trajt, trajt) at = np.dot(self.K_inv, k_t) delk_t_1 = k_t_1 - self.gamma * k_t ct = np.dot(self.C_, delk_t_1) - (self.A - self.gamma * at) st = self.sigma0 ** 2 - np.dot(ct.T, delk_t_1) diff_r = np.dot(delk_t_1.T, self.alpha_)[0, 0] - reward_sequence[i] self.alpha_ = self.alpha_ + ct / st * diff_r self.C_ = self.C_ + np.dot(ct, ct.T) / st self.A = at assert not np.isnan(self.alpha_).any( ), 'Check alpha for NaN values' self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D) def build_posterior(self, policy, num_episodes, max_episode_length, test_every=np.inf, states_V_target=()): """ policy is a function that take state as input and returns an action """ statistics = trange(num_episodes) test_error = np.array([]) for e in statistics: is_terminal = False num_steps = 0 state = self.env.reset() action = policy(state) state_sequence = np.empty((state.shape[0], max_episode_length + 1), dtype=np.float64, order='C') state_sequence[:, 0] = state[:, 0] reward_sequence = np.empty(max_episode_length, dtype=np.float64, order='C') while num_steps < max_episode_length and not is_terminal: num_steps += 1 state, reward, is_terminal = self.env.step(action) action = policy(state) state_sequence[:, num_steps] = state[:, 0] reward_sequence[num_steps - 1] = reward state_sequence = state_sequence[:, 0:num_steps + 1] reward_sequence = reward_sequence[0:num_steps] if self.D.shape[1] == 0: traj = state_sequence[:, 0][:, np.newaxis] self.D = traj self.V_D = self.V_mu(state_sequence[:, 0][:, np.newaxis]) self.K_inv = 1 / self.kernel(traj, traj) self.A = np.array([[1]]) self.alpha_ = np.array([[0]]) self.C_ = np.array([[0]]) self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D) self.update(state_sequence, reward_sequence) statistics.set_postfix(epi_length=num_steps, dict_size=self.D. shape[1], cumm_cost=np.sum(reward_sequence)) if e % test_every == 0 and len(states_V_target) == 2: V = self.get_value_function(states_V_target[0]) test_error = np.concatenate((test_error, np.array([np.mean( np.abs(V - states_V_target[1]))]))) return test_error def get_value_function(self, states): if self.D.shape[1] == 0: return self.V_mu(states) else: return self.V_mu(states) + np.dot(self.kernel(self.D, states).T, self.diff_alpha_CV_D) <|reserved_special_token_1|> from tqdm import trange import numpy as np class GPTD_fixedGrid: def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]): self.env = env self.gamma = gamma self.sigma0 = sigma0 self.kernel = kernel.kernel if (not V_mu): V_mu = lambda s: np.zeros((s.shape[1],1)) self.V_mu = V_mu self.V_D = self.V_mu(D) self.D = D # self.D = np.concatenate((self.D, self.V_D.T), axis=0) # Use V_mu in computing distances! self.A = np.zeros((self.D.shape[1],1), dtype=np.float64, order='C') self.A[-1,0] = 1 K = self.kernel(self.D, self.D) self.K_inv = np.linalg.inv(K) self.alpha_ = np.zeros((self.D.shape[1],1), dtype=np.float64, order='C') self.C_ = np.zeros((self.D.shape[1],self.D.shape[1]), dtype=np.float64, order='C') self.diff_alpha_CV_D = np.empty((self.D.shape[1],1), dtype=np.float64, order='C') def k_(self,x): if (len(x.shape)==1): x = x[:,np.newaxis] assert len(x.shape)==2, "Check state dimensions" return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1)) def update(self, state_sequence, reward_sequence): """ Update GP after observing states (state_sequence) and rewards (reward_sequence) """ for i in range(reward_sequence.shape[0]): trajt_1 = state_sequence[:,i][:,np.newaxis] # No use of V_mu in computing distances! trajt = state_sequence[:,i+1][:,np.newaxis] # trajt_1 = np.concatenate((trajt_1, self.V_mu(trajt_1)), axis=0) # Use V_mu as well # trajt = np.concatenate((trajt, self.V_mu(trajt)), axis=0) k_t_1 = self.kernel(self.D, trajt_1) k_t = self.kernel(self.D, trajt) ktt = self.kernel(trajt, trajt) at = np.dot(self.K_inv, k_t) delk_t_1 = k_t_1 - self.gamma*k_t ct = np.dot(self.C_, delk_t_1) - (self.A - self.gamma*at) st = self.sigma0**2 - np.dot(ct.T, delk_t_1) diff_r = np.dot(delk_t_1.T, self.alpha_)[0,0] - reward_sequence[i] self.alpha_ = self.alpha_ + ct/st*diff_r self.C_ = self.C_ + np.dot(ct, ct.T)/st self.A = at assert (not np.isnan(self.alpha_).any()), "Check alpha for NaN values" self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D) def build_posterior(self, policy, num_episodes, max_episode_length, test_every=np.inf, states_V_target=()): """ policy is a function that take state as input and returns an action """ statistics = trange(num_episodes) test_error = np.array([]) for e in statistics: is_terminal = False num_steps = 0 state = self.env.reset() action = policy(state) state_sequence = np.empty((state.shape[0], max_episode_length+1), dtype=np.float64, order='C') state_sequence[:, 0] = state[:,0] reward_sequence = np.empty(max_episode_length, dtype=np.float64, order='C') while ((num_steps < max_episode_length) and (not is_terminal)): num_steps+=1 state, reward, is_terminal = self.env.step(action) action = policy(state) state_sequence[:, num_steps] = state[:,0] reward_sequence[num_steps-1] = reward state_sequence = state_sequence[:, 0:(num_steps+1)] reward_sequence = reward_sequence[0:num_steps] if (self.D.shape[1]==0): traj = state_sequence[:,0][:,np.newaxis] self.D = traj self.V_D = self.V_mu(state_sequence[:,0][:,np.newaxis]) self.K_inv = 1/self.kernel(traj, traj) self.A = np.array([[1]]) self.alpha_ = np.array([[0]]) self.C_= np.array([[0]]) self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D) self.update(state_sequence, reward_sequence) statistics.set_postfix(epi_length=num_steps, dict_size=self.D.shape[1], cumm_cost=np.sum(reward_sequence)) if (e%test_every==0 and len(states_V_target)==2): V = self.get_value_function(states_V_target[0]) test_error = np.concatenate((test_error, np.array([np.mean(np.abs(V - states_V_target[1]))]))) return test_error def get_value_function(self, states): if (self.D.shape[1]==0): return self.V_mu(states) else: return self.V_mu(states) + np.dot(self.kernel(self.D, states).T, self.diff_alpha_CV_D)
flexible
{ "blob_id": "92eaceb46974ba3a5944300139d5929d44673181", "index": 1223, "step-1": "<mask token>\n\n\nclass GPTD_fixedGrid:\n\n def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]):\n self.env = env\n self.gamma = gamma\n self.sigma0 = sigma0\n self.kernel = kernel.kernel\n if not V_mu:\n V_mu = lambda s: np.zeros((s.shape[1], 1))\n self.V_mu = V_mu\n self.V_D = self.V_mu(D)\n self.D = D\n self.A = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C')\n self.A[-1, 0] = 1\n K = self.kernel(self.D, self.D)\n self.K_inv = np.linalg.inv(K)\n self.alpha_ = np.zeros((self.D.shape[1], 1), dtype=np.float64,\n order='C')\n self.C_ = np.zeros((self.D.shape[1], self.D.shape[1]), dtype=np.\n float64, order='C')\n self.diff_alpha_CV_D = np.empty((self.D.shape[1], 1), dtype=np.\n float64, order='C')\n\n def k_(self, x):\n if len(x.shape) == 1:\n x = x[:, np.newaxis]\n assert len(x.shape) == 2, 'Check state dimensions'\n return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1))\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass GPTD_fixedGrid:\n\n def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]):\n self.env = env\n self.gamma = gamma\n self.sigma0 = sigma0\n self.kernel = kernel.kernel\n if not V_mu:\n V_mu = lambda s: np.zeros((s.shape[1], 1))\n self.V_mu = V_mu\n self.V_D = self.V_mu(D)\n self.D = D\n self.A = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C')\n self.A[-1, 0] = 1\n K = self.kernel(self.D, self.D)\n self.K_inv = np.linalg.inv(K)\n self.alpha_ = np.zeros((self.D.shape[1], 1), dtype=np.float64,\n order='C')\n self.C_ = np.zeros((self.D.shape[1], self.D.shape[1]), dtype=np.\n float64, order='C')\n self.diff_alpha_CV_D = np.empty((self.D.shape[1], 1), dtype=np.\n float64, order='C')\n\n def k_(self, x):\n if len(x.shape) == 1:\n x = x[:, np.newaxis]\n assert len(x.shape) == 2, 'Check state dimensions'\n return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1))\n\n def update(self, state_sequence, reward_sequence):\n \"\"\"\n Update GP after observing states (state_sequence) and rewards (reward_sequence)\n \"\"\"\n for i in range(reward_sequence.shape[0]):\n trajt_1 = state_sequence[:, i][:, np.newaxis]\n trajt = state_sequence[:, i + 1][:, np.newaxis]\n k_t_1 = self.kernel(self.D, trajt_1)\n k_t = self.kernel(self.D, trajt)\n ktt = self.kernel(trajt, trajt)\n at = np.dot(self.K_inv, k_t)\n delk_t_1 = k_t_1 - self.gamma * k_t\n ct = np.dot(self.C_, delk_t_1) - (self.A - self.gamma * at)\n st = self.sigma0 ** 2 - np.dot(ct.T, delk_t_1)\n diff_r = np.dot(delk_t_1.T, self.alpha_)[0, 0] - reward_sequence[i]\n self.alpha_ = self.alpha_ + ct / st * diff_r\n self.C_ = self.C_ + np.dot(ct, ct.T) / st\n self.A = at\n assert not np.isnan(self.alpha_).any(\n ), 'Check alpha for NaN values'\n self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D)\n <mask token>\n\n def get_value_function(self, states):\n if self.D.shape[1] == 0:\n return self.V_mu(states)\n else:\n return self.V_mu(states) + np.dot(self.kernel(self.D, states).T,\n self.diff_alpha_CV_D)\n", "step-3": "<mask token>\n\n\nclass GPTD_fixedGrid:\n\n def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]):\n self.env = env\n self.gamma = gamma\n self.sigma0 = sigma0\n self.kernel = kernel.kernel\n if not V_mu:\n V_mu = lambda s: np.zeros((s.shape[1], 1))\n self.V_mu = V_mu\n self.V_D = self.V_mu(D)\n self.D = D\n self.A = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C')\n self.A[-1, 0] = 1\n K = self.kernel(self.D, self.D)\n self.K_inv = np.linalg.inv(K)\n self.alpha_ = np.zeros((self.D.shape[1], 1), dtype=np.float64,\n order='C')\n self.C_ = np.zeros((self.D.shape[1], self.D.shape[1]), dtype=np.\n float64, order='C')\n self.diff_alpha_CV_D = np.empty((self.D.shape[1], 1), dtype=np.\n float64, order='C')\n\n def k_(self, x):\n if len(x.shape) == 1:\n x = x[:, np.newaxis]\n assert len(x.shape) == 2, 'Check state dimensions'\n return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1))\n\n def update(self, state_sequence, reward_sequence):\n \"\"\"\n Update GP after observing states (state_sequence) and rewards (reward_sequence)\n \"\"\"\n for i in range(reward_sequence.shape[0]):\n trajt_1 = state_sequence[:, i][:, np.newaxis]\n trajt = state_sequence[:, i + 1][:, np.newaxis]\n k_t_1 = self.kernel(self.D, trajt_1)\n k_t = self.kernel(self.D, trajt)\n ktt = self.kernel(trajt, trajt)\n at = np.dot(self.K_inv, k_t)\n delk_t_1 = k_t_1 - self.gamma * k_t\n ct = np.dot(self.C_, delk_t_1) - (self.A - self.gamma * at)\n st = self.sigma0 ** 2 - np.dot(ct.T, delk_t_1)\n diff_r = np.dot(delk_t_1.T, self.alpha_)[0, 0] - reward_sequence[i]\n self.alpha_ = self.alpha_ + ct / st * diff_r\n self.C_ = self.C_ + np.dot(ct, ct.T) / st\n self.A = at\n assert not np.isnan(self.alpha_).any(\n ), 'Check alpha for NaN values'\n self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D)\n\n def build_posterior(self, policy, num_episodes, max_episode_length,\n test_every=np.inf, states_V_target=()):\n \"\"\"\n policy is a function that take state as input and returns an action\n \"\"\"\n statistics = trange(num_episodes)\n test_error = np.array([])\n for e in statistics:\n is_terminal = False\n num_steps = 0\n state = self.env.reset()\n action = policy(state)\n state_sequence = np.empty((state.shape[0], max_episode_length +\n 1), dtype=np.float64, order='C')\n state_sequence[:, 0] = state[:, 0]\n reward_sequence = np.empty(max_episode_length, dtype=np.float64,\n order='C')\n while num_steps < max_episode_length and not is_terminal:\n num_steps += 1\n state, reward, is_terminal = self.env.step(action)\n action = policy(state)\n state_sequence[:, num_steps] = state[:, 0]\n reward_sequence[num_steps - 1] = reward\n state_sequence = state_sequence[:, 0:num_steps + 1]\n reward_sequence = reward_sequence[0:num_steps]\n if self.D.shape[1] == 0:\n traj = state_sequence[:, 0][:, np.newaxis]\n self.D = traj\n self.V_D = self.V_mu(state_sequence[:, 0][:, np.newaxis])\n self.K_inv = 1 / self.kernel(traj, traj)\n self.A = np.array([[1]])\n self.alpha_ = np.array([[0]])\n self.C_ = np.array([[0]])\n self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D)\n self.update(state_sequence, reward_sequence)\n statistics.set_postfix(epi_length=num_steps, dict_size=self.D.\n shape[1], cumm_cost=np.sum(reward_sequence))\n if e % test_every == 0 and len(states_V_target) == 2:\n V = self.get_value_function(states_V_target[0])\n test_error = np.concatenate((test_error, np.array([np.mean(\n np.abs(V - states_V_target[1]))])))\n return test_error\n\n def get_value_function(self, states):\n if self.D.shape[1] == 0:\n return self.V_mu(states)\n else:\n return self.V_mu(states) + np.dot(self.kernel(self.D, states).T,\n self.diff_alpha_CV_D)\n", "step-4": "from tqdm import trange\nimport numpy as np\n\n\nclass GPTD_fixedGrid:\n\n def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]):\n self.env = env\n self.gamma = gamma\n self.sigma0 = sigma0\n self.kernel = kernel.kernel\n if not V_mu:\n V_mu = lambda s: np.zeros((s.shape[1], 1))\n self.V_mu = V_mu\n self.V_D = self.V_mu(D)\n self.D = D\n self.A = np.zeros((self.D.shape[1], 1), dtype=np.float64, order='C')\n self.A[-1, 0] = 1\n K = self.kernel(self.D, self.D)\n self.K_inv = np.linalg.inv(K)\n self.alpha_ = np.zeros((self.D.shape[1], 1), dtype=np.float64,\n order='C')\n self.C_ = np.zeros((self.D.shape[1], self.D.shape[1]), dtype=np.\n float64, order='C')\n self.diff_alpha_CV_D = np.empty((self.D.shape[1], 1), dtype=np.\n float64, order='C')\n\n def k_(self, x):\n if len(x.shape) == 1:\n x = x[:, np.newaxis]\n assert len(x.shape) == 2, 'Check state dimensions'\n return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1))\n\n def update(self, state_sequence, reward_sequence):\n \"\"\"\n Update GP after observing states (state_sequence) and rewards (reward_sequence)\n \"\"\"\n for i in range(reward_sequence.shape[0]):\n trajt_1 = state_sequence[:, i][:, np.newaxis]\n trajt = state_sequence[:, i + 1][:, np.newaxis]\n k_t_1 = self.kernel(self.D, trajt_1)\n k_t = self.kernel(self.D, trajt)\n ktt = self.kernel(trajt, trajt)\n at = np.dot(self.K_inv, k_t)\n delk_t_1 = k_t_1 - self.gamma * k_t\n ct = np.dot(self.C_, delk_t_1) - (self.A - self.gamma * at)\n st = self.sigma0 ** 2 - np.dot(ct.T, delk_t_1)\n diff_r = np.dot(delk_t_1.T, self.alpha_)[0, 0] - reward_sequence[i]\n self.alpha_ = self.alpha_ + ct / st * diff_r\n self.C_ = self.C_ + np.dot(ct, ct.T) / st\n self.A = at\n assert not np.isnan(self.alpha_).any(\n ), 'Check alpha for NaN values'\n self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D)\n\n def build_posterior(self, policy, num_episodes, max_episode_length,\n test_every=np.inf, states_V_target=()):\n \"\"\"\n policy is a function that take state as input and returns an action\n \"\"\"\n statistics = trange(num_episodes)\n test_error = np.array([])\n for e in statistics:\n is_terminal = False\n num_steps = 0\n state = self.env.reset()\n action = policy(state)\n state_sequence = np.empty((state.shape[0], max_episode_length +\n 1), dtype=np.float64, order='C')\n state_sequence[:, 0] = state[:, 0]\n reward_sequence = np.empty(max_episode_length, dtype=np.float64,\n order='C')\n while num_steps < max_episode_length and not is_terminal:\n num_steps += 1\n state, reward, is_terminal = self.env.step(action)\n action = policy(state)\n state_sequence[:, num_steps] = state[:, 0]\n reward_sequence[num_steps - 1] = reward\n state_sequence = state_sequence[:, 0:num_steps + 1]\n reward_sequence = reward_sequence[0:num_steps]\n if self.D.shape[1] == 0:\n traj = state_sequence[:, 0][:, np.newaxis]\n self.D = traj\n self.V_D = self.V_mu(state_sequence[:, 0][:, np.newaxis])\n self.K_inv = 1 / self.kernel(traj, traj)\n self.A = np.array([[1]])\n self.alpha_ = np.array([[0]])\n self.C_ = np.array([[0]])\n self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D)\n self.update(state_sequence, reward_sequence)\n statistics.set_postfix(epi_length=num_steps, dict_size=self.D.\n shape[1], cumm_cost=np.sum(reward_sequence))\n if e % test_every == 0 and len(states_V_target) == 2:\n V = self.get_value_function(states_V_target[0])\n test_error = np.concatenate((test_error, np.array([np.mean(\n np.abs(V - states_V_target[1]))])))\n return test_error\n\n def get_value_function(self, states):\n if self.D.shape[1] == 0:\n return self.V_mu(states)\n else:\n return self.V_mu(states) + np.dot(self.kernel(self.D, states).T,\n self.diff_alpha_CV_D)\n", "step-5": "from tqdm import trange\nimport numpy as np\n\nclass GPTD_fixedGrid:\n def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]):\n \n self.env = env\n self.gamma = gamma\n self.sigma0 = sigma0\n self.kernel = kernel.kernel\n if (not V_mu):\n V_mu = lambda s: np.zeros((s.shape[1],1))\n self.V_mu = V_mu\n self.V_D = self.V_mu(D)\n self.D = D\n # self.D = np.concatenate((self.D, self.V_D.T), axis=0) # Use V_mu in computing distances!\n self.A = np.zeros((self.D.shape[1],1), dtype=np.float64, order='C')\n self.A[-1,0] = 1\n K = self.kernel(self.D, self.D)\n self.K_inv = np.linalg.inv(K)\n self.alpha_ = np.zeros((self.D.shape[1],1), dtype=np.float64, order='C')\n self.C_ = np.zeros((self.D.shape[1],self.D.shape[1]), dtype=np.float64, order='C')\n self.diff_alpha_CV_D = np.empty((self.D.shape[1],1), dtype=np.float64, order='C')\n \n def k_(self,x):\n\n if (len(x.shape)==1):\n x = x[:,np.newaxis]\n assert len(x.shape)==2, \"Check state dimensions\"\n\n return self.kernel(self.D, np.repeat(x, self.D.shape[1], axis=1))\n\n def update(self, state_sequence, reward_sequence):\n \"\"\"\n Update GP after observing states (state_sequence) and rewards (reward_sequence)\n \"\"\"\n\n for i in range(reward_sequence.shape[0]):\n\n trajt_1 = state_sequence[:,i][:,np.newaxis] # No use of V_mu in computing distances!\n trajt = state_sequence[:,i+1][:,np.newaxis]\n # trajt_1 = np.concatenate((trajt_1, self.V_mu(trajt_1)), axis=0) # Use V_mu as well\n # trajt = np.concatenate((trajt, self.V_mu(trajt)), axis=0)\n k_t_1 = self.kernel(self.D, trajt_1)\n k_t = self.kernel(self.D, trajt)\n ktt = self.kernel(trajt, trajt)\n at = np.dot(self.K_inv, k_t)\n delk_t_1 = k_t_1 - self.gamma*k_t\n\n ct = np.dot(self.C_, delk_t_1) - (self.A - self.gamma*at)\n st = self.sigma0**2 - np.dot(ct.T, delk_t_1)\n\n diff_r = np.dot(delk_t_1.T, self.alpha_)[0,0] - reward_sequence[i]\n self.alpha_ = self.alpha_ + ct/st*diff_r\n\n self.C_ = self.C_ + np.dot(ct, ct.T)/st\n\n self.A = at\n\n assert (not np.isnan(self.alpha_).any()), \"Check alpha for NaN values\"\n\n self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D)\n\n def build_posterior(self, policy, num_episodes, max_episode_length, test_every=np.inf, states_V_target=()):\n \"\"\"\n policy is a function that take state as input and returns an action\n \"\"\"\n\n statistics = trange(num_episodes)\n test_error = np.array([])\n\n for e in statistics:\n is_terminal = False\n num_steps = 0\n state = self.env.reset()\n action = policy(state)\n \n state_sequence = np.empty((state.shape[0], max_episode_length+1), dtype=np.float64, order='C')\n state_sequence[:, 0] = state[:,0]\n reward_sequence = np.empty(max_episode_length, dtype=np.float64, order='C')\n \n while ((num_steps < max_episode_length) and (not is_terminal)):\n num_steps+=1\n state, reward, is_terminal = self.env.step(action)\n action = policy(state)\n\n state_sequence[:, num_steps] = state[:,0]\n reward_sequence[num_steps-1] = reward\n\n state_sequence = state_sequence[:, 0:(num_steps+1)]\n reward_sequence = reward_sequence[0:num_steps]\n\n if (self.D.shape[1]==0):\n\n traj = state_sequence[:,0][:,np.newaxis]\n self.D = traj\n self.V_D = self.V_mu(state_sequence[:,0][:,np.newaxis])\n self.K_inv = 1/self.kernel(traj, traj)\n self.A = np.array([[1]])\n self.alpha_ = np.array([[0]])\n self.C_= np.array([[0]])\n self.diff_alpha_CV_D = self.alpha_ - np.dot(self.C_, self.V_D)\n\n self.update(state_sequence, reward_sequence)\n statistics.set_postfix(epi_length=num_steps, dict_size=self.D.shape[1], cumm_cost=np.sum(reward_sequence))\n if (e%test_every==0 and len(states_V_target)==2):\n V = self.get_value_function(states_V_target[0])\n test_error = np.concatenate((test_error, np.array([np.mean(np.abs(V - states_V_target[1]))])))\n\n return test_error\n \n def get_value_function(self, states):\n\n if (self.D.shape[1]==0):\n return self.V_mu(states) \n\n else:\n return self.V_mu(states) + np.dot(self.kernel(self.D, states).T, self.diff_alpha_CV_D)", "step-ids": [ 3, 5, 6, 7, 8 ] }
[ 3, 5, 6, 7, 8 ]
import cv2 import numpy as np import copy imgpath = 'D:\\DIP-Project1/b.jpg' img = cv2.imread(imgpath) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow('img', img) row = len(img) col = len(img[0]) def medianflt(img, i, j, msize, mr, mc): pxls = [] for a in range(msize): for b in range(msize): mi = i + a - mr mj = j + b - mc pxls.append(img[mi][mj]) pxls.sort() return pxls[msize * msize // 2] def orderstatistic(img, row, col, msize=3): rimg = copy.deepcopy(img) mr = (msize - 1) // 2 mc = (msize - 1) // 2 for i in range(mr, row - mr - 1): for j in range(mc, col - mc - 1): rimg[i][j] = medianflt(img, i, j, msize, mr, mc) return rimg d0 = 9 rimg = orderstatistic(img, row, col, d0) cv2.imshow('aimg', rimg) cv2.waitKey(0)
normal
{ "blob_id": "cfcce8c760f6ba49ce450d78782cb8f3b5fc1188", "index": 2857, "step-1": "<mask token>\n\n\ndef medianflt(img, i, j, msize, mr, mc):\n pxls = []\n for a in range(msize):\n for b in range(msize):\n mi = i + a - mr\n mj = j + b - mc\n pxls.append(img[mi][mj])\n pxls.sort()\n return pxls[msize * msize // 2]\n\n\ndef orderstatistic(img, row, col, msize=3):\n rimg = copy.deepcopy(img)\n mr = (msize - 1) // 2\n mc = (msize - 1) // 2\n for i in range(mr, row - mr - 1):\n for j in range(mc, col - mc - 1):\n rimg[i][j] = medianflt(img, i, j, msize, mr, mc)\n return rimg\n\n\n<mask token>\n", "step-2": "<mask token>\ncv2.imshow('img', img)\n<mask token>\n\n\ndef medianflt(img, i, j, msize, mr, mc):\n pxls = []\n for a in range(msize):\n for b in range(msize):\n mi = i + a - mr\n mj = j + b - mc\n pxls.append(img[mi][mj])\n pxls.sort()\n return pxls[msize * msize // 2]\n\n\ndef orderstatistic(img, row, col, msize=3):\n rimg = copy.deepcopy(img)\n mr = (msize - 1) // 2\n mc = (msize - 1) // 2\n for i in range(mr, row - mr - 1):\n for j in range(mc, col - mc - 1):\n rimg[i][j] = medianflt(img, i, j, msize, mr, mc)\n return rimg\n\n\n<mask token>\ncv2.imshow('aimg', rimg)\ncv2.waitKey(0)\n", "step-3": "<mask token>\nimgpath = 'D:\\\\DIP-Project1/b.jpg'\nimg = cv2.imread(imgpath)\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\ncv2.imshow('img', img)\nrow = len(img)\ncol = len(img[0])\n\n\ndef medianflt(img, i, j, msize, mr, mc):\n pxls = []\n for a in range(msize):\n for b in range(msize):\n mi = i + a - mr\n mj = j + b - mc\n pxls.append(img[mi][mj])\n pxls.sort()\n return pxls[msize * msize // 2]\n\n\ndef orderstatistic(img, row, col, msize=3):\n rimg = copy.deepcopy(img)\n mr = (msize - 1) // 2\n mc = (msize - 1) // 2\n for i in range(mr, row - mr - 1):\n for j in range(mc, col - mc - 1):\n rimg[i][j] = medianflt(img, i, j, msize, mr, mc)\n return rimg\n\n\nd0 = 9\nrimg = orderstatistic(img, row, col, d0)\ncv2.imshow('aimg', rimg)\ncv2.waitKey(0)\n", "step-4": "import cv2\nimport numpy as np\nimport copy\nimgpath = 'D:\\\\DIP-Project1/b.jpg'\nimg = cv2.imread(imgpath)\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\ncv2.imshow('img', img)\nrow = len(img)\ncol = len(img[0])\n\n\ndef medianflt(img, i, j, msize, mr, mc):\n pxls = []\n for a in range(msize):\n for b in range(msize):\n mi = i + a - mr\n mj = j + b - mc\n pxls.append(img[mi][mj])\n pxls.sort()\n return pxls[msize * msize // 2]\n\n\ndef orderstatistic(img, row, col, msize=3):\n rimg = copy.deepcopy(img)\n mr = (msize - 1) // 2\n mc = (msize - 1) // 2\n for i in range(mr, row - mr - 1):\n for j in range(mc, col - mc - 1):\n rimg[i][j] = medianflt(img, i, j, msize, mr, mc)\n return rimg\n\n\nd0 = 9\nrimg = orderstatistic(img, row, col, d0)\ncv2.imshow('aimg', rimg)\ncv2.waitKey(0)\n", "step-5": null, "step-ids": [ 2, 3, 4, 5 ] }
[ 2, 3, 4, 5 ]
<|reserved_special_token_0|> class Post: def __init__(self, date, text, medias): self.date = date self.text = text self.medias = medias self.dcim = [] self.daterank = 0 self.extra = False def __lt__(self, other): return self.date < other.date @classmethod def from_markdown(cls, post): m = re.match('\\[(\\d\\d\\d\\d/\\d\\d/\\d\\d)\\]\\n*', post[0]) if m: date = m.group(1).replace('/', '') if not validate_date(date): error('Incorrect date value:', date) del post[0] else: error('No date in post', ' '.join(post)) while post and not post[0].strip(): del post[0] text = '' while post and not re.match('!?\\[\\]', post[0]): text += post[0] del post[0] text = re.sub('\\n\\n$', '\n', text) medias = list() while post and (match := re.match('!?\\[\\]\\((.*)\\)', post[0])): media = match.group(1) caption = None del post[0] if post and not re.match('!?\\[\\]', post[0]): caption = post[0].strip() del post[0] if match.group(0)[0] == '!': medias.append(PostImage(caption, media)) else: medias.append(PostVideo(caption, media)) return cls(date, text, medias) @classmethod def from_date(cls, date): dt = datetime.datetime.strptime(date, '%Y%m%d') datetext = dt.strftime('%A %d %B %Y').capitalize() post = cls(date, text=datetext, medias=[]) post.daterank = 1 return post def to_html(self, args, target='regular'): if target == 'regular': if args.diary: return self.to_html_diary(args) else: return self.to_html_regular(args) if target == 'blogger': return self.to_html_blogger() def to_html_regular(self, args): html = list() if self.text: html.append(markdown.markdown(self.text)) subdirs, dcim = dispatch_post_items(self.dcim) if self.dcim: html.append(SEP) for media in subdirs: html.append(media.to_html_dcim(args)) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) return html def to_html_diary(self, args): html = list() if self.extra: html.append('<div class="extra">') if self.text: html.append(markdown.markdown(self.text)) if self.medias: html.append(f'<div id="gallery-blog-{self.date}-{self.daterank}">') for media in self.medias: html.append(media.to_html_post(args)) html.append('</div>') _, dcim = dispatch_post_items(self.dcim) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') html.append(SEP) for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) if self.extra: html.append('</div>') return html def to_html_blogger(self): html = list() html.append(markdown.markdown(self.text)) for image in self.medias: html.append(image.to_html_blogger()) html.append(SEP) return html class PostItem: def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''): self.caption = caption self.uri = uri self.basename = os.path.basename(uri) self.thumb = thumb self.thumbsize = thumbsize self.descr = descr self.resized_url = None class PostImage(PostItem): def to_markdown(self): if not self.caption: return '![](%s)' % (self.uri,) else: return '![](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, * self.thumbsize, descr) def to_html_blogger(self): if not self.caption: return BIMGPAT % (self.uri, self.resized_url) else: return f'{BIMGPAT}\n{CAPTION_PAT}' % (self.uri, self. resized_url, self.caption) class PostVideo(PostItem): def to_markdown(self): if not self.caption: return '[](%s)' % (self.uri,) else: return '[](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, * self.thumbsize, descr) def to_html_blogger(self): x = f'<p style="text-align: center;">{self.iframe}</p>' if not self.caption: return x else: return f'%s\n{CAPTION_PAT}' % (x, self.caption) class PostSubdir(PostItem): def to_html_dcim(self, args): basename = os.path.basename(self.htmname) posts = self.posts title = self.caption print_html(args, posts, title, self.htmname) if not self.caption: return DIRPOST % (basename, self.thumb, *self.thumbsize) else: return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize, self.caption) <|reserved_special_token_0|> def parse_markdown(filename): """ Generate Post objects from markdown. Date must be present in each post and posts must be ordrered by date. """ if not os.path.exists(filename): error('File not found', filename) posts = list() with open(filename, encoding='utf-8') as f: line = next(f) if line.startswith('# '): title = line[2:].strip() record = [] next(f) else: title = None record = [line] for line in f: if not line.startswith('___'): record.append(line) else: posts.append(Post.from_markdown(record)) record = [] daterank = defaultdict(int) for post in posts: daterank[post.date] += 1 post.daterank = daterank[post.date] for post1, post2 in zip(posts[:-1], posts[1:]): if post1.date > post2.date: error('Posts are not ordered', f'{post1.date} > {post2.date}') return title, posts def print_markdown(posts, title, fullname): with open(fullname, 'wt', encoding='utf-8') as fdst: print(f'# {title}\n', file=fdst) for post in posts: date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]' print(date, file=fdst) if post.text: print(file=fdst) for line in post.text.splitlines(): if not line: print(file=fdst) else: for chunk in textwrap.wrap(line, width=78): print(chunk, file=fdst) if post.medias: print(file=fdst) for media in post.medias: print(media.to_markdown(), file=fdst) print('______', file=fdst) <|reserved_special_token_0|> def is_image_file(name): return os.path.splitext(name)[1].lower() in ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tif') <|reserved_special_token_0|> def is_media(name): return is_image_file(name) or is_video_file(name) <|reserved_special_token_0|> def date_from_name(name): if (match := re.search('(?:\\D|^)(\\d{8})(?:\\D|$)', name, re.ASCII)): digits = match.group(1) if validate_date(digits): return digits return None def date_from_item(filename): if (date := date_from_name(filename)): return date else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d') def time_from_name(name): if (match := re.search('(?:\\D|^)(\\d{8})\\D(\\d{6})(?:\\D|$)', name, re.ASCII)): digits = match.group(2) hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits [4:6]) if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60: return digits return None def time_from_item(filename): if (time := time_from_name(filename)): return time else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S') <|reserved_special_token_0|> def get_image_info(filename): date = date_from_item(filename) time = time_from_item(filename) img = Image.open(filename) width, height = img.size size = round(os.path.getsize(filename) / 1000000.0, 1) return (date, time, width, height, size ), f'{date} {time}, dim={width}x{height}, {size} MB' def get_video_info(filename, info_fullname): if os.path.exists(info_fullname): with open(info_fullname) as f: info = f.readline().split() date, time, width, height, size, duration, fps = info[0], info[1], int( info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6] ) formatted_info = format_video_info(date, time, width, height, size, duration, fps) return (date, time, width, height, size, duration, fps), formatted_info else: info, formatted_info = make_video_info(filename, info_fullname) with open(info_fullname, 'wt') as f: print(' '.join([str(_) for _ in info]), file=f) return info, formatted_info def make_video_info(filename, info_fullname): date = date_from_item(filename) time = time_from_item(filename) command = [*FFPROBE_CMD.split(), filename] try: output = check_output(command, stderr=STDOUT).decode() width, height, fps, duration = parse_ffprobe_output(output) size = round(os.path.getsize(filename) / 1000000.0, 1) output = format_video_info(date, time, width, height, size, duration, fps) except CalledProcessError as e: output = e.output.decode() warning(output) raise return (date, time, width, height, size, duration, fps), output def parse_ffprobe_output(ffprobe_output): match = re.match( '(\\d+),(\\d+),(\\d+)/(\\d+),(\\d+/\\d+).*\\s(\\d+\\.\\d+)', ffprobe_output, re.DOTALL) width = int(match.group(1)) height = int(match.group(2)) fps = round(int(match.group(3)) / int(match.group(4)), 1) duration = round(float(match.group(6))) return width, height, fps, duration def format_video_info(date, time, width, height, size, duration, fps): return ( f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB' ) <|reserved_special_token_0|> def size_thumbnail(width, height, maxdim): if width >= height: return maxdim, int(round(maxdim * height / width)) else: return int(round(maxdim * width / height)), maxdim def make_thumbnail_image(args, image_name, thumb_name, size): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_image(image_name, thumb_name, size) def create_thumbnail_image(image_name, thumb_name, size): imgobj = Image.open(image_name) if imgobj.mode != 'RGBA' and image_name.endswith('.jpg') and not ( image_name.endswith('.gif') and imgobj.info.get('transparency')): imgobj = imgobj.convert('RGBA') imgobj.thumbnail(size, Image.LANCZOS) imgobj = imgobj.convert('RGB') imgobj.save(thumb_name) def make_thumbnail_video(args, video_name, thumb_name, size, duration): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_video(args, video_name, thumb_name, size, duration) <|reserved_special_token_0|> def create_thumbnail_video(args, filename, thumbname, size, duration): delay = min(duration - 1, args.thumbnails.thumbdelay) sizearg = '%dx%d' % size command = ( 'ffmpeg -y -v error -itsoffset -%d -i "%s" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s "%s"' ) command = command % (delay, filename, sizearg, thumbname) result = os.system(command) try: img1 = Image.open(thumbname) except: warning('Unable to save thumbnail for', filename) return img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON))) width, height = img1.size img1.paste(img2, (6, height - 20 - 6), None) img1.save(thumbname) <|reserved_special_token_0|> def create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir): def size_thumbnail(width, height, xmax, ymax): width2 = xmax height2 = int(round(xmax * height / width)) if height2 < ymax: width2 = int(round(ymax * width / height)) height2 = ymax return width2, height2 thumblist = [os.path.basename(item.thumb) for item in items] widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size , thumblist) thumbnum = widthnum * heightnum img = Image.new('RGB', size, SUBDIR_BACKCOL) for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]): row = ind // widthnum col = ind % widthnum img2 = Image.open(os.path.join(thumbdir, thumb)) w, h = size_thumbnail(*img2.size, width[col], height[row]) cropdim = (w - width[col]) // 2, (h - height[row]) // 2, (w - width [col]) // 2 + width[col], (h - height[row]) // 2 + height[row] img2 = img2.resize((w, h), Image.LANCZOS) img2 = img2.crop(cropdim) img.paste(img2, (offsetx[col], offsety[row])) if os.path.exists(thumb_name): imgref = Image.open(thumb_name) byteio = io.BytesIO() img.save(byteio, 'JPEG') byteio.seek(0) imgnew = Image.open(byteio) diff = ImageChops.difference(imgnew, imgref) if diff.getbbox() is None: return img.save(thumb_name) <|reserved_special_token_0|> def list_of_htmlfiles_in_items(itemlist): htmlist = list() for item in itemlist: if type(item) == PostSubdir: htmlist.append(item.htmname) htmlist.extend(list_of_htmlfiles_in_items(item.sublist)) return htmlist def list_of_thumbnails(posts, diary=False): thumblist = list() for post in posts: thumblist.extend(list_of_thumbnails_in_items(post.medias)) if diary is False: thumblist.extend(list_of_thumbnails_in_items(post.dcim)) return thumblist def list_of_thumbnails_in_items(itemlist): thumblist = list() for item in itemlist: if type(item) == PostSubdir: thumblist.append(os.path.basename(item.thumb)) thumblist.extend(list_of_thumbnails_in_items(item.sublist)) else: thumblist.append(os.path.basename(item.thumb)) return thumblist def purge_htmlfiles(args, posts): """ Purge root dir from irrelevant html files """ htmlist = list_of_htmlfiles(args, posts) html_to_remove = list() for fullname in glob.glob(os.path.join(args.root, '*.htm*')): if fullname not in htmlist: html_to_remove.append(fullname) if len(html_to_remove) > args.thumbnails.threshold_htmlfiles: inpt = 'x' while inpt not in 'yn': inpt = input( f'{len(html_to_remove)} html files to remove. Continue [y|n]? ' ).lower() if inpt == 'n': return for name in html_to_remove: print('Removing html files', name) os.remove(name) def purge_thumbnails(args, thumbdir, posts, diary=False): """ Purge thumbnail dir from irrelevant thumbnails """ thumblist = list_of_thumbnails(posts, diary) thumbs_to_remove = list() for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')): if os.path.basename(fullname) not in thumblist: thumbs_to_remove.append(fullname) if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs: inpt = 'x' while inpt not in 'yn': inpt = input( f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? ' ).lower() if inpt == 'n': return for name in thumbs_to_remove: print('Removing thumbnail', name) os.remove(name) info_fullname = os.path.splitext(name)[0] + '.info' if os.path.exists(info_fullname): os.remove(info_fullname) def is_media_within_dates(fullname, dates): if is_media(fullname): if type(dates) == tuple: return dates[0] <= date_from_item(fullname) <= dates[1] else: return True else: return False def sorted_listdir(filelist): like_windows_explorer = True if not filelist: return filelist if like_windows_explorer: maxlen = max(len(os.path.splitext(name)[0]) for name in filelist) def keyfunc(name): root, ext = os.path.splitext(name.lower()) return root.ljust(maxlen, ' ') + ext else: keyfunc = str.lower return sorted(filelist, key=keyfunc) <|reserved_special_token_0|> def list_of_medias(args, sourcedir, recursive): """ Return the list of full paths for pictures and movies in source directory """ files = list_of_files(sourcedir, recursive) return [_ for _ in files if is_media_within_dates(_, args.dates)] <|reserved_special_token_0|> def dispatch_post_items(list_of_post_items): subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir] medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir] return subdirs, medias def create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax): if os.path.isfile(media_fullname): if is_image_file(media_fullname): return create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_subdir(args, media_fullname, sourcedir, thumbdir, key, thumbmax) def create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax ): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) try: info, infofmt = get_image_info(media_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize) return PostImage(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except PIL.UnidentifiedImageError: warning('Unable to read image', media_fullname) return None def create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax ): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) info_fullname = os.path.splitext(thumb_fullname)[0] + '.info' try: info, infofmt = get_video_info(media_fullname, info_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_video(args, media_fullname, thumb_fullname, thumbsize, duration=info[5]) return PostVideo(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except CalledProcessError: warning('Unable to read video', media_fullname) return None <|reserved_special_token_0|> def relative_name(media_fullname, sourcedir): """ /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg --> deeper2_deepest_OCT_20000112_000004.jpg /Gilles/Dev/journal/tests/subdir/deeper2/deepest --> deeper2_deepest """ x = os.path.relpath(media_fullname, sourcedir) x = x.replace('\\', '_').replace('/', '_').replace('#', '_') return x <|reserved_special_token_0|> def make_posts_from_diary(args): md_filename = os.path.join(args.root, 'index.md') if os.path.exists(md_filename): title, posts = parse_markdown(md_filename) else: error('File not found', md_filename) for post in posts: for media in post.medias: media_fullname = os.path.join(args.root, media.uri) item = create_item(args, media_fullname, args.root, args. thumbdir, 'post', 400) media.thumb = item.thumb media.thumbsize = item.thumbsize media.descr = item.descr return title, posts <|reserved_special_token_0|> def make_posts_from_subdir(args, dirname): if args.bydir is False: medias_ext = list_of_medias(args, dirname, args.recursive) else: medias_ext = list_of_medias_ext(args, dirname) postmedias = list() for item in medias_ext: postmedia = create_item(args, item, args.sourcedir, args.thumbdir, 'dcim', 300) if postmedia is not None: postmedias.append(postmedia) post = Post(date='00000000', text='', medias=[]) post.dcim = postmedias posts = [post] title = os.path.basename(args.sourcedir) or os.path.splitdrive(args. sourcedir)[0] return title, posts <|reserved_special_token_0|> def create_gallery(args): title, posts = make_posts(args, args.sourcedir) print_html(args, posts, title, os.path.join(args.dest, args.rootname), 'regular') purge_htmlfiles(args, posts) if args.diary and not args.sourcedir: purge_thumbnails(args, args.thumbdir, posts, diary=True) else: purge_thumbnails(args, args.thumbdir, posts) def create_diary(args): medias = list_of_medias(args, args.sourcedir, args.recursive) if args.dates == 'diary': assert 0 else: required_dates = {date_from_item(media) for media in medias} if type(args.dates) == tuple: date1, date2 = args.dates required_dates = {date for date in required_dates if date1 <= date <= date2} title = args.sourcedir posts = list() for date in sorted(required_dates): posts.append(Post.from_date(date)) os.makedirs(args.root, exist_ok=True) print_markdown(posts, title, os.path.join(args.root, 'index.md')) <|reserved_special_token_0|> def compare_image_buffers(imgbuf1, imgbuf2): """ return True if images read on file are identical, False otherwise """ with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2: img1 = Image.open(imgio1) img2 = Image.open(imgio2) diff = ImageChops.difference(img1, img2) return not diff.getbbox() def check_images(args, posts, online_images): result = True for post in posts: for media in post.medias: if type(media) is PostImage: if media.basename in online_images: with open(os.path.join(args.root, media.uri), 'rb') as f: imgbuf1 = f.read() try: with urlopen(online_images[media.basename][0]) as u: imgbuf2 = u.read() except FileNotFoundError: print('File not found', online_images[media. basename][0]) next if compare_image_buffers(imgbuf1, imgbuf2) is False: print('Files are different, upload', media.basename) elif 1: print('File already online', media.basename) else: print('File is absent, upload', media.basename) result = False elif type(media) is PostVideo: print('Video not checked', media.basename) else: assert False return result <|reserved_special_token_0|> def idempotence(args): """ For testing identity between a diary file and the fle obtained after reading and printing it. See testing. """ title, posts = parse_markdown(os.path.join(args.root, 'index.md')) print_markdown(posts, title, os.path.join(args.dest, 'index.md')) <|reserved_special_token_0|> class MyConfigParser(ConfigParser): """Add input checking.""" def __init__(self): ConfigParser.__init__(self, inline_comment_prefixes=(';',)) def error(self, section, entry): error('Missing or incorrect config value:', '[%s]%s' % (section, entry) ) def getint(self, section, entry, default=None): try: if default is None: return ConfigParser.getint(self, section, entry) else: return ConfigParser.getint(self, section, entry, raw=True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def getboolean(self, section, entry, default=None): try: if default is None: return ConfigParser.getboolean(self, section, entry) else: return ConfigParser.getboolean(self, section, entry, raw= True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def configfilename(params): return os.path.join(params.root, '.config.ini') def createconfig(config_filename): with open(config_filename, 'wt') as f: f.writelines(CONFIG_DEFAULTS) def read_config(params): config_filename = configfilename(params) try: if not os.path.exists(config_filename) or params.resetcfg: createconfig(config_filename) except: error('Error creating configuration file') try: getconfig(params, config_filename) except Exception as e: error('Error reading configuration file.', str(e), 'Use --resetcfg') <|reserved_special_token_0|> def setconfig_cmd(args): config_filename = configfilename(args) setconfig(config_filename, *args.setcfg) def update_config(args): updates = ('sourcedir', args.sourcedir), ('bydir', BOOL[args.bydir]), ( 'bydate', BOOL[args.bydate]), ('diary', BOOL[args.diary]), ('recursive' , BOOL[args.recursive]), ('dates', args.dates), ('github_pages', BOOL[args.github_pages]) cfgname = configfilename(args) with open(cfgname) as f: cfglines = [_.strip() for _ in f.readlines()] for key, value in updates: for iline, line in enumerate(cfglines): if line.startswith(key): cfglines[iline] = f'{key} = {value}' break with open(cfgname, 'wt') as f: for line in cfglines: print(line, file=f) def warning(*msg): print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) <|reserved_special_token_0|> def errorcode(msg): return ERRORS.splitlines().index(msg) + 1 def error(*msg): print(colorama.Fore.RED + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) sys.exit(errorcode(msg[0])) <|reserved_special_token_0|> def setup_part1(args): """ Made before reading config file (config file located in args.root). Check and normalize root path. """ args.rootarg = args.root rootext = os.path.splitext(args.rootarg)[1] if rootext == '': pass else: args.root = os.path.dirname(args.root) if args.root: args.root = os.path.abspath(args.root) if not os.path.isdir(args.root): if args.gallery: os.mkdir(args.root) else: error('Directory not found', args.root) def setup_part2(args): """ Made after reading config file. Check for ffmpeg in path. Create .thumbnails dir if necessary and create .nomedia in it. Copy photobox file to destination dir. Handle priority between command line and config file. """ if args.update: args.sourcedir = args.source.sourcedir args.bydir = args.source.bydir args.bydate = args.source.bydate args.diary = args.source.diary args.recursive = args.source.recursive args.dates = args.source.dates args.github_pages = args.source.github_pages elif args.gallery: args.source.sourcedir = args.sourcedir args.source.bydir = args.bydir args.source.bydate = args.bydate args.source.diary = args.diary args.source.recursive = args.recursive args.source.dates = args.dates args.source.github_pages = args.github_pages update_config(args) if args.github_pages: args.html_suffix = '.html' else: args.html_suffix = '.htm' rootext = os.path.splitext(args.rootarg)[1] if rootext: args.rootname = os.path.basename(args.rootarg) else: args.rootname = 'index' + args.html_suffix if args.sourcedir: args.sourcedir = os.path.abspath(args.sourcedir) if os.path.splitdrive(args.sourcedir)[0]: drive, rest = os.path.splitdrive(args.sourcedir) args.sourcedir = drive.upper() + rest if not os.path.isdir(args.sourcedir): error('Directory not found', args.sourcedir) elif args.gallery and args.diary is False and args.update is None: error('Directory not found', 'Use --sourcedir') if args.dest: args.dest = os.path.abspath(args.dest) if args.dest is None: args.dest = args.root if args.blogger and args.urlblogger is None: error('No blogger url (--url)') if args.gallery or args.update: for exe in ('ffmpeg', 'ffprobe'): try: check_output([exe, '-version']) except FileNotFoundError: error('File not found', exe) if args.github_pages: args.thumbrep = 'thumbnails' else: args.thumbrep = '.thumbnails' args.thumbdir = os.path.join(args.dest, args.thumbrep) if not os.path.exists(args.thumbdir): os.mkdir(args.thumbdir) open(os.path.join(args.thumbdir, '.nomedia'), 'a').close() favicondst = os.path.join(args.dest, 'favicon.ico') if not os.path.isfile(favicondst): faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico') shutil.copyfile(faviconsrc, favicondst) photoboxdir = os.path.join(args.dest, 'photobox') if not os.path.exists(photoboxdir): photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox') shutil.copytree(photoboxsrc, photoboxdir) if args.dates: if not (args.gallery or args.create): pass if args.dates == 'source': pass elif args.dates == 'diary': if args.create: error('Incorrect date format', args.dates) elif re.match('\\d+-\\d+', args.dates): date1, date2 = args.dates.split('-') if validate_date(date1) and validate_date(date2): args.dates = date1, date2 else: error('Incorrect date format', args.dates) else: error('Incorrect date format', args.dates) def main(argstring=None): colorama.init() args = parse_command_line(argstring) setup_part1(args) read_config(args) setup_part2(args) try: if args.gallery or args.update: create_gallery(args) elif args.create: create_diary(args) elif args.blogger: prepare_for_blogger(args) elif args.idem: idempotence(args) elif args.setcfg: setconfig_cmd(args) except KeyboardInterrupt: warning('Interrupted by user.') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Post: def __init__(self, date, text, medias): self.date = date self.text = text self.medias = medias self.dcim = [] self.daterank = 0 self.extra = False def __lt__(self, other): return self.date < other.date @classmethod def from_markdown(cls, post): m = re.match('\\[(\\d\\d\\d\\d/\\d\\d/\\d\\d)\\]\\n*', post[0]) if m: date = m.group(1).replace('/', '') if not validate_date(date): error('Incorrect date value:', date) del post[0] else: error('No date in post', ' '.join(post)) while post and not post[0].strip(): del post[0] text = '' while post and not re.match('!?\\[\\]', post[0]): text += post[0] del post[0] text = re.sub('\\n\\n$', '\n', text) medias = list() while post and (match := re.match('!?\\[\\]\\((.*)\\)', post[0])): media = match.group(1) caption = None del post[0] if post and not re.match('!?\\[\\]', post[0]): caption = post[0].strip() del post[0] if match.group(0)[0] == '!': medias.append(PostImage(caption, media)) else: medias.append(PostVideo(caption, media)) return cls(date, text, medias) @classmethod def from_date(cls, date): dt = datetime.datetime.strptime(date, '%Y%m%d') datetext = dt.strftime('%A %d %B %Y').capitalize() post = cls(date, text=datetext, medias=[]) post.daterank = 1 return post def to_html(self, args, target='regular'): if target == 'regular': if args.diary: return self.to_html_diary(args) else: return self.to_html_regular(args) if target == 'blogger': return self.to_html_blogger() def to_html_regular(self, args): html = list() if self.text: html.append(markdown.markdown(self.text)) subdirs, dcim = dispatch_post_items(self.dcim) if self.dcim: html.append(SEP) for media in subdirs: html.append(media.to_html_dcim(args)) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) return html def to_html_diary(self, args): html = list() if self.extra: html.append('<div class="extra">') if self.text: html.append(markdown.markdown(self.text)) if self.medias: html.append(f'<div id="gallery-blog-{self.date}-{self.daterank}">') for media in self.medias: html.append(media.to_html_post(args)) html.append('</div>') _, dcim = dispatch_post_items(self.dcim) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') html.append(SEP) for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) if self.extra: html.append('</div>') return html def to_html_blogger(self): html = list() html.append(markdown.markdown(self.text)) for image in self.medias: html.append(image.to_html_blogger()) html.append(SEP) return html class PostItem: def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''): self.caption = caption self.uri = uri self.basename = os.path.basename(uri) self.thumb = thumb self.thumbsize = thumbsize self.descr = descr self.resized_url = None class PostImage(PostItem): def to_markdown(self): if not self.caption: return '![](%s)' % (self.uri,) else: return '![](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, * self.thumbsize, descr) def to_html_blogger(self): if not self.caption: return BIMGPAT % (self.uri, self.resized_url) else: return f'{BIMGPAT}\n{CAPTION_PAT}' % (self.uri, self. resized_url, self.caption) class PostVideo(PostItem): def to_markdown(self): if not self.caption: return '[](%s)' % (self.uri,) else: return '[](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, * self.thumbsize, descr) def to_html_blogger(self): x = f'<p style="text-align: center;">{self.iframe}</p>' if not self.caption: return x else: return f'%s\n{CAPTION_PAT}' % (x, self.caption) class PostSubdir(PostItem): def to_html_dcim(self, args): basename = os.path.basename(self.htmname) posts = self.posts title = self.caption print_html(args, posts, title, self.htmname) if not self.caption: return DIRPOST % (basename, self.thumb, *self.thumbsize) else: return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize, self.caption) <|reserved_special_token_0|> def parse_markdown(filename): """ Generate Post objects from markdown. Date must be present in each post and posts must be ordrered by date. """ if not os.path.exists(filename): error('File not found', filename) posts = list() with open(filename, encoding='utf-8') as f: line = next(f) if line.startswith('# '): title = line[2:].strip() record = [] next(f) else: title = None record = [line] for line in f: if not line.startswith('___'): record.append(line) else: posts.append(Post.from_markdown(record)) record = [] daterank = defaultdict(int) for post in posts: daterank[post.date] += 1 post.daterank = daterank[post.date] for post1, post2 in zip(posts[:-1], posts[1:]): if post1.date > post2.date: error('Posts are not ordered', f'{post1.date} > {post2.date}') return title, posts def print_markdown(posts, title, fullname): with open(fullname, 'wt', encoding='utf-8') as fdst: print(f'# {title}\n', file=fdst) for post in posts: date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]' print(date, file=fdst) if post.text: print(file=fdst) for line in post.text.splitlines(): if not line: print(file=fdst) else: for chunk in textwrap.wrap(line, width=78): print(chunk, file=fdst) if post.medias: print(file=fdst) for media in post.medias: print(media.to_markdown(), file=fdst) print('______', file=fdst) <|reserved_special_token_0|> def print_html(args, posts, title, html_name, target='regular'): assert target in ('regular', 'blogger') with io.StringIO() as f: print_html_to_stream(args, posts, title, f, target) html = f.getvalue() if html_name: if os.path.exists(html_name): with open(html_name, 'rt', encoding='utf-8') as f: html0 = f.read() if html == html0: return None with open(html_name, 'wt', encoding='utf-8') as f: f.write(html) return None else: return html <|reserved_special_token_0|> def is_image_file(name): return os.path.splitext(name)[1].lower() in ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tif') <|reserved_special_token_0|> def is_media(name): return is_image_file(name) or is_video_file(name) <|reserved_special_token_0|> def date_from_name(name): if (match := re.search('(?:\\D|^)(\\d{8})(?:\\D|$)', name, re.ASCII)): digits = match.group(1) if validate_date(digits): return digits return None def date_from_item(filename): if (date := date_from_name(filename)): return date else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d') def time_from_name(name): if (match := re.search('(?:\\D|^)(\\d{8})\\D(\\d{6})(?:\\D|$)', name, re.ASCII)): digits = match.group(2) hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits [4:6]) if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60: return digits return None def time_from_item(filename): if (time := time_from_name(filename)): return time else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S') <|reserved_special_token_0|> def get_image_info(filename): date = date_from_item(filename) time = time_from_item(filename) img = Image.open(filename) width, height = img.size size = round(os.path.getsize(filename) / 1000000.0, 1) return (date, time, width, height, size ), f'{date} {time}, dim={width}x{height}, {size} MB' def get_video_info(filename, info_fullname): if os.path.exists(info_fullname): with open(info_fullname) as f: info = f.readline().split() date, time, width, height, size, duration, fps = info[0], info[1], int( info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6] ) formatted_info = format_video_info(date, time, width, height, size, duration, fps) return (date, time, width, height, size, duration, fps), formatted_info else: info, formatted_info = make_video_info(filename, info_fullname) with open(info_fullname, 'wt') as f: print(' '.join([str(_) for _ in info]), file=f) return info, formatted_info def make_video_info(filename, info_fullname): date = date_from_item(filename) time = time_from_item(filename) command = [*FFPROBE_CMD.split(), filename] try: output = check_output(command, stderr=STDOUT).decode() width, height, fps, duration = parse_ffprobe_output(output) size = round(os.path.getsize(filename) / 1000000.0, 1) output = format_video_info(date, time, width, height, size, duration, fps) except CalledProcessError as e: output = e.output.decode() warning(output) raise return (date, time, width, height, size, duration, fps), output def parse_ffprobe_output(ffprobe_output): match = re.match( '(\\d+),(\\d+),(\\d+)/(\\d+),(\\d+/\\d+).*\\s(\\d+\\.\\d+)', ffprobe_output, re.DOTALL) width = int(match.group(1)) height = int(match.group(2)) fps = round(int(match.group(3)) / int(match.group(4)), 1) duration = round(float(match.group(6))) return width, height, fps, duration def format_video_info(date, time, width, height, size, duration, fps): return ( f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB' ) <|reserved_special_token_0|> def thumbname(name, key): return key + '-' + name + '.jpg' def size_thumbnail(width, height, maxdim): if width >= height: return maxdim, int(round(maxdim * height / width)) else: return int(round(maxdim * width / height)), maxdim def make_thumbnail_image(args, image_name, thumb_name, size): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_image(image_name, thumb_name, size) def create_thumbnail_image(image_name, thumb_name, size): imgobj = Image.open(image_name) if imgobj.mode != 'RGBA' and image_name.endswith('.jpg') and not ( image_name.endswith('.gif') and imgobj.info.get('transparency')): imgobj = imgobj.convert('RGBA') imgobj.thumbnail(size, Image.LANCZOS) imgobj = imgobj.convert('RGB') imgobj.save(thumb_name) def make_thumbnail_video(args, video_name, thumb_name, size, duration): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_video(args, video_name, thumb_name, size, duration) <|reserved_special_token_0|> def create_thumbnail_video(args, filename, thumbname, size, duration): delay = min(duration - 1, args.thumbnails.thumbdelay) sizearg = '%dx%d' % size command = ( 'ffmpeg -y -v error -itsoffset -%d -i "%s" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s "%s"' ) command = command % (delay, filename, sizearg, thumbname) result = os.system(command) try: img1 = Image.open(thumbname) except: warning('Unable to save thumbnail for', filename) return img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON))) width, height = img1.size img1.paste(img2, (6, height - 20 - 6), None) img1.save(thumbname) <|reserved_special_token_0|> def create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir): def size_thumbnail(width, height, xmax, ymax): width2 = xmax height2 = int(round(xmax * height / width)) if height2 < ymax: width2 = int(round(ymax * width / height)) height2 = ymax return width2, height2 thumblist = [os.path.basename(item.thumb) for item in items] widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size , thumblist) thumbnum = widthnum * heightnum img = Image.new('RGB', size, SUBDIR_BACKCOL) for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]): row = ind // widthnum col = ind % widthnum img2 = Image.open(os.path.join(thumbdir, thumb)) w, h = size_thumbnail(*img2.size, width[col], height[row]) cropdim = (w - width[col]) // 2, (h - height[row]) // 2, (w - width [col]) // 2 + width[col], (h - height[row]) // 2 + height[row] img2 = img2.resize((w, h), Image.LANCZOS) img2 = img2.crop(cropdim) img.paste(img2, (offsetx[col], offsety[row])) if os.path.exists(thumb_name): imgref = Image.open(thumb_name) byteio = io.BytesIO() img.save(byteio, 'JPEG') byteio.seek(0) imgnew = Image.open(byteio) diff = ImageChops.difference(imgnew, imgref) if diff.getbbox() is None: return img.save(thumb_name) def mosaic_geometry(size, thumblist): if len(thumblist) == 1: widthnum = 1 heightnum = 1 elif len(thumblist) <= 3: widthnum = 1 heightnum = 2 elif len(thumblist) <= 8: widthnum = 2 heightnum = 2 else: widthnum = 3 heightnum = 3 if widthnum == 1: width = [size[0] - 2] else: width = [size[0] // widthnum - 2] * (widthnum - 1) width.append(size[0] - (1 + sum(width) + 2 * len(width) + 1)) if heightnum == 1: height = [size[1] - 2] else: height = [size[1] // heightnum - 2] * (heightnum - 1) height.append(size[1] - (1 + sum(height) + 2 * len(height) + 1)) offsetx = [1] for w in width[:-1]: offsetx.append(offsetx[-1] + w + 2) offsety = [1] for h in height[:-1]: offsety.append(offsety[-1] + h + 2) return widthnum, heightnum, width, height, offsetx, offsety <|reserved_special_token_0|> def list_of_htmlfiles_in_items(itemlist): htmlist = list() for item in itemlist: if type(item) == PostSubdir: htmlist.append(item.htmname) htmlist.extend(list_of_htmlfiles_in_items(item.sublist)) return htmlist def list_of_thumbnails(posts, diary=False): thumblist = list() for post in posts: thumblist.extend(list_of_thumbnails_in_items(post.medias)) if diary is False: thumblist.extend(list_of_thumbnails_in_items(post.dcim)) return thumblist def list_of_thumbnails_in_items(itemlist): thumblist = list() for item in itemlist: if type(item) == PostSubdir: thumblist.append(os.path.basename(item.thumb)) thumblist.extend(list_of_thumbnails_in_items(item.sublist)) else: thumblist.append(os.path.basename(item.thumb)) return thumblist def purge_htmlfiles(args, posts): """ Purge root dir from irrelevant html files """ htmlist = list_of_htmlfiles(args, posts) html_to_remove = list() for fullname in glob.glob(os.path.join(args.root, '*.htm*')): if fullname not in htmlist: html_to_remove.append(fullname) if len(html_to_remove) > args.thumbnails.threshold_htmlfiles: inpt = 'x' while inpt not in 'yn': inpt = input( f'{len(html_to_remove)} html files to remove. Continue [y|n]? ' ).lower() if inpt == 'n': return for name in html_to_remove: print('Removing html files', name) os.remove(name) def purge_thumbnails(args, thumbdir, posts, diary=False): """ Purge thumbnail dir from irrelevant thumbnails """ thumblist = list_of_thumbnails(posts, diary) thumbs_to_remove = list() for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')): if os.path.basename(fullname) not in thumblist: thumbs_to_remove.append(fullname) if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs: inpt = 'x' while inpt not in 'yn': inpt = input( f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? ' ).lower() if inpt == 'n': return for name in thumbs_to_remove: print('Removing thumbnail', name) os.remove(name) info_fullname = os.path.splitext(name)[0] + '.info' if os.path.exists(info_fullname): os.remove(info_fullname) def is_media_within_dates(fullname, dates): if is_media(fullname): if type(dates) == tuple: return dates[0] <= date_from_item(fullname) <= dates[1] else: return True else: return False def sorted_listdir(filelist): like_windows_explorer = True if not filelist: return filelist if like_windows_explorer: maxlen = max(len(os.path.splitext(name)[0]) for name in filelist) def keyfunc(name): root, ext = os.path.splitext(name.lower()) return root.ljust(maxlen, ' ') + ext else: keyfunc = str.lower return sorted(filelist, key=keyfunc) <|reserved_special_token_0|> def list_of_medias(args, sourcedir, recursive): """ Return the list of full paths for pictures and movies in source directory """ files = list_of_files(sourcedir, recursive) return [_ for _ in files if is_media_within_dates(_, args.dates)] <|reserved_special_token_0|> def dispatch_post_items(list_of_post_items): subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir] medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir] return subdirs, medias def create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax): if os.path.isfile(media_fullname): if is_image_file(media_fullname): return create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_subdir(args, media_fullname, sourcedir, thumbdir, key, thumbmax) def create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax ): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) try: info, infofmt = get_image_info(media_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize) return PostImage(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except PIL.UnidentifiedImageError: warning('Unable to read image', media_fullname) return None def create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax ): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) info_fullname = os.path.splitext(thumb_fullname)[0] + '.info' try: info, infofmt = get_video_info(media_fullname, info_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_video(args, media_fullname, thumb_fullname, thumbsize, duration=info[5]) return PostVideo(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except CalledProcessError: warning('Unable to read video', media_fullname) return None <|reserved_special_token_0|> def relative_name(media_fullname, sourcedir): """ /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg --> deeper2_deepest_OCT_20000112_000004.jpg /Gilles/Dev/journal/tests/subdir/deeper2/deepest --> deeper2_deepest """ x = os.path.relpath(media_fullname, sourcedir) x = x.replace('\\', '_').replace('/', '_').replace('#', '_') return x <|reserved_special_token_0|> def make_posts_from_diary(args): md_filename = os.path.join(args.root, 'index.md') if os.path.exists(md_filename): title, posts = parse_markdown(md_filename) else: error('File not found', md_filename) for post in posts: for media in post.medias: media_fullname = os.path.join(args.root, media.uri) item = create_item(args, media_fullname, args.root, args. thumbdir, 'post', 400) media.thumb = item.thumb media.thumbsize = item.thumbsize media.descr = item.descr return title, posts <|reserved_special_token_0|> def make_posts_from_subdir(args, dirname): if args.bydir is False: medias_ext = list_of_medias(args, dirname, args.recursive) else: medias_ext = list_of_medias_ext(args, dirname) postmedias = list() for item in medias_ext: postmedia = create_item(args, item, args.sourcedir, args.thumbdir, 'dcim', 300) if postmedia is not None: postmedias.append(postmedia) post = Post(date='00000000', text='', medias=[]) post.dcim = postmedias posts = [post] title = os.path.basename(args.sourcedir) or os.path.splitdrive(args. sourcedir)[0] return title, posts <|reserved_special_token_0|> def create_gallery(args): title, posts = make_posts(args, args.sourcedir) print_html(args, posts, title, os.path.join(args.dest, args.rootname), 'regular') purge_htmlfiles(args, posts) if args.diary and not args.sourcedir: purge_thumbnails(args, args.thumbdir, posts, diary=True) else: purge_thumbnails(args, args.thumbdir, posts) def create_diary(args): medias = list_of_medias(args, args.sourcedir, args.recursive) if args.dates == 'diary': assert 0 else: required_dates = {date_from_item(media) for media in medias} if type(args.dates) == tuple: date1, date2 = args.dates required_dates = {date for date in required_dates if date1 <= date <= date2} title = args.sourcedir posts = list() for date in sorted(required_dates): posts.append(Post.from_date(date)) os.makedirs(args.root, exist_ok=True) print_markdown(posts, title, os.path.join(args.root, 'index.md')) <|reserved_special_token_0|> def compare_image_buffers(imgbuf1, imgbuf2): """ return True if images read on file are identical, False otherwise """ with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2: img1 = Image.open(imgio1) img2 = Image.open(imgio2) diff = ImageChops.difference(img1, img2) return not diff.getbbox() def check_images(args, posts, online_images): result = True for post in posts: for media in post.medias: if type(media) is PostImage: if media.basename in online_images: with open(os.path.join(args.root, media.uri), 'rb') as f: imgbuf1 = f.read() try: with urlopen(online_images[media.basename][0]) as u: imgbuf2 = u.read() except FileNotFoundError: print('File not found', online_images[media. basename][0]) next if compare_image_buffers(imgbuf1, imgbuf2) is False: print('Files are different, upload', media.basename) elif 1: print('File already online', media.basename) else: print('File is absent, upload', media.basename) result = False elif type(media) is PostVideo: print('Video not checked', media.basename) else: assert False return result def compose_blogger_html(args, title, posts, imgdata, online_videos): """ Compose html with blogger image urls """ for post in posts: for media in post.medias: if type(media) is PostImage: if media.uri not in imgdata: print('Image missing: ', media.uri) else: img_url, resized_url = imgdata[media.uri] media.uri = img_url media.resized_url = resized_url elif type(media) is PostVideo: if not online_videos: print('Video missing: ', media.uri) else: media.iframe = online_videos[0] del online_videos[0] else: assert False return print_html(args, posts, title, '', target='blogger') def prepare_for_blogger(args): """ Export blogger html to clipboard. If --full, export complete html, otherwise export html extract ready to paste into blogger edit mode. """ title, posts = parse_markdown(os.path.join(args.root, 'index.md')) online_images, online_videos = online_images_url(args) if args.check_images and check_images(args, posts, online_images) is False: pass html = compose_blogger_html(args, title, posts, online_images, online_videos) if args.full is False: html = re.search('<body>(.*)?</body>', html, flags=re.DOTALL).group(1) html = re.sub('<script>.*?</script>', '', html, flags=re.DOTALL) html = STYLE.replace('%%', '%') + html if args.dest: with open(args.dest, 'wt', encoding='utf-8') as f: f.write(html) else: clipboard.copy(html) def idempotence(args): """ For testing identity between a diary file and the fle obtained after reading and printing it. See testing. """ title, posts = parse_markdown(os.path.join(args.root, 'index.md')) print_markdown(posts, title, os.path.join(args.dest, 'index.md')) <|reserved_special_token_0|> class MyConfigParser(ConfigParser): """Add input checking.""" def __init__(self): ConfigParser.__init__(self, inline_comment_prefixes=(';',)) def error(self, section, entry): error('Missing or incorrect config value:', '[%s]%s' % (section, entry) ) def getint(self, section, entry, default=None): try: if default is None: return ConfigParser.getint(self, section, entry) else: return ConfigParser.getint(self, section, entry, raw=True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def getboolean(self, section, entry, default=None): try: if default is None: return ConfigParser.getboolean(self, section, entry) else: return ConfigParser.getboolean(self, section, entry, raw= True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def configfilename(params): return os.path.join(params.root, '.config.ini') def createconfig(config_filename): with open(config_filename, 'wt') as f: f.writelines(CONFIG_DEFAULTS) def read_config(params): config_filename = configfilename(params) try: if not os.path.exists(config_filename) or params.resetcfg: createconfig(config_filename) except: error('Error creating configuration file') try: getconfig(params, config_filename) except Exception as e: error('Error reading configuration file.', str(e), 'Use --resetcfg') <|reserved_special_token_0|> def setconfig_cmd(args): config_filename = configfilename(args) setconfig(config_filename, *args.setcfg) def update_config(args): updates = ('sourcedir', args.sourcedir), ('bydir', BOOL[args.bydir]), ( 'bydate', BOOL[args.bydate]), ('diary', BOOL[args.diary]), ('recursive' , BOOL[args.recursive]), ('dates', args.dates), ('github_pages', BOOL[args.github_pages]) cfgname = configfilename(args) with open(cfgname) as f: cfglines = [_.strip() for _ in f.readlines()] for key, value in updates: for iline, line in enumerate(cfglines): if line.startswith(key): cfglines[iline] = f'{key} = {value}' break with open(cfgname, 'wt') as f: for line in cfglines: print(line, file=f) def warning(*msg): print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) <|reserved_special_token_0|> def errorcode(msg): return ERRORS.splitlines().index(msg) + 1 def error(*msg): print(colorama.Fore.RED + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) sys.exit(errorcode(msg[0])) <|reserved_special_token_0|> def setup_part1(args): """ Made before reading config file (config file located in args.root). Check and normalize root path. """ args.rootarg = args.root rootext = os.path.splitext(args.rootarg)[1] if rootext == '': pass else: args.root = os.path.dirname(args.root) if args.root: args.root = os.path.abspath(args.root) if not os.path.isdir(args.root): if args.gallery: os.mkdir(args.root) else: error('Directory not found', args.root) def setup_part2(args): """ Made after reading config file. Check for ffmpeg in path. Create .thumbnails dir if necessary and create .nomedia in it. Copy photobox file to destination dir. Handle priority between command line and config file. """ if args.update: args.sourcedir = args.source.sourcedir args.bydir = args.source.bydir args.bydate = args.source.bydate args.diary = args.source.diary args.recursive = args.source.recursive args.dates = args.source.dates args.github_pages = args.source.github_pages elif args.gallery: args.source.sourcedir = args.sourcedir args.source.bydir = args.bydir args.source.bydate = args.bydate args.source.diary = args.diary args.source.recursive = args.recursive args.source.dates = args.dates args.source.github_pages = args.github_pages update_config(args) if args.github_pages: args.html_suffix = '.html' else: args.html_suffix = '.htm' rootext = os.path.splitext(args.rootarg)[1] if rootext: args.rootname = os.path.basename(args.rootarg) else: args.rootname = 'index' + args.html_suffix if args.sourcedir: args.sourcedir = os.path.abspath(args.sourcedir) if os.path.splitdrive(args.sourcedir)[0]: drive, rest = os.path.splitdrive(args.sourcedir) args.sourcedir = drive.upper() + rest if not os.path.isdir(args.sourcedir): error('Directory not found', args.sourcedir) elif args.gallery and args.diary is False and args.update is None: error('Directory not found', 'Use --sourcedir') if args.dest: args.dest = os.path.abspath(args.dest) if args.dest is None: args.dest = args.root if args.blogger and args.urlblogger is None: error('No blogger url (--url)') if args.gallery or args.update: for exe in ('ffmpeg', 'ffprobe'): try: check_output([exe, '-version']) except FileNotFoundError: error('File not found', exe) if args.github_pages: args.thumbrep = 'thumbnails' else: args.thumbrep = '.thumbnails' args.thumbdir = os.path.join(args.dest, args.thumbrep) if not os.path.exists(args.thumbdir): os.mkdir(args.thumbdir) open(os.path.join(args.thumbdir, '.nomedia'), 'a').close() favicondst = os.path.join(args.dest, 'favicon.ico') if not os.path.isfile(favicondst): faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico') shutil.copyfile(faviconsrc, favicondst) photoboxdir = os.path.join(args.dest, 'photobox') if not os.path.exists(photoboxdir): photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox') shutil.copytree(photoboxsrc, photoboxdir) if args.dates: if not (args.gallery or args.create): pass if args.dates == 'source': pass elif args.dates == 'diary': if args.create: error('Incorrect date format', args.dates) elif re.match('\\d+-\\d+', args.dates): date1, date2 = args.dates.split('-') if validate_date(date1) and validate_date(date2): args.dates = date1, date2 else: error('Incorrect date format', args.dates) else: error('Incorrect date format', args.dates) def main(argstring=None): colorama.init() args = parse_command_line(argstring) setup_part1(args) read_config(args) setup_part2(args) try: if args.gallery or args.update: create_gallery(args) elif args.create: create_diary(args) elif args.blogger: prepare_for_blogger(args) elif args.idem: idempotence(args) elif args.setcfg: setconfig_cmd(args) except KeyboardInterrupt: warning('Interrupted by user.') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Post: def __init__(self, date, text, medias): self.date = date self.text = text self.medias = medias self.dcim = [] self.daterank = 0 self.extra = False def __lt__(self, other): return self.date < other.date @classmethod def from_markdown(cls, post): m = re.match('\\[(\\d\\d\\d\\d/\\d\\d/\\d\\d)\\]\\n*', post[0]) if m: date = m.group(1).replace('/', '') if not validate_date(date): error('Incorrect date value:', date) del post[0] else: error('No date in post', ' '.join(post)) while post and not post[0].strip(): del post[0] text = '' while post and not re.match('!?\\[\\]', post[0]): text += post[0] del post[0] text = re.sub('\\n\\n$', '\n', text) medias = list() while post and (match := re.match('!?\\[\\]\\((.*)\\)', post[0])): media = match.group(1) caption = None del post[0] if post and not re.match('!?\\[\\]', post[0]): caption = post[0].strip() del post[0] if match.group(0)[0] == '!': medias.append(PostImage(caption, media)) else: medias.append(PostVideo(caption, media)) return cls(date, text, medias) @classmethod def from_date(cls, date): dt = datetime.datetime.strptime(date, '%Y%m%d') datetext = dt.strftime('%A %d %B %Y').capitalize() post = cls(date, text=datetext, medias=[]) post.daterank = 1 return post def to_html(self, args, target='regular'): if target == 'regular': if args.diary: return self.to_html_diary(args) else: return self.to_html_regular(args) if target == 'blogger': return self.to_html_blogger() def to_html_regular(self, args): html = list() if self.text: html.append(markdown.markdown(self.text)) subdirs, dcim = dispatch_post_items(self.dcim) if self.dcim: html.append(SEP) for media in subdirs: html.append(media.to_html_dcim(args)) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) return html def to_html_diary(self, args): html = list() if self.extra: html.append('<div class="extra">') if self.text: html.append(markdown.markdown(self.text)) if self.medias: html.append(f'<div id="gallery-blog-{self.date}-{self.daterank}">') for media in self.medias: html.append(media.to_html_post(args)) html.append('</div>') _, dcim = dispatch_post_items(self.dcim) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') html.append(SEP) for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) if self.extra: html.append('</div>') return html def to_html_blogger(self): html = list() html.append(markdown.markdown(self.text)) for image in self.medias: html.append(image.to_html_blogger()) html.append(SEP) return html class PostItem: def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''): self.caption = caption self.uri = uri self.basename = os.path.basename(uri) self.thumb = thumb self.thumbsize = thumbsize self.descr = descr self.resized_url = None class PostImage(PostItem): def to_markdown(self): if not self.caption: return '![](%s)' % (self.uri,) else: return '![](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, * self.thumbsize, descr) def to_html_blogger(self): if not self.caption: return BIMGPAT % (self.uri, self.resized_url) else: return f'{BIMGPAT}\n{CAPTION_PAT}' % (self.uri, self. resized_url, self.caption) class PostVideo(PostItem): def to_markdown(self): if not self.caption: return '[](%s)' % (self.uri,) else: return '[](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, * self.thumbsize, descr) def to_html_blogger(self): x = f'<p style="text-align: center;">{self.iframe}</p>' if not self.caption: return x else: return f'%s\n{CAPTION_PAT}' % (x, self.caption) class PostSubdir(PostItem): def to_html_dcim(self, args): basename = os.path.basename(self.htmname) posts = self.posts title = self.caption print_html(args, posts, title, self.htmname) if not self.caption: return DIRPOST % (basename, self.thumb, *self.thumbsize) else: return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize, self.caption) <|reserved_special_token_0|> def parse_markdown(filename): """ Generate Post objects from markdown. Date must be present in each post and posts must be ordrered by date. """ if not os.path.exists(filename): error('File not found', filename) posts = list() with open(filename, encoding='utf-8') as f: line = next(f) if line.startswith('# '): title = line[2:].strip() record = [] next(f) else: title = None record = [line] for line in f: if not line.startswith('___'): record.append(line) else: posts.append(Post.from_markdown(record)) record = [] daterank = defaultdict(int) for post in posts: daterank[post.date] += 1 post.daterank = daterank[post.date] for post1, post2 in zip(posts[:-1], posts[1:]): if post1.date > post2.date: error('Posts are not ordered', f'{post1.date} > {post2.date}') return title, posts def print_markdown(posts, title, fullname): with open(fullname, 'wt', encoding='utf-8') as fdst: print(f'# {title}\n', file=fdst) for post in posts: date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]' print(date, file=fdst) if post.text: print(file=fdst) for line in post.text.splitlines(): if not line: print(file=fdst) else: for chunk in textwrap.wrap(line, width=78): print(chunk, file=fdst) if post.medias: print(file=fdst) for media in post.medias: print(media.to_markdown(), file=fdst) print('______', file=fdst) <|reserved_special_token_0|> def print_html(args, posts, title, html_name, target='regular'): assert target in ('regular', 'blogger') with io.StringIO() as f: print_html_to_stream(args, posts, title, f, target) html = f.getvalue() if html_name: if os.path.exists(html_name): with open(html_name, 'rt', encoding='utf-8') as f: html0 = f.read() if html == html0: return None with open(html_name, 'wt', encoding='utf-8') as f: f.write(html) return None else: return html <|reserved_special_token_0|> def is_image_file(name): return os.path.splitext(name)[1].lower() in ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tif') <|reserved_special_token_0|> def is_media(name): return is_image_file(name) or is_video_file(name) <|reserved_special_token_0|> def date_from_name(name): if (match := re.search('(?:\\D|^)(\\d{8})(?:\\D|$)', name, re.ASCII)): digits = match.group(1) if validate_date(digits): return digits return None def date_from_item(filename): if (date := date_from_name(filename)): return date else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d') def time_from_name(name): if (match := re.search('(?:\\D|^)(\\d{8})\\D(\\d{6})(?:\\D|$)', name, re.ASCII)): digits = match.group(2) hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits [4:6]) if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60: return digits return None def time_from_item(filename): if (time := time_from_name(filename)): return time else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S') <|reserved_special_token_0|> def get_image_info(filename): date = date_from_item(filename) time = time_from_item(filename) img = Image.open(filename) width, height = img.size size = round(os.path.getsize(filename) / 1000000.0, 1) return (date, time, width, height, size ), f'{date} {time}, dim={width}x{height}, {size} MB' def get_video_info(filename, info_fullname): if os.path.exists(info_fullname): with open(info_fullname) as f: info = f.readline().split() date, time, width, height, size, duration, fps = info[0], info[1], int( info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6] ) formatted_info = format_video_info(date, time, width, height, size, duration, fps) return (date, time, width, height, size, duration, fps), formatted_info else: info, formatted_info = make_video_info(filename, info_fullname) with open(info_fullname, 'wt') as f: print(' '.join([str(_) for _ in info]), file=f) return info, formatted_info def make_video_info(filename, info_fullname): date = date_from_item(filename) time = time_from_item(filename) command = [*FFPROBE_CMD.split(), filename] try: output = check_output(command, stderr=STDOUT).decode() width, height, fps, duration = parse_ffprobe_output(output) size = round(os.path.getsize(filename) / 1000000.0, 1) output = format_video_info(date, time, width, height, size, duration, fps) except CalledProcessError as e: output = e.output.decode() warning(output) raise return (date, time, width, height, size, duration, fps), output def parse_ffprobe_output(ffprobe_output): match = re.match( '(\\d+),(\\d+),(\\d+)/(\\d+),(\\d+/\\d+).*\\s(\\d+\\.\\d+)', ffprobe_output, re.DOTALL) width = int(match.group(1)) height = int(match.group(2)) fps = round(int(match.group(3)) / int(match.group(4)), 1) duration = round(float(match.group(6))) return width, height, fps, duration def format_video_info(date, time, width, height, size, duration, fps): return ( f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB' ) <|reserved_special_token_0|> def thumbname(name, key): return key + '-' + name + '.jpg' def size_thumbnail(width, height, maxdim): if width >= height: return maxdim, int(round(maxdim * height / width)) else: return int(round(maxdim * width / height)), maxdim def make_thumbnail_image(args, image_name, thumb_name, size): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_image(image_name, thumb_name, size) def create_thumbnail_image(image_name, thumb_name, size): imgobj = Image.open(image_name) if imgobj.mode != 'RGBA' and image_name.endswith('.jpg') and not ( image_name.endswith('.gif') and imgobj.info.get('transparency')): imgobj = imgobj.convert('RGBA') imgobj.thumbnail(size, Image.LANCZOS) imgobj = imgobj.convert('RGB') imgobj.save(thumb_name) def make_thumbnail_video(args, video_name, thumb_name, size, duration): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_video(args, video_name, thumb_name, size, duration) <|reserved_special_token_0|> def create_thumbnail_video(args, filename, thumbname, size, duration): delay = min(duration - 1, args.thumbnails.thumbdelay) sizearg = '%dx%d' % size command = ( 'ffmpeg -y -v error -itsoffset -%d -i "%s" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s "%s"' ) command = command % (delay, filename, sizearg, thumbname) result = os.system(command) try: img1 = Image.open(thumbname) except: warning('Unable to save thumbnail for', filename) return img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON))) width, height = img1.size img1.paste(img2, (6, height - 20 - 6), None) img1.save(thumbname) <|reserved_special_token_0|> def create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir): def size_thumbnail(width, height, xmax, ymax): width2 = xmax height2 = int(round(xmax * height / width)) if height2 < ymax: width2 = int(round(ymax * width / height)) height2 = ymax return width2, height2 thumblist = [os.path.basename(item.thumb) for item in items] widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size , thumblist) thumbnum = widthnum * heightnum img = Image.new('RGB', size, SUBDIR_BACKCOL) for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]): row = ind // widthnum col = ind % widthnum img2 = Image.open(os.path.join(thumbdir, thumb)) w, h = size_thumbnail(*img2.size, width[col], height[row]) cropdim = (w - width[col]) // 2, (h - height[row]) // 2, (w - width [col]) // 2 + width[col], (h - height[row]) // 2 + height[row] img2 = img2.resize((w, h), Image.LANCZOS) img2 = img2.crop(cropdim) img.paste(img2, (offsetx[col], offsety[row])) if os.path.exists(thumb_name): imgref = Image.open(thumb_name) byteio = io.BytesIO() img.save(byteio, 'JPEG') byteio.seek(0) imgnew = Image.open(byteio) diff = ImageChops.difference(imgnew, imgref) if diff.getbbox() is None: return img.save(thumb_name) def mosaic_geometry(size, thumblist): if len(thumblist) == 1: widthnum = 1 heightnum = 1 elif len(thumblist) <= 3: widthnum = 1 heightnum = 2 elif len(thumblist) <= 8: widthnum = 2 heightnum = 2 else: widthnum = 3 heightnum = 3 if widthnum == 1: width = [size[0] - 2] else: width = [size[0] // widthnum - 2] * (widthnum - 1) width.append(size[0] - (1 + sum(width) + 2 * len(width) + 1)) if heightnum == 1: height = [size[1] - 2] else: height = [size[1] // heightnum - 2] * (heightnum - 1) height.append(size[1] - (1 + sum(height) + 2 * len(height) + 1)) offsetx = [1] for w in width[:-1]: offsetx.append(offsetx[-1] + w + 2) offsety = [1] for h in height[:-1]: offsety.append(offsety[-1] + h + 2) return widthnum, heightnum, width, height, offsetx, offsety <|reserved_special_token_0|> def list_of_htmlfiles_in_items(itemlist): htmlist = list() for item in itemlist: if type(item) == PostSubdir: htmlist.append(item.htmname) htmlist.extend(list_of_htmlfiles_in_items(item.sublist)) return htmlist def list_of_thumbnails(posts, diary=False): thumblist = list() for post in posts: thumblist.extend(list_of_thumbnails_in_items(post.medias)) if diary is False: thumblist.extend(list_of_thumbnails_in_items(post.dcim)) return thumblist def list_of_thumbnails_in_items(itemlist): thumblist = list() for item in itemlist: if type(item) == PostSubdir: thumblist.append(os.path.basename(item.thumb)) thumblist.extend(list_of_thumbnails_in_items(item.sublist)) else: thumblist.append(os.path.basename(item.thumb)) return thumblist def purge_htmlfiles(args, posts): """ Purge root dir from irrelevant html files """ htmlist = list_of_htmlfiles(args, posts) html_to_remove = list() for fullname in glob.glob(os.path.join(args.root, '*.htm*')): if fullname not in htmlist: html_to_remove.append(fullname) if len(html_to_remove) > args.thumbnails.threshold_htmlfiles: inpt = 'x' while inpt not in 'yn': inpt = input( f'{len(html_to_remove)} html files to remove. Continue [y|n]? ' ).lower() if inpt == 'n': return for name in html_to_remove: print('Removing html files', name) os.remove(name) def purge_thumbnails(args, thumbdir, posts, diary=False): """ Purge thumbnail dir from irrelevant thumbnails """ thumblist = list_of_thumbnails(posts, diary) thumbs_to_remove = list() for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')): if os.path.basename(fullname) not in thumblist: thumbs_to_remove.append(fullname) if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs: inpt = 'x' while inpt not in 'yn': inpt = input( f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? ' ).lower() if inpt == 'n': return for name in thumbs_to_remove: print('Removing thumbnail', name) os.remove(name) info_fullname = os.path.splitext(name)[0] + '.info' if os.path.exists(info_fullname): os.remove(info_fullname) def is_media_within_dates(fullname, dates): if is_media(fullname): if type(dates) == tuple: return dates[0] <= date_from_item(fullname) <= dates[1] else: return True else: return False def sorted_listdir(filelist): like_windows_explorer = True if not filelist: return filelist if like_windows_explorer: maxlen = max(len(os.path.splitext(name)[0]) for name in filelist) def keyfunc(name): root, ext = os.path.splitext(name.lower()) return root.ljust(maxlen, ' ') + ext else: keyfunc = str.lower return sorted(filelist, key=keyfunc) def list_of_files(sourcedir, recursive): """ Return the list of full paths for files in source directory """ result = list() if recursive is False: listdir = sorted_listdir(os.listdir(sourcedir)) if '.nomedia' not in listdir: for basename in listdir: result.append(os.path.join(sourcedir, basename)) else: for root, dirs, files in os.walk(sourcedir): if '.nomedia' not in files: for basename in sorted_listdir(files): result.append(os.path.join(root, basename)) return result def list_of_medias(args, sourcedir, recursive): """ Return the list of full paths for pictures and movies in source directory """ files = list_of_files(sourcedir, recursive) return [_ for _ in files if is_media_within_dates(_, args.dates)] <|reserved_special_token_0|> def dispatch_post_items(list_of_post_items): subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir] medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir] return subdirs, medias def create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax): if os.path.isfile(media_fullname): if is_image_file(media_fullname): return create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_subdir(args, media_fullname, sourcedir, thumbdir, key, thumbmax) def create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax ): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) try: info, infofmt = get_image_info(media_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize) return PostImage(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except PIL.UnidentifiedImageError: warning('Unable to read image', media_fullname) return None def create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax ): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) info_fullname = os.path.splitext(thumb_fullname)[0] + '.info' try: info, infofmt = get_video_info(media_fullname, info_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_video(args, media_fullname, thumb_fullname, thumbsize, duration=info[5]) return PostVideo(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except CalledProcessError: warning('Unable to read video', media_fullname) return None <|reserved_special_token_0|> def relative_name(media_fullname, sourcedir): """ /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg --> deeper2_deepest_OCT_20000112_000004.jpg /Gilles/Dev/journal/tests/subdir/deeper2/deepest --> deeper2_deepest """ x = os.path.relpath(media_fullname, sourcedir) x = x.replace('\\', '_').replace('/', '_').replace('#', '_') return x <|reserved_special_token_0|> def make_posts_from_diary(args): md_filename = os.path.join(args.root, 'index.md') if os.path.exists(md_filename): title, posts = parse_markdown(md_filename) else: error('File not found', md_filename) for post in posts: for media in post.medias: media_fullname = os.path.join(args.root, media.uri) item = create_item(args, media_fullname, args.root, args. thumbdir, 'post', 400) media.thumb = item.thumb media.thumbsize = item.thumbsize media.descr = item.descr return title, posts def create_items_by_date(args, medias, posts): if args.dates == 'diary': required_dates = {post.date for post in posts} else: required_dates = {date_from_item(media) for media in medias} if type(args.dates) == tuple: date1, date2 = args.dates required_dates = {date for date in required_dates if date1 <= date <= date2} bydate = defaultdict(list) for media_fullname in medias: date = date_from_item(media_fullname) if date in required_dates: item = create_item(args, media_fullname, args.sourcedir, args. thumbdir, 'dcim', 300) if item: bydate[date].append(item) for date, liste in bydate.items(): liste.sort(key=lambda item: time_from_item(item.uri)) return bydate <|reserved_special_token_0|> def make_posts_from_subdir(args, dirname): if args.bydir is False: medias_ext = list_of_medias(args, dirname, args.recursive) else: medias_ext = list_of_medias_ext(args, dirname) postmedias = list() for item in medias_ext: postmedia = create_item(args, item, args.sourcedir, args.thumbdir, 'dcim', 300) if postmedia is not None: postmedias.append(postmedia) post = Post(date='00000000', text='', medias=[]) post.dcim = postmedias posts = [post] title = os.path.basename(args.sourcedir) or os.path.splitdrive(args. sourcedir)[0] return title, posts <|reserved_special_token_0|> def create_gallery(args): title, posts = make_posts(args, args.sourcedir) print_html(args, posts, title, os.path.join(args.dest, args.rootname), 'regular') purge_htmlfiles(args, posts) if args.diary and not args.sourcedir: purge_thumbnails(args, args.thumbdir, posts, diary=True) else: purge_thumbnails(args, args.thumbdir, posts) def create_diary(args): medias = list_of_medias(args, args.sourcedir, args.recursive) if args.dates == 'diary': assert 0 else: required_dates = {date_from_item(media) for media in medias} if type(args.dates) == tuple: date1, date2 = args.dates required_dates = {date for date in required_dates if date1 <= date <= date2} title = args.sourcedir posts = list() for date in sorted(required_dates): posts.append(Post.from_date(date)) os.makedirs(args.root, exist_ok=True) print_markdown(posts, title, os.path.join(args.root, 'index.md')) def online_images_url(args): try: if args.urlblogger.startswith('http:') or args.urlblogger.startswith( 'https:'): with urlopen(args.urlblogger) as u: buffer = u.read() else: with open(args.urlblogger, 'rb') as f: buffer = f.read() except: error('Unable to read url', args.urlblogger) buffer = buffer.decode('utf-8') online_images = dict() for match in re.finditer('<div class="separator"((?!<div).)*?</div>', buffer, flags=re.DOTALL): div_separator = match.group(0) div_separator = div_separator.replace('&nbsp;', '') elem_div = objectify.fromstring(div_separator) for elem_a in elem_div.iterchildren(tag='a'): href = elem_a.get('href') thumb = elem_a.img.get('src') online_images[os.path.basename(href)] = href, thumb online_videos = list() for match in re.finditer( '<iframe allowfullscreen="allowfullscreen".*?</iframe>', buffer, flags=re.DOTALL): iframe = match.group(0) online_videos.append(iframe) return online_images, online_videos def compare_image_buffers(imgbuf1, imgbuf2): """ return True if images read on file are identical, False otherwise """ with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2: img1 = Image.open(imgio1) img2 = Image.open(imgio2) diff = ImageChops.difference(img1, img2) return not diff.getbbox() def check_images(args, posts, online_images): result = True for post in posts: for media in post.medias: if type(media) is PostImage: if media.basename in online_images: with open(os.path.join(args.root, media.uri), 'rb') as f: imgbuf1 = f.read() try: with urlopen(online_images[media.basename][0]) as u: imgbuf2 = u.read() except FileNotFoundError: print('File not found', online_images[media. basename][0]) next if compare_image_buffers(imgbuf1, imgbuf2) is False: print('Files are different, upload', media.basename) elif 1: print('File already online', media.basename) else: print('File is absent, upload', media.basename) result = False elif type(media) is PostVideo: print('Video not checked', media.basename) else: assert False return result def compose_blogger_html(args, title, posts, imgdata, online_videos): """ Compose html with blogger image urls """ for post in posts: for media in post.medias: if type(media) is PostImage: if media.uri not in imgdata: print('Image missing: ', media.uri) else: img_url, resized_url = imgdata[media.uri] media.uri = img_url media.resized_url = resized_url elif type(media) is PostVideo: if not online_videos: print('Video missing: ', media.uri) else: media.iframe = online_videos[0] del online_videos[0] else: assert False return print_html(args, posts, title, '', target='blogger') def prepare_for_blogger(args): """ Export blogger html to clipboard. If --full, export complete html, otherwise export html extract ready to paste into blogger edit mode. """ title, posts = parse_markdown(os.path.join(args.root, 'index.md')) online_images, online_videos = online_images_url(args) if args.check_images and check_images(args, posts, online_images) is False: pass html = compose_blogger_html(args, title, posts, online_images, online_videos) if args.full is False: html = re.search('<body>(.*)?</body>', html, flags=re.DOTALL).group(1) html = re.sub('<script>.*?</script>', '', html, flags=re.DOTALL) html = STYLE.replace('%%', '%') + html if args.dest: with open(args.dest, 'wt', encoding='utf-8') as f: f.write(html) else: clipboard.copy(html) def idempotence(args): """ For testing identity between a diary file and the fle obtained after reading and printing it. See testing. """ title, posts = parse_markdown(os.path.join(args.root, 'index.md')) print_markdown(posts, title, os.path.join(args.dest, 'index.md')) <|reserved_special_token_0|> class MyConfigParser(ConfigParser): """Add input checking.""" def __init__(self): ConfigParser.__init__(self, inline_comment_prefixes=(';',)) def error(self, section, entry): error('Missing or incorrect config value:', '[%s]%s' % (section, entry) ) def getint(self, section, entry, default=None): try: if default is None: return ConfigParser.getint(self, section, entry) else: return ConfigParser.getint(self, section, entry, raw=True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def getboolean(self, section, entry, default=None): try: if default is None: return ConfigParser.getboolean(self, section, entry) else: return ConfigParser.getboolean(self, section, entry, raw= True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def configfilename(params): return os.path.join(params.root, '.config.ini') def createconfig(config_filename): with open(config_filename, 'wt') as f: f.writelines(CONFIG_DEFAULTS) def read_config(params): config_filename = configfilename(params) try: if not os.path.exists(config_filename) or params.resetcfg: createconfig(config_filename) except: error('Error creating configuration file') try: getconfig(params, config_filename) except Exception as e: error('Error reading configuration file.', str(e), 'Use --resetcfg') def getconfig(options, config_filename): class Section: pass options.source = Section() options.thumbnails = Section() options.photobox = Section() config = MyConfigParser() config.read(config_filename) options.source.sourcedir = config.get('source', 'sourcedir') options.source.bydir = config.getboolean('source', 'bydir') options.source.bydate = config.getboolean('source', 'bydate') options.source.diary = config.getboolean('source', 'diary') options.source.recursive = config.getboolean('source', 'recursive') options.source.dates = config.get('source', 'dates') options.source.github_pages = config.getboolean('source', 'github_pages', default=False) options.thumbnails.media_description = config.getboolean('thumbnails', 'media_description') options.thumbnails.subdir_caption = config.getboolean('thumbnails', 'subdir_caption') options.thumbnails.thumbdelay = config.getint('thumbnails', 'thumbdelay') options.thumbnails.threshold_thumbs = config.getint('thumbnails', 'threshold_thumbs') options.thumbnails.threshold_htmlfiles = config.getint('thumbnails', 'threshold_htmlfiles', default=3) options.photobox.loop = config.getboolean('photobox', 'loop') options.photobox.thumbs = config.getboolean('photobox', 'thumbs') options.photobox.autoplay = config.getboolean('photobox', 'autoplay') options.photobox.time = config.getint('photobox', 'time') options.photobox.zoomable = config.getboolean('photobox', 'zoomable') options.photobox.rotatable = config.getboolean('photobox', 'rotatable') options.photobox.wheelNextPrev = config.getboolean('photobox', 'wheelNextPrev') <|reserved_special_token_0|> def setconfig_cmd(args): config_filename = configfilename(args) setconfig(config_filename, *args.setcfg) def update_config(args): updates = ('sourcedir', args.sourcedir), ('bydir', BOOL[args.bydir]), ( 'bydate', BOOL[args.bydate]), ('diary', BOOL[args.diary]), ('recursive' , BOOL[args.recursive]), ('dates', args.dates), ('github_pages', BOOL[args.github_pages]) cfgname = configfilename(args) with open(cfgname) as f: cfglines = [_.strip() for _ in f.readlines()] for key, value in updates: for iline, line in enumerate(cfglines): if line.startswith(key): cfglines[iline] = f'{key} = {value}' break with open(cfgname, 'wt') as f: for line in cfglines: print(line, file=f) def warning(*msg): print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) <|reserved_special_token_0|> def errorcode(msg): return ERRORS.splitlines().index(msg) + 1 def error(*msg): print(colorama.Fore.RED + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) sys.exit(errorcode(msg[0])) <|reserved_special_token_0|> def setup_part1(args): """ Made before reading config file (config file located in args.root). Check and normalize root path. """ args.rootarg = args.root rootext = os.path.splitext(args.rootarg)[1] if rootext == '': pass else: args.root = os.path.dirname(args.root) if args.root: args.root = os.path.abspath(args.root) if not os.path.isdir(args.root): if args.gallery: os.mkdir(args.root) else: error('Directory not found', args.root) def setup_part2(args): """ Made after reading config file. Check for ffmpeg in path. Create .thumbnails dir if necessary and create .nomedia in it. Copy photobox file to destination dir. Handle priority between command line and config file. """ if args.update: args.sourcedir = args.source.sourcedir args.bydir = args.source.bydir args.bydate = args.source.bydate args.diary = args.source.diary args.recursive = args.source.recursive args.dates = args.source.dates args.github_pages = args.source.github_pages elif args.gallery: args.source.sourcedir = args.sourcedir args.source.bydir = args.bydir args.source.bydate = args.bydate args.source.diary = args.diary args.source.recursive = args.recursive args.source.dates = args.dates args.source.github_pages = args.github_pages update_config(args) if args.github_pages: args.html_suffix = '.html' else: args.html_suffix = '.htm' rootext = os.path.splitext(args.rootarg)[1] if rootext: args.rootname = os.path.basename(args.rootarg) else: args.rootname = 'index' + args.html_suffix if args.sourcedir: args.sourcedir = os.path.abspath(args.sourcedir) if os.path.splitdrive(args.sourcedir)[0]: drive, rest = os.path.splitdrive(args.sourcedir) args.sourcedir = drive.upper() + rest if not os.path.isdir(args.sourcedir): error('Directory not found', args.sourcedir) elif args.gallery and args.diary is False and args.update is None: error('Directory not found', 'Use --sourcedir') if args.dest: args.dest = os.path.abspath(args.dest) if args.dest is None: args.dest = args.root if args.blogger and args.urlblogger is None: error('No blogger url (--url)') if args.gallery or args.update: for exe in ('ffmpeg', 'ffprobe'): try: check_output([exe, '-version']) except FileNotFoundError: error('File not found', exe) if args.github_pages: args.thumbrep = 'thumbnails' else: args.thumbrep = '.thumbnails' args.thumbdir = os.path.join(args.dest, args.thumbrep) if not os.path.exists(args.thumbdir): os.mkdir(args.thumbdir) open(os.path.join(args.thumbdir, '.nomedia'), 'a').close() favicondst = os.path.join(args.dest, 'favicon.ico') if not os.path.isfile(favicondst): faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico') shutil.copyfile(faviconsrc, favicondst) photoboxdir = os.path.join(args.dest, 'photobox') if not os.path.exists(photoboxdir): photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox') shutil.copytree(photoboxsrc, photoboxdir) if args.dates: if not (args.gallery or args.create): pass if args.dates == 'source': pass elif args.dates == 'diary': if args.create: error('Incorrect date format', args.dates) elif re.match('\\d+-\\d+', args.dates): date1, date2 = args.dates.split('-') if validate_date(date1) and validate_date(date2): args.dates = date1, date2 else: error('Incorrect date format', args.dates) else: error('Incorrect date format', args.dates) def main(argstring=None): colorama.init() args = parse_command_line(argstring) setup_part1(args) read_config(args) setup_part2(args) try: if args.gallery or args.update: create_gallery(args) elif args.create: create_diary(args) elif args.blogger: prepare_for_blogger(args) elif args.idem: idempotence(args) elif args.setcfg: setconfig_cmd(args) except KeyboardInterrupt: warning('Interrupted by user.') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Post: def __init__(self, date, text, medias): self.date = date self.text = text self.medias = medias self.dcim = [] self.daterank = 0 self.extra = False def __lt__(self, other): return self.date < other.date @classmethod def from_markdown(cls, post): m = re.match('\\[(\\d\\d\\d\\d/\\d\\d/\\d\\d)\\]\\n*', post[0]) if m: date = m.group(1).replace('/', '') if not validate_date(date): error('Incorrect date value:', date) del post[0] else: error('No date in post', ' '.join(post)) while post and not post[0].strip(): del post[0] text = '' while post and not re.match('!?\\[\\]', post[0]): text += post[0] del post[0] text = re.sub('\\n\\n$', '\n', text) medias = list() while post and (match := re.match('!?\\[\\]\\((.*)\\)', post[0])): media = match.group(1) caption = None del post[0] if post and not re.match('!?\\[\\]', post[0]): caption = post[0].strip() del post[0] if match.group(0)[0] == '!': medias.append(PostImage(caption, media)) else: medias.append(PostVideo(caption, media)) return cls(date, text, medias) @classmethod def from_date(cls, date): dt = datetime.datetime.strptime(date, '%Y%m%d') datetext = dt.strftime('%A %d %B %Y').capitalize() post = cls(date, text=datetext, medias=[]) post.daterank = 1 return post def to_html(self, args, target='regular'): if target == 'regular': if args.diary: return self.to_html_diary(args) else: return self.to_html_regular(args) if target == 'blogger': return self.to_html_blogger() def to_html_regular(self, args): html = list() if self.text: html.append(markdown.markdown(self.text)) subdirs, dcim = dispatch_post_items(self.dcim) if self.dcim: html.append(SEP) for media in subdirs: html.append(media.to_html_dcim(args)) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) return html def to_html_diary(self, args): html = list() if self.extra: html.append('<div class="extra">') if self.text: html.append(markdown.markdown(self.text)) if self.medias: html.append(f'<div id="gallery-blog-{self.date}-{self.daterank}">') for media in self.medias: html.append(media.to_html_post(args)) html.append('</div>') _, dcim = dispatch_post_items(self.dcim) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') html.append(SEP) for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) if self.extra: html.append('</div>') return html def to_html_blogger(self): html = list() html.append(markdown.markdown(self.text)) for image in self.medias: html.append(image.to_html_blogger()) html.append(SEP) return html class PostItem: def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''): self.caption = caption self.uri = uri self.basename = os.path.basename(uri) self.thumb = thumb self.thumbsize = thumbsize self.descr = descr self.resized_url = None class PostImage(PostItem): def to_markdown(self): if not self.caption: return '![](%s)' % (self.uri,) else: return '![](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, * self.thumbsize, descr) def to_html_blogger(self): if not self.caption: return BIMGPAT % (self.uri, self.resized_url) else: return f'{BIMGPAT}\n{CAPTION_PAT}' % (self.uri, self. resized_url, self.caption) class PostVideo(PostItem): def to_markdown(self): if not self.caption: return '[](%s)' % (self.uri,) else: return '[](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, * self.thumbsize, descr) def to_html_blogger(self): x = f'<p style="text-align: center;">{self.iframe}</p>' if not self.caption: return x else: return f'%s\n{CAPTION_PAT}' % (x, self.caption) class PostSubdir(PostItem): def to_html_dcim(self, args): basename = os.path.basename(self.htmname) posts = self.posts title = self.caption print_html(args, posts, title, self.htmname) if not self.caption: return DIRPOST % (basename, self.thumb, *self.thumbsize) else: return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize, self.caption) def relative_url(path, root): """ returns a normalized url to path relative from root """ try: url = os.path.relpath(path, root) except: error('Unable to make a relative url:', url, root) url = url.replace('\\', '/') if os.sep == '\\' else url return urllib.parse.quote(url) def parse_markdown(filename): """ Generate Post objects from markdown. Date must be present in each post and posts must be ordrered by date. """ if not os.path.exists(filename): error('File not found', filename) posts = list() with open(filename, encoding='utf-8') as f: line = next(f) if line.startswith('# '): title = line[2:].strip() record = [] next(f) else: title = None record = [line] for line in f: if not line.startswith('___'): record.append(line) else: posts.append(Post.from_markdown(record)) record = [] daterank = defaultdict(int) for post in posts: daterank[post.date] += 1 post.daterank = daterank[post.date] for post1, post2 in zip(posts[:-1], posts[1:]): if post1.date > post2.date: error('Posts are not ordered', f'{post1.date} > {post2.date}') return title, posts def print_markdown(posts, title, fullname): with open(fullname, 'wt', encoding='utf-8') as fdst: print(f'# {title}\n', file=fdst) for post in posts: date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]' print(date, file=fdst) if post.text: print(file=fdst) for line in post.text.splitlines(): if not line: print(file=fdst) else: for chunk in textwrap.wrap(line, width=78): print(chunk, file=fdst) if post.medias: print(file=fdst) for media in post.medias: print(media.to_markdown(), file=fdst) print('______', file=fdst) def compose_html_reduced(args, posts, title, target): html = list() html.append(START % title) for post in posts: for line in post.to_html(args, target): html.append(line.strip()) html.append('') html.append(END) return html def compose_html_full(args, posts, title, target): html = list() html.append(START % title) if args.diary: html.append(BUTTONS) for post in posts: for line in post.to_html(args, target): html.append(line.strip()) html.append('') html.append('<script>') for post in posts: if post.medias: gallery_id = f'gallery-blog-{post.date}-{post.daterank}' html.append(gallery_call(args, gallery_id)) if post.dcim: gallery_id = f'gallery-dcim-{post.date}-{post.daterank}' html.append(gallery_call(args, gallery_id)) html.append('</script>') html.append(END) return html def print_html_to_stream(args, posts, title, stream, target): if target == 'regular': for line in compose_html_full(args, posts, title, target): print(line, file=stream) else: for line in compose_html_reduced(args, posts, title, target): print(line, file=stream) def print_html(args, posts, title, html_name, target='regular'): assert target in ('regular', 'blogger') with io.StringIO() as f: print_html_to_stream(args, posts, title, f, target) html = f.getvalue() if html_name: if os.path.exists(html_name): with open(html_name, 'rt', encoding='utf-8') as f: html0 = f.read() if html == html0: return None with open(html_name, 'wt', encoding='utf-8') as f: f.write(html) return None else: return html <|reserved_special_token_0|> def is_image_file(name): return os.path.splitext(name)[1].lower() in ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tif') def is_video_file(name): return os.path.splitext(name)[1].lower() in ('.mp4', '.webm', '.mkv', '.flv', '.m4v', '.avi', '.wmv', '.mts', '.vob', '.divx') def is_media(name): return is_image_file(name) or is_video_file(name) def validate_date(datestr): try: datetime.datetime.strptime(datestr, '%Y%m%d') return True except ValueError: return False def date_from_name(name): if (match := re.search('(?:\\D|^)(\\d{8})(?:\\D|$)', name, re.ASCII)): digits = match.group(1) if validate_date(digits): return digits return None def date_from_item(filename): if (date := date_from_name(filename)): return date else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d') def time_from_name(name): if (match := re.search('(?:\\D|^)(\\d{8})\\D(\\d{6})(?:\\D|$)', name, re.ASCII)): digits = match.group(2) hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits [4:6]) if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60: return digits return None def time_from_item(filename): if (time := time_from_name(filename)): return time else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S') <|reserved_special_token_0|> def get_image_info(filename): date = date_from_item(filename) time = time_from_item(filename) img = Image.open(filename) width, height = img.size size = round(os.path.getsize(filename) / 1000000.0, 1) return (date, time, width, height, size ), f'{date} {time}, dim={width}x{height}, {size} MB' def get_video_info(filename, info_fullname): if os.path.exists(info_fullname): with open(info_fullname) as f: info = f.readline().split() date, time, width, height, size, duration, fps = info[0], info[1], int( info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6] ) formatted_info = format_video_info(date, time, width, height, size, duration, fps) return (date, time, width, height, size, duration, fps), formatted_info else: info, formatted_info = make_video_info(filename, info_fullname) with open(info_fullname, 'wt') as f: print(' '.join([str(_) for _ in info]), file=f) return info, formatted_info def make_video_info(filename, info_fullname): date = date_from_item(filename) time = time_from_item(filename) command = [*FFPROBE_CMD.split(), filename] try: output = check_output(command, stderr=STDOUT).decode() width, height, fps, duration = parse_ffprobe_output(output) size = round(os.path.getsize(filename) / 1000000.0, 1) output = format_video_info(date, time, width, height, size, duration, fps) except CalledProcessError as e: output = e.output.decode() warning(output) raise return (date, time, width, height, size, duration, fps), output def parse_ffprobe_output(ffprobe_output): match = re.match( '(\\d+),(\\d+),(\\d+)/(\\d+),(\\d+/\\d+).*\\s(\\d+\\.\\d+)', ffprobe_output, re.DOTALL) width = int(match.group(1)) height = int(match.group(2)) fps = round(int(match.group(3)) / int(match.group(4)), 1) duration = round(float(match.group(6))) return width, height, fps, duration def format_video_info(date, time, width, height, size, duration, fps): return ( f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB' ) def format_duration(duration): mn = duration // 60 sec = duration % 60 if mn <= 59: return f'm:s={mn:02}:{sec:02}' else: hour = mn // 60 mn = mn % 60 return f'h:m:s={hour:02}:{mn:02}:{sec:02}' def thumbname(name, key): return key + '-' + name + '.jpg' def size_thumbnail(width, height, maxdim): if width >= height: return maxdim, int(round(maxdim * height / width)) else: return int(round(maxdim * width / height)), maxdim def make_thumbnail_image(args, image_name, thumb_name, size): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_image(image_name, thumb_name, size) def create_thumbnail_image(image_name, thumb_name, size): imgobj = Image.open(image_name) if imgobj.mode != 'RGBA' and image_name.endswith('.jpg') and not ( image_name.endswith('.gif') and imgobj.info.get('transparency')): imgobj = imgobj.convert('RGBA') imgobj.thumbnail(size, Image.LANCZOS) imgobj = imgobj.convert('RGB') imgobj.save(thumb_name) def make_thumbnail_video(args, video_name, thumb_name, size, duration): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_video(args, video_name, thumb_name, size, duration) <|reserved_special_token_0|> def create_thumbnail_video(args, filename, thumbname, size, duration): delay = min(duration - 1, args.thumbnails.thumbdelay) sizearg = '%dx%d' % size command = ( 'ffmpeg -y -v error -itsoffset -%d -i "%s" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s "%s"' ) command = command % (delay, filename, sizearg, thumbname) result = os.system(command) try: img1 = Image.open(thumbname) except: warning('Unable to save thumbnail for', filename) return img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON))) width, height = img1.size img1.paste(img2, (6, height - 20 - 6), None) img1.save(thumbname) def make_thumbnail_subdir(args, subdir_name, thumb_name, size, items, thumbdir ): print('Making thumbnail:', thumb_name) create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir) def create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir): def size_thumbnail(width, height, xmax, ymax): width2 = xmax height2 = int(round(xmax * height / width)) if height2 < ymax: width2 = int(round(ymax * width / height)) height2 = ymax return width2, height2 thumblist = [os.path.basename(item.thumb) for item in items] widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size , thumblist) thumbnum = widthnum * heightnum img = Image.new('RGB', size, SUBDIR_BACKCOL) for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]): row = ind // widthnum col = ind % widthnum img2 = Image.open(os.path.join(thumbdir, thumb)) w, h = size_thumbnail(*img2.size, width[col], height[row]) cropdim = (w - width[col]) // 2, (h - height[row]) // 2, (w - width [col]) // 2 + width[col], (h - height[row]) // 2 + height[row] img2 = img2.resize((w, h), Image.LANCZOS) img2 = img2.crop(cropdim) img.paste(img2, (offsetx[col], offsety[row])) if os.path.exists(thumb_name): imgref = Image.open(thumb_name) byteio = io.BytesIO() img.save(byteio, 'JPEG') byteio.seek(0) imgnew = Image.open(byteio) diff = ImageChops.difference(imgnew, imgref) if diff.getbbox() is None: return img.save(thumb_name) def mosaic_geometry(size, thumblist): if len(thumblist) == 1: widthnum = 1 heightnum = 1 elif len(thumblist) <= 3: widthnum = 1 heightnum = 2 elif len(thumblist) <= 8: widthnum = 2 heightnum = 2 else: widthnum = 3 heightnum = 3 if widthnum == 1: width = [size[0] - 2] else: width = [size[0] // widthnum - 2] * (widthnum - 1) width.append(size[0] - (1 + sum(width) + 2 * len(width) + 1)) if heightnum == 1: height = [size[1] - 2] else: height = [size[1] // heightnum - 2] * (heightnum - 1) height.append(size[1] - (1 + sum(height) + 2 * len(height) + 1)) offsetx = [1] for w in width[:-1]: offsetx.append(offsetx[-1] + w + 2) offsety = [1] for h in height[:-1]: offsety.append(offsety[-1] + h + 2) return widthnum, heightnum, width, height, offsetx, offsety <|reserved_special_token_0|> def list_of_htmlfiles_in_items(itemlist): htmlist = list() for item in itemlist: if type(item) == PostSubdir: htmlist.append(item.htmname) htmlist.extend(list_of_htmlfiles_in_items(item.sublist)) return htmlist def list_of_thumbnails(posts, diary=False): thumblist = list() for post in posts: thumblist.extend(list_of_thumbnails_in_items(post.medias)) if diary is False: thumblist.extend(list_of_thumbnails_in_items(post.dcim)) return thumblist def list_of_thumbnails_in_items(itemlist): thumblist = list() for item in itemlist: if type(item) == PostSubdir: thumblist.append(os.path.basename(item.thumb)) thumblist.extend(list_of_thumbnails_in_items(item.sublist)) else: thumblist.append(os.path.basename(item.thumb)) return thumblist def purge_htmlfiles(args, posts): """ Purge root dir from irrelevant html files """ htmlist = list_of_htmlfiles(args, posts) html_to_remove = list() for fullname in glob.glob(os.path.join(args.root, '*.htm*')): if fullname not in htmlist: html_to_remove.append(fullname) if len(html_to_remove) > args.thumbnails.threshold_htmlfiles: inpt = 'x' while inpt not in 'yn': inpt = input( f'{len(html_to_remove)} html files to remove. Continue [y|n]? ' ).lower() if inpt == 'n': return for name in html_to_remove: print('Removing html files', name) os.remove(name) def purge_thumbnails(args, thumbdir, posts, diary=False): """ Purge thumbnail dir from irrelevant thumbnails """ thumblist = list_of_thumbnails(posts, diary) thumbs_to_remove = list() for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')): if os.path.basename(fullname) not in thumblist: thumbs_to_remove.append(fullname) if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs: inpt = 'x' while inpt not in 'yn': inpt = input( f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? ' ).lower() if inpt == 'n': return for name in thumbs_to_remove: print('Removing thumbnail', name) os.remove(name) info_fullname = os.path.splitext(name)[0] + '.info' if os.path.exists(info_fullname): os.remove(info_fullname) def is_media_within_dates(fullname, dates): if is_media(fullname): if type(dates) == tuple: return dates[0] <= date_from_item(fullname) <= dates[1] else: return True else: return False def sorted_listdir(filelist): like_windows_explorer = True if not filelist: return filelist if like_windows_explorer: maxlen = max(len(os.path.splitext(name)[0]) for name in filelist) def keyfunc(name): root, ext = os.path.splitext(name.lower()) return root.ljust(maxlen, ' ') + ext else: keyfunc = str.lower return sorted(filelist, key=keyfunc) def list_of_files(sourcedir, recursive): """ Return the list of full paths for files in source directory """ result = list() if recursive is False: listdir = sorted_listdir(os.listdir(sourcedir)) if '.nomedia' not in listdir: for basename in listdir: result.append(os.path.join(sourcedir, basename)) else: for root, dirs, files in os.walk(sourcedir): if '.nomedia' not in files: for basename in sorted_listdir(files): result.append(os.path.join(root, basename)) return result def list_of_medias(args, sourcedir, recursive): """ Return the list of full paths for pictures and movies in source directory """ files = list_of_files(sourcedir, recursive) return [_ for _ in files if is_media_within_dates(_, args.dates)] <|reserved_special_token_0|> def dispatch_post_items(list_of_post_items): subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir] medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir] return subdirs, medias def create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax): if os.path.isfile(media_fullname): if is_image_file(media_fullname): return create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_subdir(args, media_fullname, sourcedir, thumbdir, key, thumbmax) def create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax ): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) try: info, infofmt = get_image_info(media_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize) return PostImage(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except PIL.UnidentifiedImageError: warning('Unable to read image', media_fullname) return None def create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax ): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) info_fullname = os.path.splitext(thumb_fullname)[0] + '.info' try: info, infofmt = get_video_info(media_fullname, info_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_video(args, media_fullname, thumb_fullname, thumbsize, duration=info[5]) return PostVideo(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except CalledProcessError: warning('Unable to read video', media_fullname) return None <|reserved_special_token_0|> def relative_name(media_fullname, sourcedir): """ /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg --> deeper2_deepest_OCT_20000112_000004.jpg /Gilles/Dev/journal/tests/subdir/deeper2/deepest --> deeper2_deepest """ x = os.path.relpath(media_fullname, sourcedir) x = x.replace('\\', '_').replace('/', '_').replace('#', '_') return x def make_posts(args, dirname): if args.diary is True: if not args.sourcedir: return make_posts_from_diary(args) else: return make_posts_from_diary_and_dir(args) elif args.bydate is False: return make_posts_from_subdir(args, dirname) else: return make_posts_from_subdir_and_date(args, dirname) def make_posts_from_diary(args): md_filename = os.path.join(args.root, 'index.md') if os.path.exists(md_filename): title, posts = parse_markdown(md_filename) else: error('File not found', md_filename) for post in posts: for media in post.medias: media_fullname = os.path.join(args.root, media.uri) item = create_item(args, media_fullname, args.root, args. thumbdir, 'post', 400) media.thumb = item.thumb media.thumbsize = item.thumbsize media.descr = item.descr return title, posts def create_items_by_date(args, medias, posts): if args.dates == 'diary': required_dates = {post.date for post in posts} else: required_dates = {date_from_item(media) for media in medias} if type(args.dates) == tuple: date1, date2 = args.dates required_dates = {date for date in required_dates if date1 <= date <= date2} bydate = defaultdict(list) for media_fullname in medias: date = date_from_item(media_fullname) if date in required_dates: item = create_item(args, media_fullname, args.sourcedir, args. thumbdir, 'dcim', 300) if item: bydate[date].append(item) for date, liste in bydate.items(): liste.sort(key=lambda item: time_from_item(item.uri)) return bydate <|reserved_special_token_0|> def make_posts_from_subdir(args, dirname): if args.bydir is False: medias_ext = list_of_medias(args, dirname, args.recursive) else: medias_ext = list_of_medias_ext(args, dirname) postmedias = list() for item in medias_ext: postmedia = create_item(args, item, args.sourcedir, args.thumbdir, 'dcim', 300) if postmedia is not None: postmedias.append(postmedia) post = Post(date='00000000', text='', medias=[]) post.dcim = postmedias posts = [post] title = os.path.basename(args.sourcedir) or os.path.splitdrive(args. sourcedir)[0] return title, posts def make_posts_from_subdir_and_date(args, dirname): if args.bydir is False: medias = list_of_medias(args, dirname, args.recursive) subdirs = [] else: medias_ext = list_of_medias_ext(args, dirname) medias = [_ for _ in medias_ext if is_media(_)] subdirs = [_ for _ in medias_ext if not is_media(_)] posts = list() items = list() for media_fullname in subdirs: item = create_item(args, media_fullname, args.sourcedir, args. thumbdir, 'dcim', 300) if item: items.append(item) if items: post = Post(date='00000000', text='', medias=[]) post.dcim = items posts.append(post) bydate = create_items_by_date(args, medias, posts) for date in sorted(bydate): post = Post.from_date(date) post.dcim = bydate[post.date] posts.append(post) title = os.path.basename(args.sourcedir) or os.path.splitdrive(args. sourcedir)[0] return title, posts def create_gallery(args): title, posts = make_posts(args, args.sourcedir) print_html(args, posts, title, os.path.join(args.dest, args.rootname), 'regular') purge_htmlfiles(args, posts) if args.diary and not args.sourcedir: purge_thumbnails(args, args.thumbdir, posts, diary=True) else: purge_thumbnails(args, args.thumbdir, posts) def create_diary(args): medias = list_of_medias(args, args.sourcedir, args.recursive) if args.dates == 'diary': assert 0 else: required_dates = {date_from_item(media) for media in medias} if type(args.dates) == tuple: date1, date2 = args.dates required_dates = {date for date in required_dates if date1 <= date <= date2} title = args.sourcedir posts = list() for date in sorted(required_dates): posts.append(Post.from_date(date)) os.makedirs(args.root, exist_ok=True) print_markdown(posts, title, os.path.join(args.root, 'index.md')) def online_images_url(args): try: if args.urlblogger.startswith('http:') or args.urlblogger.startswith( 'https:'): with urlopen(args.urlblogger) as u: buffer = u.read() else: with open(args.urlblogger, 'rb') as f: buffer = f.read() except: error('Unable to read url', args.urlblogger) buffer = buffer.decode('utf-8') online_images = dict() for match in re.finditer('<div class="separator"((?!<div).)*?</div>', buffer, flags=re.DOTALL): div_separator = match.group(0) div_separator = div_separator.replace('&nbsp;', '') elem_div = objectify.fromstring(div_separator) for elem_a in elem_div.iterchildren(tag='a'): href = elem_a.get('href') thumb = elem_a.img.get('src') online_images[os.path.basename(href)] = href, thumb online_videos = list() for match in re.finditer( '<iframe allowfullscreen="allowfullscreen".*?</iframe>', buffer, flags=re.DOTALL): iframe = match.group(0) online_videos.append(iframe) return online_images, online_videos def compare_image_buffers(imgbuf1, imgbuf2): """ return True if images read on file are identical, False otherwise """ with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2: img1 = Image.open(imgio1) img2 = Image.open(imgio2) diff = ImageChops.difference(img1, img2) return not diff.getbbox() def check_images(args, posts, online_images): result = True for post in posts: for media in post.medias: if type(media) is PostImage: if media.basename in online_images: with open(os.path.join(args.root, media.uri), 'rb') as f: imgbuf1 = f.read() try: with urlopen(online_images[media.basename][0]) as u: imgbuf2 = u.read() except FileNotFoundError: print('File not found', online_images[media. basename][0]) next if compare_image_buffers(imgbuf1, imgbuf2) is False: print('Files are different, upload', media.basename) elif 1: print('File already online', media.basename) else: print('File is absent, upload', media.basename) result = False elif type(media) is PostVideo: print('Video not checked', media.basename) else: assert False return result def compose_blogger_html(args, title, posts, imgdata, online_videos): """ Compose html with blogger image urls """ for post in posts: for media in post.medias: if type(media) is PostImage: if media.uri not in imgdata: print('Image missing: ', media.uri) else: img_url, resized_url = imgdata[media.uri] media.uri = img_url media.resized_url = resized_url elif type(media) is PostVideo: if not online_videos: print('Video missing: ', media.uri) else: media.iframe = online_videos[0] del online_videos[0] else: assert False return print_html(args, posts, title, '', target='blogger') def prepare_for_blogger(args): """ Export blogger html to clipboard. If --full, export complete html, otherwise export html extract ready to paste into blogger edit mode. """ title, posts = parse_markdown(os.path.join(args.root, 'index.md')) online_images, online_videos = online_images_url(args) if args.check_images and check_images(args, posts, online_images) is False: pass html = compose_blogger_html(args, title, posts, online_images, online_videos) if args.full is False: html = re.search('<body>(.*)?</body>', html, flags=re.DOTALL).group(1) html = re.sub('<script>.*?</script>', '', html, flags=re.DOTALL) html = STYLE.replace('%%', '%') + html if args.dest: with open(args.dest, 'wt', encoding='utf-8') as f: f.write(html) else: clipboard.copy(html) def idempotence(args): """ For testing identity between a diary file and the fle obtained after reading and printing it. See testing. """ title, posts = parse_markdown(os.path.join(args.root, 'index.md')) print_markdown(posts, title, os.path.join(args.dest, 'index.md')) <|reserved_special_token_0|> class MyConfigParser(ConfigParser): """Add input checking.""" def __init__(self): ConfigParser.__init__(self, inline_comment_prefixes=(';',)) def error(self, section, entry): error('Missing or incorrect config value:', '[%s]%s' % (section, entry) ) def getint(self, section, entry, default=None): try: if default is None: return ConfigParser.getint(self, section, entry) else: return ConfigParser.getint(self, section, entry, raw=True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def getboolean(self, section, entry, default=None): try: if default is None: return ConfigParser.getboolean(self, section, entry) else: return ConfigParser.getboolean(self, section, entry, raw= True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def configfilename(params): return os.path.join(params.root, '.config.ini') def createconfig(config_filename): with open(config_filename, 'wt') as f: f.writelines(CONFIG_DEFAULTS) def read_config(params): config_filename = configfilename(params) try: if not os.path.exists(config_filename) or params.resetcfg: createconfig(config_filename) except: error('Error creating configuration file') try: getconfig(params, config_filename) except Exception as e: error('Error reading configuration file.', str(e), 'Use --resetcfg') def getconfig(options, config_filename): class Section: pass options.source = Section() options.thumbnails = Section() options.photobox = Section() config = MyConfigParser() config.read(config_filename) options.source.sourcedir = config.get('source', 'sourcedir') options.source.bydir = config.getboolean('source', 'bydir') options.source.bydate = config.getboolean('source', 'bydate') options.source.diary = config.getboolean('source', 'diary') options.source.recursive = config.getboolean('source', 'recursive') options.source.dates = config.get('source', 'dates') options.source.github_pages = config.getboolean('source', 'github_pages', default=False) options.thumbnails.media_description = config.getboolean('thumbnails', 'media_description') options.thumbnails.subdir_caption = config.getboolean('thumbnails', 'subdir_caption') options.thumbnails.thumbdelay = config.getint('thumbnails', 'thumbdelay') options.thumbnails.threshold_thumbs = config.getint('thumbnails', 'threshold_thumbs') options.thumbnails.threshold_htmlfiles = config.getint('thumbnails', 'threshold_htmlfiles', default=3) options.photobox.loop = config.getboolean('photobox', 'loop') options.photobox.thumbs = config.getboolean('photobox', 'thumbs') options.photobox.autoplay = config.getboolean('photobox', 'autoplay') options.photobox.time = config.getint('photobox', 'time') options.photobox.zoomable = config.getboolean('photobox', 'zoomable') options.photobox.rotatable = config.getboolean('photobox', 'rotatable') options.photobox.wheelNextPrev = config.getboolean('photobox', 'wheelNextPrev') def setconfig(cfgname, section, key, value): config = MyConfigParser() config.read(cfgname) config.set(section, key, value) with open(cfgname, 'wt') as configfile: config.write(configfile) def setconfig_cmd(args): config_filename = configfilename(args) setconfig(config_filename, *args.setcfg) def update_config(args): updates = ('sourcedir', args.sourcedir), ('bydir', BOOL[args.bydir]), ( 'bydate', BOOL[args.bydate]), ('diary', BOOL[args.diary]), ('recursive' , BOOL[args.recursive]), ('dates', args.dates), ('github_pages', BOOL[args.github_pages]) cfgname = configfilename(args) with open(cfgname) as f: cfglines = [_.strip() for _ in f.readlines()] for key, value in updates: for iline, line in enumerate(cfglines): if line.startswith(key): cfglines[iline] = f'{key} = {value}' break with open(cfgname, 'wt') as f: for line in cfglines: print(line, file=f) def warning(*msg): print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) <|reserved_special_token_0|> def errorcode(msg): return ERRORS.splitlines().index(msg) + 1 def error(*msg): print(colorama.Fore.RED + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) sys.exit(errorcode(msg[0])) <|reserved_special_token_0|> def parse_command_line(argstring): parser = argparse.ArgumentParser(description=None, usage=USAGE) agroup = parser.add_argument_group('Commands') xgroup = agroup.add_mutually_exclusive_group() xgroup.add_argument('--gallery', help='source in --sourcedir', action= 'store', metavar='<root-dir>') agroup.add_argument('--update', help= 'updates gallery with parameters in config file', action='store', metavar='<root-dir>') xgroup.add_argument('--create', help= 'create journal from medias in --sourcedir', action='store', metavar='<root-dir>') xgroup.add_argument('--resetcfg', help='reset config file to defaults', action='store', metavar='<root-dir>') xgroup.add_argument('--setcfg', help=argparse.SUPPRESS, action='store', nargs=4, metavar='<root-dir>') xgroup.add_argument('--idem', help=argparse.SUPPRESS, action='store', metavar='<root-dir>') xgroup.add_argument('--blogger', help= 'input md, html blogger ready in clipboard', action='store', metavar='<root-dir>') agroup = parser.add_argument_group('Parameters') agroup.add_argument('--bydir', help='organize gallery by subdirectory', action='store', default=None, choices=BOOL) agroup.add_argument('--bydate', help='organize gallery by date', action ='store', default=None, choices=BOOL) agroup.add_argument('--diary', help= 'organize gallery using markdown file diary', action='store', default=None, choices=BOOL) agroup.add_argument('--recursive', help='--sourcedir scans recursively', action='store', default=None, choices=BOOL) agroup.add_argument('--dates', help='dates interval', action='store', default=None) agroup.add_argument('--sourcedir', help='media directory', action= 'store', default=None) agroup.add_argument('--github_pages', help='github Pages compatibility', action='store', default=None, choices=BOOL) agroup.add_argument('--dest', help='output directory', action='store') agroup.add_argument('--forcethumb', help= 'force calculation of thumbnails', action='store_true', default=False) agroup.add_argument('--full', help= 'full html (versus blogger ready html)', action='store_true', default=False) agroup.add_argument('--check', dest='check_images', help= 'check availability of medias on blogger', action='store_true') agroup.add_argument('--url', dest='urlblogger', help='blogger post url', action='store') if argstring is None: print('Type "galerie -h" for help') sys.exit(1) else: args = parser.parse_args(argstring.split()) if args.update and (args.bydir or args.bydate or args.diary or args. sourcedir or args.recursive or args.dates or args.github_pages): error('Incorrect parameters:', '--update cannot be used with creation parameters, use explicit command' ) args.bydir = args.bydir == 'true' args.bydate = args.bydate == 'true' args.diary = args.diary == 'true' args.recursive = args.recursive == 'true' args.dates = 'source' if args.dates is None else args.dates args.github_pages = args.github_pages == 'true' args.root = (args.create or args.gallery or args.update or args.blogger or args.idem or args.resetcfg) if args.setcfg: args.root = args.setcfg[0] args.setcfg = args.setcfg[1:] return args def setup_part1(args): """ Made before reading config file (config file located in args.root). Check and normalize root path. """ args.rootarg = args.root rootext = os.path.splitext(args.rootarg)[1] if rootext == '': pass else: args.root = os.path.dirname(args.root) if args.root: args.root = os.path.abspath(args.root) if not os.path.isdir(args.root): if args.gallery: os.mkdir(args.root) else: error('Directory not found', args.root) def setup_part2(args): """ Made after reading config file. Check for ffmpeg in path. Create .thumbnails dir if necessary and create .nomedia in it. Copy photobox file to destination dir. Handle priority between command line and config file. """ if args.update: args.sourcedir = args.source.sourcedir args.bydir = args.source.bydir args.bydate = args.source.bydate args.diary = args.source.diary args.recursive = args.source.recursive args.dates = args.source.dates args.github_pages = args.source.github_pages elif args.gallery: args.source.sourcedir = args.sourcedir args.source.bydir = args.bydir args.source.bydate = args.bydate args.source.diary = args.diary args.source.recursive = args.recursive args.source.dates = args.dates args.source.github_pages = args.github_pages update_config(args) if args.github_pages: args.html_suffix = '.html' else: args.html_suffix = '.htm' rootext = os.path.splitext(args.rootarg)[1] if rootext: args.rootname = os.path.basename(args.rootarg) else: args.rootname = 'index' + args.html_suffix if args.sourcedir: args.sourcedir = os.path.abspath(args.sourcedir) if os.path.splitdrive(args.sourcedir)[0]: drive, rest = os.path.splitdrive(args.sourcedir) args.sourcedir = drive.upper() + rest if not os.path.isdir(args.sourcedir): error('Directory not found', args.sourcedir) elif args.gallery and args.diary is False and args.update is None: error('Directory not found', 'Use --sourcedir') if args.dest: args.dest = os.path.abspath(args.dest) if args.dest is None: args.dest = args.root if args.blogger and args.urlblogger is None: error('No blogger url (--url)') if args.gallery or args.update: for exe in ('ffmpeg', 'ffprobe'): try: check_output([exe, '-version']) except FileNotFoundError: error('File not found', exe) if args.github_pages: args.thumbrep = 'thumbnails' else: args.thumbrep = '.thumbnails' args.thumbdir = os.path.join(args.dest, args.thumbrep) if not os.path.exists(args.thumbdir): os.mkdir(args.thumbdir) open(os.path.join(args.thumbdir, '.nomedia'), 'a').close() favicondst = os.path.join(args.dest, 'favicon.ico') if not os.path.isfile(favicondst): faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico') shutil.copyfile(faviconsrc, favicondst) photoboxdir = os.path.join(args.dest, 'photobox') if not os.path.exists(photoboxdir): photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox') shutil.copytree(photoboxsrc, photoboxdir) if args.dates: if not (args.gallery or args.create): pass if args.dates == 'source': pass elif args.dates == 'diary': if args.create: error('Incorrect date format', args.dates) elif re.match('\\d+-\\d+', args.dates): date1, date2 = args.dates.split('-') if validate_date(date1) and validate_date(date2): args.dates = date1, date2 else: error('Incorrect date format', args.dates) else: error('Incorrect date format', args.dates) def main(argstring=None): colorama.init() args = parse_command_line(argstring) setup_part1(args) read_config(args) setup_part2(args) try: if args.gallery or args.update: create_gallery(args) elif args.create: create_diary(args) elif args.blogger: prepare_for_blogger(args) elif args.idem: idempotence(args) elif args.setcfg: setconfig_cmd(args) except KeyboardInterrupt: warning('Interrupted by user.') <|reserved_special_token_0|> <|reserved_special_token_1|> """ Make html galleries from media directories. Organize by dates, by subdirs or by the content of a diary file. The diary file is a markdown file organized by dates, each day described by a text and some medias (photos and movies). The diary file can be exported to: * an html file with the text and subset of medias associated with each day, * the previous html file extended with all medias in the media directory, * an html file ready to import into Blogger. """ import sys import os import argparse import glob import shutil import re import io import bisect import locale import textwrap import base64 import datetime import urllib from configparser import ConfigParser from collections import defaultdict from subprocess import check_output, CalledProcessError, STDOUT from urllib.request import urlopen import colorama import clipboard import PIL from PIL import Image, ImageChops from lxml import objectify import markdown USAGE = """ galerie --gallery <root-dir> [--sourcedir <media-dir>] [--bydir true|false*] [--bydate true|false*] [--diary true|false*] [--recursive true|false*] [--dates source*|diary|<yyyymmdd-yyyymmdd>] [--github_pages true|false] [--dest <directory>] [--forcethumb] galerie --update <root-dir> galerie --create <root-dir> --sourcedir <media-dir> [--recursive true|false*] [--dates source*|<yyyymmdd-yyyymmdd>] galerie --blogger <root-dir> --url <url> [--check] [--full] [--dest <filename>] Notes: - * gives default - all options can be abbreviated if there is no conflict with other options (--gallery --> --gal) """ # -- Post objects ------------------------------------------------------------- CAPTION_IMAGE_STYLE = '''\ <style type="text/css"> span { display:inline-table; } </style>\ ''' STYLE = '''\ <style type="text/css"> p { margin-top:0px; margin-bottom:0px; } h3 { font-size: 100%%; font-weight: bold; margin-top:0px; margin-bottom:0px; } </style> ''' START = f'''\ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>%s</title> <link rel="icon" href="favicon.ico" /> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="photobox/photobox.css"> <script src="photobox/jquery.min.js"></script> <script src="photobox/jquery.photobox.js"></script> {CAPTION_IMAGE_STYLE} {STYLE} </head> <body>\ ''' BUTTONS = '''\ <button id="btn_full" type="button" style="position: fixed; width: 50px; top: 20px; right: 20px; background-color:white">Full</button> <button id="btn_blog" type="button" style="position: fixed; width: 50px; top: 40px; right: 20px; background-color:white">Diary</button> <button id="btn_text" type="button" style="position: fixed; width: 50px; top: 60px; right: 20px; background-color:white">Text</button> <script> $('#btn_full').click(function() { $("[id^=gallery-blog]").show(); $("[id^=gallery-dcim]").show(); $("div.extra").show(); }); $('#btn_text').click(function() { $("[id^=gallery-blog]").hide(); $("[id^=gallery-dcim]").hide(); $("div.extra").hide(); }); $('#btn_blog').click(function() { $("[id^=gallery-blog]").show(); $("[id^=gallery-dcim]").hide(); $("div.extra").hide(); }); </script> ''' SUBDIR_BACKCOL = '#eee' END = '</body>\n</html>' SEP = '<hr color="#C0C0C0" size="1" />' IMGPOST = '<a href="%s"><img src="%s" width="%d" height="%d" title="%s"/></a>' VIDPOST = '<a href="%s" rel="video"><img src="%s" width="%d" height="%d" title="%s"/></a>' IMGPOSTCAPTION = '''\ <span> <a href="%s"><img src=%s width="%d" height="%d" title="%s"/></a> <p>%s</p> </span> ''' VIDPOSTCAPTION = '''\ <span> <a href="%s" rel="video"><img src=%s width="%d" height="%d" title="%s"/></a> <p>%s</p> </span> ''' IMGDCIM = '<a href="%s"><img src="%s" width="%d" height="%d" title="%s"/></a>' VIDDCIM = '<a href="%s" rel="video"><img src="%s" width="%d" height="%d" title="%s"/></a>' # diminution de l'espace entre images, on utilise : # "display: block;", "margin-bottom: 0em;" et "font-size: 0;" # "display: block;" dans img : espacement correct ordi mais pas centré téléphone # "display: block;" dans a : ok DIRPOST = '<a href="%s"><img src="%s" width="%d" height="%d" style="border: 1px solid #C0C0C0;" /></a>' DIRPOSTCAPTION = f''' <span style="background-color:{SUBDIR_BACKCOL}; margin-bottom: 8px; border: 1px solid #C0C0C0;"> <a href="%s"><img src="%s" width="%d" height="%d" style="border: 1px solid #C0C0C0;" /></a> <p style="margin-left:2px;">%s</p> </span> ''' BIMGPAT = '''\ <div class="separator" style="clear: both; text-align: center;"> <a href="%s" style="clear: left; margin-bottom: 0em; margin-right: 1em; font-size: 0; display: block;"> <img border="0" src="%s" width="640" /> </a></div> ''' CAPTION_PAT = '''\ <div class="separator" style="clear: both; text-align: center;"> %s </div> ''' class Post: def __init__(self, date, text, medias): # date: yyyymmdd self.date = date self.text = text self.medias = medias self.dcim = [] self.daterank = 0 self.extra = False def __lt__(self, other): return self.date < other.date @classmethod def from_markdown(cls, post): m = re.match(r'\[(\d\d\d\d/\d\d/\d\d)\]\n*', post[0]) if m: date = m.group(1).replace('/', '') if not validate_date(date): error('Incorrect date value:', date) del post[0] else: error('No date in post', ' '.join(post)) while post and not post[0].strip(): del post[0] text = '' while post and not re.match(r'!?\[\]', post[0]): text += post[0] del post[0] # remove empty lines at end text = re.sub(r'\n\n$', '\n', text) medias = list() while post and (match := re.match(r'!?\[\]\((.*)\)', post[0])): media = match.group(1) caption = None del post[0] if post and not re.match(r'!?\[\]', post[0]): caption = post[0].strip() del post[0] if match.group(0)[0] == '!': medias.append(PostImage(caption, media)) else: medias.append(PostVideo(caption, media)) return cls(date, text, medias) @classmethod def from_date(cls, date): dt = datetime.datetime.strptime(date, '%Y%m%d') datetext = dt.strftime("%A %d %B %Y").capitalize() post = cls(date, text=datetext, medias=[]) post.daterank = 1 return post def to_html(self, args, target='regular'): if target == 'regular': if args.diary: return self.to_html_diary(args) else: return self.to_html_regular(args) if target == 'blogger': return self.to_html_blogger() def to_html_regular(self, args): html = list() if self.text: # possible with --bydate html.append(markdown.markdown(self.text)) subdirs, dcim = dispatch_post_items(self.dcim) if self.dcim: html.append(SEP) for media in subdirs: html.append(media.to_html_dcim(args)) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) return html def to_html_diary(self, args): html = list() if self.extra: html.append('<div class="extra">') if self.text: html.append(markdown.markdown(self.text)) if self.medias: html.append(f'<div id="gallery-blog-{self.date}-{self.daterank}">') for media in self.medias: html.append(media.to_html_post(args)) html.append('</div>') _, dcim = dispatch_post_items(self.dcim) if dcim: html.append(f'<div id="gallery-dcim-{self.date}-{self.daterank}">') html.append(SEP) for media in dcim: html.append(media.to_html_dcim(args)) html.append('</div>') html.append(SEP) if self.extra: html.append('</div>') return html def to_html_blogger(self): html = list() html.append(markdown.markdown(self.text)) for image in self.medias: html.append(image.to_html_blogger()) html.append(SEP) return html class PostItem: def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''): self.caption = caption self.uri = uri self.basename = os.path.basename(uri) self.thumb = thumb self.thumbsize = thumbsize self.descr = descr self.resized_url = None class PostImage(PostItem): def to_markdown(self): if not self.caption: return '![](%s)' % (self.uri,) else: return '![](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, *self.thumbsize, descr) def to_html_blogger(self): if not self.caption: return BIMGPAT % (self.uri, self.resized_url) else: return f'{BIMGPAT}\n{CAPTION_PAT}' % (self.uri, self.resized_url, self.caption) class PostVideo(PostItem): def to_markdown(self): if not self.caption: return '[](%s)' % (self.uri,) else: return '[](%s)\n%s' % (self.uri, self.caption) def to_html_post(self, args): descr = self.descr if args.thumbnails.media_description else '' if not self.caption: return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr) else: return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption) def to_html_dcim(self, args): descr = self.descr if args.thumbnails.media_description else '' return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, *self.thumbsize, descr) def to_html_blogger(self): x = f'<p style="text-align: center;">{self.iframe}</p>' if not self.caption: return x else: return f'%s\n{CAPTION_PAT}' % (x, self.caption) class PostSubdir(PostItem): def to_html_dcim(self, args): basename = os.path.basename(self.htmname) posts = self.posts title = self.caption print_html(args, posts, title, self.htmname) if not self.caption: return DIRPOST % (basename, self.thumb, *self.thumbsize) else: return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize, self.caption) def relative_url(path, root): """ returns a normalized url to path relative from root """ try: url = os.path.relpath(path, root) except: error('Unable to make a relative url:', url, root) url = url.replace('\\', '/') if os.sep == '\\' else url return urllib.parse.quote(url) # -- Markdown parser ---------------------------------------------------------- def parse_markdown(filename): """ Generate Post objects from markdown. Date must be present in each post and posts must be ordrered by date. """ if not os.path.exists(filename): error('File not found', filename) posts = list() with open(filename, encoding='utf-8') as f: line = next(f) if line.startswith('# '): title = line[2:].strip() record = [] next(f) else: title = None record = [line] for line in f: if not line.startswith('___'): record.append(line) else: posts.append(Post.from_markdown(record)) record = [] # set rank of posts in date daterank = defaultdict(int) for post in posts: daterank[post.date] += 1 post.daterank = daterank[post.date] # check post order for post1, post2 in zip(posts[:-1], posts[1:]): if post1.date > post2.date: error('Posts are not ordered', f'{post1.date} > {post2.date}') return title, posts # -- Markdown printer --------------------------------------------------------- def print_markdown(posts, title, fullname): with open(fullname, 'wt', encoding='utf-8') as fdst: print(f'# {title}\n', file=fdst) for post in posts: date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]' print(date, file=fdst) if post.text: print(file=fdst) for line in post.text.splitlines(): if not line: print(file=fdst) else: for chunk in textwrap.wrap(line, width=78): print(chunk, file=fdst) if post.medias: print(file=fdst) for media in post.medias: print(media.to_markdown(), file=fdst) print('______', file=fdst) # -- html printer ------------------------------------------------------------- def compose_html_reduced(args, posts, title, target): html = list() html.append(START % title) for post in posts: for line in post.to_html(args, target): html.append(line.strip()) html.append('') html.append(END) return html def compose_html_full(args, posts, title, target): html = list() html.append(START % title) if args.diary: html.append(BUTTONS) for post in posts: for line in post.to_html(args, target): html.append(line.strip()) html.append('') html.append('<script>') for post in posts: if post.medias: gallery_id = f'gallery-blog-{post.date}-{post.daterank}' html.append(gallery_call(args, gallery_id)) if post.dcim: gallery_id = f'gallery-dcim-{post.date}-{post.daterank}' html.append(gallery_call(args, gallery_id)) html.append('</script>') html.append(END) return html def print_html_to_stream(args, posts, title, stream, target): if target == 'regular': for line in compose_html_full(args, posts, title, target): print(line, file=stream) else: for line in compose_html_reduced(args, posts, title, target): print(line, file=stream) def print_html(args, posts, title, html_name, target='regular'): assert target in ('regular', 'blogger') with io.StringIO() as f: print_html_to_stream(args, posts, title, f, target) html = f.getvalue() if html_name: if os.path.exists(html_name): # test if the generated html is identical to the one already on disk with open(html_name, 'rt', encoding='utf-8') as f: html0 = f.read() if html == html0: return None with open(html_name, 'wt', encoding='utf-8') as f: f.write(html) return None else: return html GALLERYCALL = """ $('#%s').photobox('a', { loop:%s, thumbs:%s, autoplay:%s, time:%d, zoomable:%s , rotatable:%s, wheelNextPrev:%s }); """ def gallery_call(args, gallery_id): return GALLERYCALL.replace('\n', '') % ( gallery_id, str(args.photobox.loop).lower(), str(args.photobox.thumbs).lower(), str(args.photobox.autoplay).lower(), args.photobox.time, str(args.photobox.zoomable).lower(), str(args.photobox.rotatable).lower(), str(args.photobox.wheelNextPrev).lower(), ) # -- Media description -------------------------------------------------------- def is_image_file(name): return os.path.splitext(name)[1].lower() in ( '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tif' ) def is_video_file(name): return os.path.splitext(name)[1].lower() in ( '.mp4', '.webm', '.mkv', '.flv', '.m4v', '.avi', '.wmv', '.mts', '.vob', '.divx' ) def is_media(name): return is_image_file(name) or is_video_file(name) def validate_date(datestr): # datestr = yyyymmdd try: datetime.datetime.strptime(datestr, '%Y%m%d') return True except ValueError: return False def date_from_name(name): # heuristics if match := re.search(r'(?:\D|^)(\d{8})(?:\D|$)', name, re.ASCII): digits = match.group(1) if validate_date(digits): return digits return None def date_from_item(filename): if date := date_from_name(filename): return date else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d') def time_from_name(name): # heuristics if match := re.search(r'(?:\D|^)(\d{8})\D(\d{6})(?:\D|$)', name, re.ASCII): digits = match.group(2) hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits[4:6]) if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60: return digits return None def time_from_item(filename): if time := time_from_name(filename): return time else: timestamp = os.path.getmtime(filename) return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S') FFPROBE_CMD = '''\ ffprobe -v error -select_streams v:0 -show_entries stream=width,height,avg_frame_rate,r_frame_rate:format=duration -of csv=p=0 ''' def get_image_info(filename): date = date_from_item(filename) time = time_from_item(filename) img = Image.open(filename) width, height = img.size size = round(os.path.getsize(filename) / 1e6, 1) return (date, time, width, height, size), f'{date} {time}, dim={width}x{height}, {size} MB' def get_video_info(filename, info_fullname): if os.path.exists(info_fullname): with open(info_fullname) as f: info = f.readline().split() date, time, width, height, size, duration, fps = info[0], info[1], int(info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6]) formatted_info = format_video_info(date, time, width, height, size, duration, fps) return (date, time, width, height, size, duration, fps), formatted_info else: info, formatted_info = make_video_info(filename, info_fullname) with open(info_fullname, 'wt') as f: print(' '.join([str(_) for _ in info]), file=f) return info, formatted_info def make_video_info(filename, info_fullname): # ffmpeg must be in path date = date_from_item(filename) time = time_from_item(filename) command = [*FFPROBE_CMD.split(), filename] try: output = check_output(command, stderr=STDOUT).decode() width, height, fps, duration = parse_ffprobe_output(output) size = round(os.path.getsize(filename) / 1e6, 1) output = format_video_info(date, time, width, height, size, duration, fps) except CalledProcessError as e: output = e.output.decode() warning(output) raise return (date, time, width, height, size, duration, fps), output def parse_ffprobe_output(ffprobe_output): # parse first channel data and last line for duration match = re.match(r'(\d+),(\d+),(\d+)/(\d+),(\d+/\d+).*\s(\d+\.\d+)', ffprobe_output, re.DOTALL) width = int(match.group(1)) height = int(match.group(2)) fps = round(int(match.group(3)) / int(match.group(4)), 1) duration = round(float(match.group(6))) return width, height, fps, duration def format_video_info(date, time, width, height, size, duration, fps): return f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB' def format_duration(duration): mn = duration // 60 sec = duration % 60 if mn <= 59: return f'm:s={mn:02}:{sec:02}' else: hour = mn // 60 mn = mn % 60 return f'h:m:s={hour:02}:{mn:02}:{sec:02}' # -- Thumbnails (image and video) --------------------------------------------- def thumbname(name, key): return key + '-' + name + '.jpg' def size_thumbnail(width, height, maxdim): if width >= height: return maxdim, int(round(maxdim * height / width)) else: return int(round(maxdim * width / height)), maxdim def make_thumbnail_image(args, image_name, thumb_name, size): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_image(image_name, thumb_name, size) def create_thumbnail_image(image_name, thumb_name, size): imgobj = Image.open(image_name) if (imgobj.mode != 'RGBA' and image_name.endswith('.jpg') and not (image_name.endswith('.gif') and imgobj.info.get('transparency')) ): imgobj = imgobj.convert('RGBA') imgobj.thumbnail(size, Image.LANCZOS) imgobj = imgobj.convert('RGB') imgobj.save(thumb_name) def make_thumbnail_video(args, video_name, thumb_name, size, duration): if os.path.exists(thumb_name) and args.forcethumb is False: pass else: print('Making thumbnail:', thumb_name) create_thumbnail_video(args, video_name, thumb_name, size, duration) # base64 video.png VIDEO_ICON = '''\ iVBORw0KGgoAAAANSUhEUgAAABgAAAAUCAAAAACy3qJfAAAA4UlEQVR4 2m1QoRbCMAy88SaK69xscfuEWiS4SZBIcCCRfAL8An8AcnJzTOJSWdxwzJXSPUoHRPQlueYuucigxm 9kDGaMf8AjopGcYn8LmmyLoihBWBiThb+5MTuUsc3aL56upneZ9sByAIg8Z8BEn96EeZ65iU7DvmbP PxqDcH6p1swXBC4l6yZskACkTN1WrQr2SlIFhTtgqeZa+zsOogLXegvEocZ5c/W5BcoVNNCg3hSudV /hEh4ofw6cEb00Km8i0dpRDUXfKiaQOEAdrUDo4dFp9C33jjaRac9/gDF/AlplVYtfWGCjAAAAAElF TkSuQmCC''' def create_thumbnail_video(args, filename, thumbname, size, duration): # ffmpeg must be in path delay = min(duration - 1, args.thumbnails.thumbdelay) sizearg = '%dx%d' % size command = 'ffmpeg -y -v error -itsoffset -%d -i "%s" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s "%s"' command = command % (delay, filename, sizearg, thumbname) result = os.system(command) # add a movie icon to the thumbnail to identify videos try: img1 = Image.open(thumbname) except: # ffmpeg was unable to save thumbnail warning('Unable to save thumbnail for', filename) return img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON))) width, height = img1.size img1.paste(img2, (6, height - 20 - 6), None) img1.save(thumbname) def make_thumbnail_subdir(args, subdir_name, thumb_name, size, items, thumbdir): # subdir thumbnails are always created as they depend on the content of the # directory print('Making thumbnail:', thumb_name) create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir) def create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir): def size_thumbnail(width, height, xmax, ymax): width2 = xmax height2 = int(round(xmax * height / width)) if height2 < ymax: width2 = int(round(ymax * width / height)) height2 = ymax return width2, height2 thumblist = [os.path.basename(item.thumb) for item in items] widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size, thumblist) thumbnum = widthnum * heightnum img = Image.new('RGB', size, SUBDIR_BACKCOL) for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]): row = ind // widthnum col = ind % widthnum img2 = Image.open(os.path.join(thumbdir, thumb)) w, h = size_thumbnail(*img2.size, width[col], height[row]) cropdim = ((w - width[col]) // 2, (h - height[row]) // 2, (w - width[col]) // 2 + width[col], (h - height[row]) // 2 + height[row]) img2 = img2.resize((w, h), Image.LANCZOS) img2 = img2.crop(cropdim) img.paste(img2, (offsetx[col], offsety[row])) if os.path.exists(thumb_name): # test if the generated thumbnail is identical to the one already on disk imgref = Image.open(thumb_name) # must save and reload before comparing byteio = io.BytesIO() img.save(byteio, "JPEG") byteio.seek(0) imgnew = Image.open(byteio) diff = ImageChops.difference(imgnew, imgref) if diff.getbbox() is None: return img.save(thumb_name) def mosaic_geometry(size, thumblist): if len(thumblist) == 1: widthnum = 1 heightnum = 1 elif len(thumblist) <= 3: widthnum = 1 heightnum = 2 elif len(thumblist) <= 8: widthnum = 2 heightnum = 2 else: widthnum = 3 heightnum = 3 if widthnum == 1: width = [size[0] - 2] else: width = [size[0] // widthnum - 2] * (widthnum - 1) width.append(size[0] - (1 + sum(width) + 2 * len(width) + 1)) if heightnum == 1: height = [size[1] - 2] else: height = [size[1] // heightnum - 2] * (heightnum - 1) height.append(size[1] - (1 + sum(height) + 2 * len(height) + 1)) offsetx = [1] for w in width[:-1]: offsetx.append(offsetx[-1] + w + 2) offsety = [1] for h in height[:-1]: offsety.append(offsety[-1] + h + 2) return widthnum, heightnum, width, height, offsetx, offsety def list_of_htmlfiles(args, posts): htmlist = list() htmlist.append(os.path.join(args.dest, args.rootname)) for post in posts: htmlist.extend(list_of_htmlfiles_in_items(post.dcim)) return htmlist def list_of_htmlfiles_in_items(itemlist): htmlist = list() for item in itemlist: if type(item) == PostSubdir: htmlist.append(item.htmname) htmlist.extend(list_of_htmlfiles_in_items(item.sublist)) return htmlist def list_of_thumbnails(posts, diary=False): thumblist = list() for post in posts: thumblist.extend(list_of_thumbnails_in_items(post.medias)) if diary is False: thumblist.extend(list_of_thumbnails_in_items(post.dcim)) return thumblist def list_of_thumbnails_in_items(itemlist): thumblist = list() for item in itemlist: if type(item) == PostSubdir: thumblist.append(os.path.basename(item.thumb)) thumblist.extend(list_of_thumbnails_in_items(item.sublist)) else: thumblist.append(os.path.basename(item.thumb)) return thumblist def purge_htmlfiles(args, posts): """ Purge root dir from irrelevant html files """ htmlist = list_of_htmlfiles(args, posts) html_to_remove = list() for fullname in glob.glob(os.path.join(args.root, '*.htm*')): if fullname not in htmlist: html_to_remove.append(fullname) if len(html_to_remove) > args.thumbnails.threshold_htmlfiles: inpt = 'x' while inpt not in 'yn': inpt = input(f'{len(html_to_remove)} html files to remove. Continue [y|n]? ').lower() if inpt == 'n': return for name in html_to_remove: print('Removing html files', name) os.remove(name) def purge_thumbnails(args, thumbdir, posts, diary=False): """ Purge thumbnail dir from irrelevant thumbnails """ thumblist = list_of_thumbnails(posts, diary) thumbs_to_remove = list() for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')): if os.path.basename(fullname) not in thumblist: thumbs_to_remove.append(fullname) if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs: inpt = 'x' while inpt not in 'yn': inpt = input(f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? ').lower() if inpt == 'n': return for name in thumbs_to_remove: print('Removing thumbnail', name) os.remove(name) info_fullname = os.path.splitext(name)[0] + '.info' if os.path.exists(info_fullname): os.remove(info_fullname) # -- List of medias helpers --------------------------------------------------- def is_media_within_dates(fullname, dates): if is_media(fullname): if type(dates) == tuple: return dates[0] <= date_from_item(fullname) <= dates[1] else: return True else: return False def sorted_listdir(filelist): like_windows_explorer = True if not filelist: return filelist if like_windows_explorer: maxlen = max(len(os.path.splitext(name)[0]) for name in filelist) def keyfunc(name): root, ext = os.path.splitext(name.lower()) return root.ljust(maxlen, ' ') + ext else: keyfunc = str.lower return sorted(filelist, key=keyfunc) def list_of_files(sourcedir, recursive): """ Return the list of full paths for files in source directory """ result = list() if recursive is False: listdir = sorted_listdir(os.listdir(sourcedir)) if '.nomedia' not in listdir: for basename in listdir: result.append(os.path.join(sourcedir, basename)) else: for root, dirs, files in os.walk(sourcedir): if '.nomedia' not in files: for basename in sorted_listdir(files): result.append(os.path.join(root, basename)) return result def list_of_medias(args, sourcedir, recursive): """ Return the list of full paths for pictures and movies in source directory """ files = list_of_files(sourcedir, recursive) return [_ for _ in files if is_media_within_dates(_, args.dates)] def list_of_medias_ext(args, sourcedir): """ Return the list of full paths for pictures and movies in source directory plus subdirectories containing media """ result = list() listdir = sorted_listdir(os.listdir(sourcedir)) if '.nomedia' not in listdir: for basename in listdir: fullname = os.path.join(sourcedir, basename) if os.path.isdir(fullname) and basename != '$RECYCLE.BIN' and contains_media(args, fullname): result.append(fullname) else: if is_media_within_dates(fullname, args.dates): result.append(fullname) return result def contains_media(args, dirname): for root, dirs, files in os.walk(dirname): if '.nomedia' not in files: for basename in files: if is_media_within_dates(os.path.join(root, basename), args.dates): return True else: return False def dispatch_post_items(list_of_post_items): subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir] medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir] return subdirs, medias # -- Creation of gallery element ---------------------------------------------- def create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax): if os.path.isfile(media_fullname): if is_image_file(media_fullname): return create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax) else: return create_item_subdir(args, media_fullname, sourcedir, thumbdir, key, thumbmax) def create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) try: info, infofmt = get_image_info(media_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize) return PostImage(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except PIL.UnidentifiedImageError: # corrupted image warning('Unable to read image', media_fullname) return None def create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) info_fullname = os.path.splitext(thumb_fullname)[0] + '.info' try: info, infofmt = get_video_info(media_fullname, info_fullname) infofmt = media_basename + ': ' + infofmt thumbsize = size_thumbnail(info[2], info[3], thumbmax) make_thumbnail_video(args, media_fullname, thumb_fullname, thumbsize, duration=info[5]) return PostVideo(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) except CalledProcessError: # corrupted video warning('Unable to read video', media_fullname) return None def create_item_subdir(args, media_fullname, sourcedir, thumbdir, key, thumbmax): media_basename = os.path.basename(media_fullname) media_relname = relative_name(media_fullname, sourcedir) thumb_basename = thumbname(media_relname, key) thumb_fullname = os.path.join(thumbdir, thumb_basename) info, infofmt = None, None thumbsize = (thumbmax, int(round(thumbmax / 640 * 480))) medias_ext = list_of_medias_ext(args, media_fullname) if not medias_ext: return None item = PostSubdir(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)), thumbsize, infofmt) item.htmname = os.path.join(os.path.dirname(thumbdir), media_relname + args.html_suffix) if args.thumbnails.subdir_caption: item.caption = media_basename else: item.caption = '' _, posts = make_posts(args, media_fullname) item.posts = posts items = [item for post in posts for item in post.dcim] item.sublist = items make_thumbnail_subdir(args, media_fullname, thumb_fullname, thumbsize, items, thumbdir) return item def relative_name(media_fullname, sourcedir): """ /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg --> deeper2_deepest_OCT_20000112_000004.jpg /Gilles/Dev/journal/tests/subdir/deeper2/deepest --> deeper2_deepest """ x = os.path.relpath(media_fullname, sourcedir) x = x.replace('\\', '_').replace('/', '_').replace('#', '_') return x # -- Creation of posts -------------------------------------------------------- def make_posts(args, dirname): if args.diary is True: if not args.sourcedir: return make_posts_from_diary(args) else: return make_posts_from_diary_and_dir(args) elif args.bydate is False: return make_posts_from_subdir(args, dirname) else: return make_posts_from_subdir_and_date(args, dirname) def make_posts_from_diary(args): md_filename = os.path.join(args.root, 'index.md') if os.path.exists(md_filename): title, posts = parse_markdown(md_filename) else: error('File not found', md_filename) for post in posts: for media in post.medias: media_fullname = os.path.join(args.root, media.uri) item = create_item(args, media_fullname, args.root, args.thumbdir, 'post', 400) media.thumb = item.thumb media.thumbsize = item.thumbsize media.descr = item.descr return title, posts def create_items_by_date(args, medias, posts): # list of required dates if args.dates == 'diary': required_dates = {post.date for post in posts} else: required_dates = {date_from_item(media) for media in medias} if type(args.dates) == tuple: date1, date2 = args.dates required_dates = {date for date in required_dates if date1 <= date <= date2} bydate = defaultdict(list) for media_fullname in medias: date = date_from_item(media_fullname) if date in required_dates: item = create_item(args, media_fullname, args.sourcedir, args.thumbdir, 'dcim', 300) if item: bydate[date].append(item) for date, liste in bydate.items(): liste.sort(key=lambda item: time_from_item(item.uri)) return bydate def make_posts_from_diary_and_dir(args): title, posts = make_posts_from_diary(args) # list of all pictures and movies medias = list_of_medias(args, args.sourcedir, args.recursive) bydate = create_items_by_date(args, medias, posts) # make list of extra dates (not in posts) extradates = set(bydate) - {post.date for post in posts} # complete posts with extra dates for date in extradates: post = Post.from_date(date) post.extra = True bisect.insort(posts, post) # several posts can have the same date, only the first one is completed with dcim medias for post in posts: if post.date in bydate and post.daterank == 1: post.dcim = bydate[post.date] return title, posts def make_posts_from_subdir(args, dirname): # list of pictures and movies plus subdirectories if args.bydir is False: medias_ext = list_of_medias(args, dirname, args.recursive) else: medias_ext = list_of_medias_ext(args, dirname) #required_dates = get_required_dates(args, medias_ext, posts=None) #medias_ext_bis = [] #for media in medias_ext: # if complies_with_required_dates(media): # medias_ext_bis.append(media) # complete posts postmedias = list() for item in medias_ext: postmedia = create_item(args, item, args.sourcedir, args.thumbdir, 'dcim', 300) if postmedia is not None: postmedias.append(postmedia) post = Post(date='00000000', text='', medias=[]) post.dcim = postmedias posts = [post] title = os.path.basename(args.sourcedir) or os.path.splitdrive(args.sourcedir)[0] return title, posts def make_posts_from_subdir_and_date(args, dirname): # list of all pictures and movies if args.bydir is False: medias = list_of_medias(args, dirname, args.recursive) subdirs = [] else: medias_ext = list_of_medias_ext(args, dirname) medias = [_ for _ in medias_ext if is_media(_)] subdirs = [_ for _ in medias_ext if not is_media(_)] # create list of posts with a single post containing all subdirs posts = list() items = list() for media_fullname in subdirs: item = create_item(args, media_fullname, args.sourcedir, args.thumbdir, 'dcim', 300) if item: items.append(item) if items: post = Post(date='00000000', text='', medias=[]) post.dcim = items posts.append(post) bydate = create_items_by_date(args, medias, posts) # add dates for date in sorted(bydate): post = Post.from_date(date) post.dcim = bydate[post.date] posts.append(post) title = os.path.basename(args.sourcedir) or os.path.splitdrive(args.sourcedir)[0] return title, posts # -- Creation of html page from directory tree -------------------------------- def create_gallery(args): title, posts = make_posts(args, args.sourcedir) print_html(args, posts, title, os.path.join(args.dest, args.rootname), 'regular') purge_htmlfiles(args, posts) if args.diary and not args.sourcedir: purge_thumbnails(args, args.thumbdir, posts, diary=True) else: purge_thumbnails(args, args.thumbdir, posts) # -- Creation of diary from medias -------------------------------------------- def create_diary(args): # list of all pictures and movies medias = list_of_medias(args, args.sourcedir, args.recursive) # list of required dates if args.dates == 'diary': assert 0 else: required_dates = {date_from_item(media) for media in medias} if type(args.dates) == tuple: date1, date2 = args.dates required_dates = {date for date in required_dates if date1 <= date <= date2} title = args.sourcedir posts = list() for date in sorted(required_dates): posts.append(Post.from_date(date)) os.makedirs(args.root, exist_ok=True) print_markdown(posts, title, os.path.join(args.root, 'index.md')) # -- Export to blogger--------------------------------------------------------- def online_images_url(args): try: if args.urlblogger.startswith('http:') or args.urlblogger.startswith('https:'): with urlopen(args.urlblogger) as u: buffer = u.read() else: with open(args.urlblogger, 'rb') as f: buffer = f.read() except: error('Unable to read url', args.urlblogger) buffer = buffer.decode('utf-8') online_images = dict() for match in re.finditer('<div class="separator"((?!<div).)*?</div>', buffer, flags=re.DOTALL): div_separator = match.group(0) div_separator = div_separator.replace('&nbsp;', '') elem_div = objectify.fromstring(div_separator) for elem_a in elem_div.iterchildren(tag='a'): href = elem_a.get("href") thumb = elem_a.img.get("src") online_images[os.path.basename(href)] = (href, thumb) # video insertion relies only on video order online_videos = list() for match in re.finditer('<iframe allowfullscreen="allowfullscreen".*?</iframe>', buffer, flags=re.DOTALL): iframe = match.group(0) online_videos.append(iframe) return online_images, online_videos def compare_image_buffers(imgbuf1, imgbuf2): """ return True if images read on file are identical, False otherwise """ with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2: img1 = Image.open(imgio1) img2 = Image.open(imgio2) diff = ImageChops.difference(img1, img2) return not diff.getbbox() def check_images(args, posts, online_images): result = True for post in posts: for media in post.medias: if type(media) is PostImage: if media.basename in online_images: with open(os.path.join(args.root, media.uri), 'rb') as f: imgbuf1 = f.read() try: with urlopen(online_images[media.basename][0]) as u: imgbuf2 = u.read() except FileNotFoundError: print('File not found', online_images[media.basename][0]) next if compare_image_buffers(imgbuf1, imgbuf2) is False: print('Files are different, upload', media.basename) else: if 1: print('File already online', media.basename) else: print('File is absent, upload', media.basename) result = False elif type(media) is PostVideo: # no check for the moment print('Video not checked', media.basename) else: assert False return result def compose_blogger_html(args, title, posts, imgdata, online_videos): """ Compose html with blogger image urls """ for post in posts: for media in post.medias: if type(media) is PostImage: if media.uri not in imgdata: print('Image missing: ', media.uri) else: img_url, resized_url = imgdata[media.uri] media.uri = img_url media.resized_url = resized_url elif type(media) is PostVideo: if not online_videos: print('Video missing: ', media.uri) else: media.iframe = online_videos[0] del online_videos[0] else: assert False return print_html(args, posts, title, '', target='blogger') def prepare_for_blogger(args): """ Export blogger html to clipboard. If --full, export complete html, otherwise export html extract ready to paste into blogger edit mode. """ title, posts = parse_markdown(os.path.join(args.root, 'index.md')) online_images, online_videos = online_images_url(args) if args.check_images and check_images(args, posts, online_images) is False: pass html = compose_blogger_html(args, title, posts, online_images, online_videos) if args.full is False: html = re.search('<body>(.*)?</body>', html, flags=re.DOTALL).group(1) html = re.sub('<script>.*?</script>', '', html, flags=re.DOTALL) html = STYLE.replace('%%', '%') + html if args.dest: with open(args.dest, 'wt', encoding='utf-8') as f: f.write(html) else: clipboard.copy(html) # -- Other commands ----------------------------------------------------------- def idempotence(args): """ For testing identity between a diary file and the fle obtained after reading and printing it. See testing. """ title, posts = parse_markdown(os.path.join(args.root, 'index.md')) print_markdown(posts, title, os.path.join(args.dest, 'index.md')) # -- Configuration file ------------------------------------------------------ # The following docstring is used to create the configuration file. CONFIG_DEFAULTS = """\ [source] ; source directory ; value: valid path sourcedir = . ; one web page per directory ; value: true or false bydir = false ; dispatch medias by dates ; value: true or false bydate = false ; include text and medias from diary file ; value: true or false diary = false ; include subdirectories recursively (used when bydir is false) ; value: true or false recursive = false ; interval of dates to include ; value: source|diary|yyyymmdd-yyyymmdd or empty (= source) dates = ; github Pages compatibility (.htlml extension and no dot in directory names) ; value: true or false github_pages = false [thumbnails] ; specifies whether or not the gallery displays media description (size, dimension, etc) ; value: true or false media_description = true ; specifies whether subdir captions are empty or the name of the subdir ; value: true or false subdir_caption = true ; timestamp of thumbnail in video ; value: number of seconds thumbdelay = 5 ; maximum number of thumbnails to remove without user confirmation ; value: integer threshold_thumbs = 10 [photobox] ; Allows to navigate between first and last images ; value: true or false loop = false ; Show gallery thumbnails below the presented photo ; value: true or false thumbs = true ; Should autoplay on first time or not ; value: true or false autoplay = false ; Autoplay interval (less than 1000 will hide the autoplay button) ; value: milliseconds time = 3000 ; Disable/enable mousewheel image zooming ; value: true or false zoomable = true ; Allow rotation of the image ; value: true or false rotatable = true ; Change image using mousewheel left/right ; value: true or false wheelNextPrev = true """ class MyConfigParser (ConfigParser): """Add input checking.""" def __init__(self): ConfigParser.__init__(self, inline_comment_prefixes=(';',)) def error(self, section, entry): error('Missing or incorrect config value:', '[%s]%s' % (section, entry)) def getint(self, section, entry, default=None): try: if default is None: return ConfigParser.getint(self, section, entry) else: return ConfigParser.getint(self, section, entry, raw=True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def getboolean(self, section, entry, default=None): try: if default is None: return ConfigParser.getboolean(self, section, entry) else: return ConfigParser.getboolean(self, section, entry, raw=True, vars=None, fallback=default) except Exception as e: print(e) self.error(section, entry) def configfilename(params): return os.path.join(params.root, '.config.ini') def createconfig(config_filename): with open(config_filename, 'wt') as f: f.writelines(CONFIG_DEFAULTS) def read_config(params): config_filename = configfilename(params) try: if not os.path.exists(config_filename) or params.resetcfg: createconfig(config_filename) except: error('Error creating configuration file') try: getconfig(params, config_filename) except Exception as e: error('Error reading configuration file.', str(e), 'Use --resetcfg') def getconfig(options, config_filename): class Section: pass options.source = Section() options.thumbnails = Section() options.photobox = Section() config = MyConfigParser() config.read(config_filename) # [source] options.source.sourcedir = config.get('source', 'sourcedir') options.source.bydir = config.getboolean('source', 'bydir') options.source.bydate = config.getboolean('source', 'bydate') options.source.diary = config.getboolean('source', 'diary') options.source.recursive = config.getboolean('source', 'recursive') options.source.dates = config.get('source', 'dates') options.source.github_pages = config.getboolean('source', 'github_pages', default=False) # [thumbnails] options.thumbnails.media_description = config.getboolean('thumbnails', 'media_description') options.thumbnails.subdir_caption = config.getboolean('thumbnails', 'subdir_caption') options.thumbnails.thumbdelay = config.getint('thumbnails', 'thumbdelay') options.thumbnails.threshold_thumbs = config.getint('thumbnails', 'threshold_thumbs') options.thumbnails.threshold_htmlfiles = config.getint('thumbnails', 'threshold_htmlfiles', default=3) # [photobox] options.photobox.loop = config.getboolean('photobox', 'loop') options.photobox.thumbs = config.getboolean('photobox', 'thumbs') options.photobox.autoplay = config.getboolean('photobox', 'autoplay') options.photobox.time = config.getint('photobox', 'time') options.photobox.zoomable = config.getboolean('photobox', 'zoomable') options.photobox.rotatable = config.getboolean('photobox', 'rotatable') options.photobox.wheelNextPrev = config.getboolean('photobox', 'wheelNextPrev') def setconfig(cfgname, section, key, value): config = MyConfigParser() config.read(cfgname) config.set(section, key, value) with open(cfgname, 'wt') as configfile: config.write(configfile) def setconfig_cmd(args): config_filename = configfilename(args) setconfig(config_filename, *args.setcfg) def update_config(args): # update only entries which can be modified from the command line (source section) updates = ( ('sourcedir', args.sourcedir), ('bydir', BOOL[args.bydir]), ('bydate', BOOL[args.bydate]), ('diary', BOOL[args.diary]), ('recursive', BOOL[args.recursive]), ('dates', args.dates), ('github_pages', BOOL[args.github_pages]), ) # manual update to keep comments cfgname = configfilename(args) with open(cfgname) as f: cfglines = [_.strip() for _ in f.readlines()] for key, value in updates: for iline, line in enumerate(cfglines): if line.startswith(key): cfglines[iline] = f'{key} = {value}' break with open(cfgname, 'wt') as f: for line in cfglines: print(line, file=f) # -- Error handling ----------------------------------------------------------- def warning(*msg): print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) # Every error message error must be declared here to give a return code to the error ERRORS = '''\ File not found Directory not found No date in post Incorrect date value: Posts are not ordered Unable to read url No image source (--sourcedir) No blogger url (--url) Missing or incorrect config value: Error creating configuration file Error reading configuration file. Incorrect date format Incorrect parameters: ''' def errorcode(msg): return ERRORS.splitlines().index(msg) + 1 def error(*msg): print(colorama.Fore.RED + colorama.Style.BRIGHT + ' '.join(msg), colorama.Style.RESET_ALL) sys.exit(errorcode(msg[0])) # -- Main --------------------------------------------------------------------- BOOL = ('false', 'true') def parse_command_line(argstring): parser = argparse.ArgumentParser(description=None, usage=USAGE) agroup = parser.add_argument_group('Commands') xgroup = agroup.add_mutually_exclusive_group() xgroup.add_argument('--gallery', help='source in --sourcedir', action='store', metavar='<root-dir>') agroup.add_argument('--update', help='updates gallery with parameters in config file', action='store', metavar='<root-dir>') xgroup.add_argument('--create', help='create journal from medias in --sourcedir', action='store', metavar='<root-dir>') # testing xgroup.add_argument('--resetcfg', help='reset config file to defaults', action='store', metavar='<root-dir>') xgroup.add_argument('--setcfg', help=argparse.SUPPRESS, action='store', nargs=4, metavar='<root-dir>') xgroup.add_argument('--idem', help=argparse.SUPPRESS, action='store', metavar='<root-dir>') # blogger xgroup.add_argument('--blogger', help='input md, html blogger ready in clipboard', action='store', metavar='<root-dir>') agroup = parser.add_argument_group('Parameters') agroup.add_argument('--bydir', help='organize gallery by subdirectory', action='store', default=None, choices=BOOL) agroup.add_argument('--bydate', help='organize gallery by date', action='store', default=None, choices=BOOL) agroup.add_argument('--diary', help='organize gallery using markdown file diary', action='store', default=None, choices=BOOL) agroup.add_argument('--recursive', help='--sourcedir scans recursively', action='store', default=None, choices=BOOL) agroup.add_argument('--dates', help='dates interval', action='store', default=None) agroup.add_argument('--sourcedir', help='media directory', action='store', default=None) agroup.add_argument('--github_pages', help='github Pages compatibility', action='store', default=None, choices=BOOL) agroup.add_argument('--dest', help='output directory', action='store') agroup.add_argument('--forcethumb', help='force calculation of thumbnails', action='store_true', default=False) agroup.add_argument('--full', help='full html (versus blogger ready html)', action='store_true', default=False) agroup.add_argument('--check', dest='check_images', help='check availability of medias on blogger', action='store_true') agroup.add_argument('--url', dest='urlblogger', help='blogger post url', action='store') if argstring is None: print('Type "galerie -h" for help') sys.exit(1) else: args = parser.parse_args(argstring.split()) if args.update and (args.bydir or args.bydate or args.diary or args.sourcedir or args.recursive or args.dates or args.github_pages): error('Incorrect parameters:', '--update cannot be used with creation parameters, use explicit command') args.bydir = args.bydir == 'true' args.bydate = args.bydate == 'true' args.diary = args.diary == 'true' args.recursive = args.recursive == 'true' args.dates = 'source' if (args.dates is None) else args.dates args.github_pages = args.github_pages == 'true' args.root = ( args.create or args.gallery or args.update or args.blogger or args.idem or args.resetcfg ) if args.setcfg: args.root = args.setcfg[0] args.setcfg = args.setcfg[1:] return args def setup_part1(args): """ Made before reading config file (config file located in args.root). Check and normalize root path. """ args.rootarg = args.root rootext = os.path.splitext(args.rootarg)[1] if rootext == '': pass else: args.root = os.path.dirname(args.root) if args.root: args.root = os.path.abspath(args.root) if not os.path.isdir(args.root): if args.gallery: os.mkdir(args.root) else: error('Directory not found', args.root) def setup_part2(args): """ Made after reading config file. Check for ffmpeg in path. Create .thumbnails dir if necessary and create .nomedia in it. Copy photobox file to destination dir. Handle priority between command line and config file. """ if args.update: args.sourcedir = args.source.sourcedir args.bydir = args.source.bydir args.bydate = args.source.bydate args.diary = args.source.diary args.recursive = args.source.recursive args.dates = args.source.dates args.github_pages = args.source.github_pages elif args.gallery: args.source.sourcedir = args.sourcedir args.source.bydir = args.bydir args.source.bydate = args.bydate args.source.diary = args.diary args.source.recursive = args.recursive args.source.dates = args.dates args.source.github_pages = args.github_pages update_config(args) if args.github_pages: args.html_suffix = '.html' else: args.html_suffix = '.htm' rootext = os.path.splitext(args.rootarg)[1] if rootext: args.rootname = os.path.basename(args.rootarg) else: args.rootname = 'index' + args.html_suffix if args.sourcedir: args.sourcedir = os.path.abspath(args.sourcedir) if os.path.splitdrive(args.sourcedir)[0]: drive, rest = os.path.splitdrive(args.sourcedir) args.sourcedir = drive.upper() + rest if not os.path.isdir(args.sourcedir): error('Directory not found', args.sourcedir) else: if args.gallery and args.diary is False and args.update is None: error('Directory not found', 'Use --sourcedir') if args.dest: args.dest = os.path.abspath(args.dest) if args.dest is None: args.dest = args.root if args.blogger and args.urlblogger is None: error('No blogger url (--url)') if args.gallery or args.update: # check for ffmpeg and ffprobe in path for exe in ('ffmpeg', 'ffprobe'): try: check_output([exe, '-version']) except FileNotFoundError: error('File not found', exe) if args.github_pages: args.thumbrep = 'thumbnails' else: args.thumbrep = '.thumbnails' args.thumbdir = os.path.join(args.dest, args.thumbrep) if not os.path.exists(args.thumbdir): os.mkdir(args.thumbdir) open(os.path.join(args.thumbdir, '.nomedia'), 'a').close() favicondst = os.path.join(args.dest, 'favicon.ico') if not os.path.isfile(favicondst): faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico') shutil.copyfile(faviconsrc, favicondst) photoboxdir = os.path.join(args.dest, 'photobox') if not os.path.exists(photoboxdir): photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox') shutil.copytree(photoboxsrc, photoboxdir) if args.dates: if not(args.gallery or args.create): # silently ignored for the moment, otherwise all other commands will # launch a wanrning or an error on the default --dates value pass if args.dates == 'source': pass elif args.dates == 'diary': if args.create: error('Incorrect date format', args.dates) elif re.match(r'\d+-\d+', args.dates): date1, date2 = args.dates.split('-') if validate_date(date1) and validate_date(date2): args.dates = date1, date2 else: error('Incorrect date format', args.dates) else: error('Incorrect date format', args.dates) def main(argstring=None): colorama.init() args = parse_command_line(argstring) setup_part1(args) read_config(args) setup_part2(args) try: if args.gallery or args.update: create_gallery(args) elif args.create: create_diary(args) elif args.blogger: prepare_for_blogger(args) elif args.idem: idempotence(args) elif args.setcfg: setconfig_cmd(args) except KeyboardInterrupt: warning('Interrupted by user.') if __name__ == '__main__': main(' '.join(sys.argv[1:]))
flexible
{ "blob_id": "6018f35afc6646d0302ca32de649ffe7d544a765", "index": 3377, "step-1": "<mask token>\n\n\nclass Post:\n\n def __init__(self, date, text, medias):\n self.date = date\n self.text = text\n self.medias = medias\n self.dcim = []\n self.daterank = 0\n self.extra = False\n\n def __lt__(self, other):\n return self.date < other.date\n\n @classmethod\n def from_markdown(cls, post):\n m = re.match('\\\\[(\\\\d\\\\d\\\\d\\\\d/\\\\d\\\\d/\\\\d\\\\d)\\\\]\\\\n*', post[0])\n if m:\n date = m.group(1).replace('/', '')\n if not validate_date(date):\n error('Incorrect date value:', date)\n del post[0]\n else:\n error('No date in post', ' '.join(post))\n while post and not post[0].strip():\n del post[0]\n text = ''\n while post and not re.match('!?\\\\[\\\\]', post[0]):\n text += post[0]\n del post[0]\n text = re.sub('\\\\n\\\\n$', '\\n', text)\n medias = list()\n while post and (match := re.match('!?\\\\[\\\\]\\\\((.*)\\\\)', post[0])):\n media = match.group(1)\n caption = None\n del post[0]\n if post and not re.match('!?\\\\[\\\\]', post[0]):\n caption = post[0].strip()\n del post[0]\n if match.group(0)[0] == '!':\n medias.append(PostImage(caption, media))\n else:\n medias.append(PostVideo(caption, media))\n return cls(date, text, medias)\n\n @classmethod\n def from_date(cls, date):\n dt = datetime.datetime.strptime(date, '%Y%m%d')\n datetext = dt.strftime('%A %d %B %Y').capitalize()\n post = cls(date, text=datetext, medias=[])\n post.daterank = 1\n return post\n\n def to_html(self, args, target='regular'):\n if target == 'regular':\n if args.diary:\n return self.to_html_diary(args)\n else:\n return self.to_html_regular(args)\n if target == 'blogger':\n return self.to_html_blogger()\n\n def to_html_regular(self, args):\n html = list()\n if self.text:\n html.append(markdown.markdown(self.text))\n subdirs, dcim = dispatch_post_items(self.dcim)\n if self.dcim:\n html.append(SEP)\n for media in subdirs:\n html.append(media.to_html_dcim(args))\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n html.append(SEP)\n return html\n\n def to_html_diary(self, args):\n html = list()\n if self.extra:\n html.append('<div class=\"extra\">')\n if self.text:\n html.append(markdown.markdown(self.text))\n if self.medias:\n html.append(f'<div id=\"gallery-blog-{self.date}-{self.daterank}\">')\n for media in self.medias:\n html.append(media.to_html_post(args))\n html.append('</div>')\n _, dcim = dispatch_post_items(self.dcim)\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n html.append(SEP)\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n html.append(SEP)\n if self.extra:\n html.append('</div>')\n return html\n\n def to_html_blogger(self):\n html = list()\n html.append(markdown.markdown(self.text))\n for image in self.medias:\n html.append(image.to_html_blogger())\n html.append(SEP)\n return html\n\n\nclass PostItem:\n\n def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''):\n self.caption = caption\n self.uri = uri\n self.basename = os.path.basename(uri)\n self.thumb = thumb\n self.thumbsize = thumbsize\n self.descr = descr\n self.resized_url = None\n\n\nclass PostImage(PostItem):\n\n def to_markdown(self):\n if not self.caption:\n return '![](%s)' % (self.uri,)\n else:\n return '![](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize,\n descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, *\n self.thumbsize, descr)\n\n def to_html_blogger(self):\n if not self.caption:\n return BIMGPAT % (self.uri, self.resized_url)\n else:\n return f'{BIMGPAT}\\n{CAPTION_PAT}' % (self.uri, self.\n resized_url, self.caption)\n\n\nclass PostVideo(PostItem):\n\n def to_markdown(self):\n if not self.caption:\n return '[](%s)' % (self.uri,)\n else:\n return '[](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize,\n descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, *\n self.thumbsize, descr)\n\n def to_html_blogger(self):\n x = f'<p style=\"text-align: center;\">{self.iframe}</p>'\n if not self.caption:\n return x\n else:\n return f'%s\\n{CAPTION_PAT}' % (x, self.caption)\n\n\nclass PostSubdir(PostItem):\n\n def to_html_dcim(self, args):\n basename = os.path.basename(self.htmname)\n posts = self.posts\n title = self.caption\n print_html(args, posts, title, self.htmname)\n if not self.caption:\n return DIRPOST % (basename, self.thumb, *self.thumbsize)\n else:\n return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize,\n self.caption)\n\n\n<mask token>\n\n\ndef parse_markdown(filename):\n \"\"\"\n Generate Post objects from markdown. Date must be present in each post and\n posts must be ordrered by date.\n \"\"\"\n if not os.path.exists(filename):\n error('File not found', filename)\n posts = list()\n with open(filename, encoding='utf-8') as f:\n line = next(f)\n if line.startswith('# '):\n title = line[2:].strip()\n record = []\n next(f)\n else:\n title = None\n record = [line]\n for line in f:\n if not line.startswith('___'):\n record.append(line)\n else:\n posts.append(Post.from_markdown(record))\n record = []\n daterank = defaultdict(int)\n for post in posts:\n daterank[post.date] += 1\n post.daterank = daterank[post.date]\n for post1, post2 in zip(posts[:-1], posts[1:]):\n if post1.date > post2.date:\n error('Posts are not ordered', f'{post1.date} > {post2.date}')\n return title, posts\n\n\ndef print_markdown(posts, title, fullname):\n with open(fullname, 'wt', encoding='utf-8') as fdst:\n print(f'# {title}\\n', file=fdst)\n for post in posts:\n date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]'\n print(date, file=fdst)\n if post.text:\n print(file=fdst)\n for line in post.text.splitlines():\n if not line:\n print(file=fdst)\n else:\n for chunk in textwrap.wrap(line, width=78):\n print(chunk, file=fdst)\n if post.medias:\n print(file=fdst)\n for media in post.medias:\n print(media.to_markdown(), file=fdst)\n print('______', file=fdst)\n\n\n<mask token>\n\n\ndef is_image_file(name):\n return os.path.splitext(name)[1].lower() in ('.jpg', '.jpeg', '.png',\n '.gif', '.bmp', '.webp', '.tif')\n\n\n<mask token>\n\n\ndef is_media(name):\n return is_image_file(name) or is_video_file(name)\n\n\n<mask token>\n\n\ndef date_from_name(name):\n if (match := re.search('(?:\\\\D|^)(\\\\d{8})(?:\\\\D|$)', name, re.ASCII)):\n digits = match.group(1)\n if validate_date(digits):\n return digits\n return None\n\n\ndef date_from_item(filename):\n if (date := date_from_name(filename)):\n return date\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d')\n\n\ndef time_from_name(name):\n if (match := re.search('(?:\\\\D|^)(\\\\d{8})\\\\D(\\\\d{6})(?:\\\\D|$)', name,\n re.ASCII)):\n digits = match.group(2)\n hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits\n [4:6])\n if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60:\n return digits\n return None\n\n\ndef time_from_item(filename):\n if (time := time_from_name(filename)):\n return time\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S')\n\n\n<mask token>\n\n\ndef get_image_info(filename):\n date = date_from_item(filename)\n time = time_from_item(filename)\n img = Image.open(filename)\n width, height = img.size\n size = round(os.path.getsize(filename) / 1000000.0, 1)\n return (date, time, width, height, size\n ), f'{date} {time}, dim={width}x{height}, {size} MB'\n\n\ndef get_video_info(filename, info_fullname):\n if os.path.exists(info_fullname):\n with open(info_fullname) as f:\n info = f.readline().split()\n date, time, width, height, size, duration, fps = info[0], info[1], int(\n info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6]\n )\n formatted_info = format_video_info(date, time, width, height, size,\n duration, fps)\n return (date, time, width, height, size, duration, fps), formatted_info\n else:\n info, formatted_info = make_video_info(filename, info_fullname)\n with open(info_fullname, 'wt') as f:\n print(' '.join([str(_) for _ in info]), file=f)\n return info, formatted_info\n\n\ndef make_video_info(filename, info_fullname):\n date = date_from_item(filename)\n time = time_from_item(filename)\n command = [*FFPROBE_CMD.split(), filename]\n try:\n output = check_output(command, stderr=STDOUT).decode()\n width, height, fps, duration = parse_ffprobe_output(output)\n size = round(os.path.getsize(filename) / 1000000.0, 1)\n output = format_video_info(date, time, width, height, size,\n duration, fps)\n except CalledProcessError as e:\n output = e.output.decode()\n warning(output)\n raise\n return (date, time, width, height, size, duration, fps), output\n\n\ndef parse_ffprobe_output(ffprobe_output):\n match = re.match(\n '(\\\\d+),(\\\\d+),(\\\\d+)/(\\\\d+),(\\\\d+/\\\\d+).*\\\\s(\\\\d+\\\\.\\\\d+)',\n ffprobe_output, re.DOTALL)\n width = int(match.group(1))\n height = int(match.group(2))\n fps = round(int(match.group(3)) / int(match.group(4)), 1)\n duration = round(float(match.group(6)))\n return width, height, fps, duration\n\n\ndef format_video_info(date, time, width, height, size, duration, fps):\n return (\n f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB'\n )\n\n\n<mask token>\n\n\ndef size_thumbnail(width, height, maxdim):\n if width >= height:\n return maxdim, int(round(maxdim * height / width))\n else:\n return int(round(maxdim * width / height)), maxdim\n\n\ndef make_thumbnail_image(args, image_name, thumb_name, size):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_image(image_name, thumb_name, size)\n\n\ndef create_thumbnail_image(image_name, thumb_name, size):\n imgobj = Image.open(image_name)\n if imgobj.mode != 'RGBA' and image_name.endswith('.jpg') and not (\n image_name.endswith('.gif') and imgobj.info.get('transparency')):\n imgobj = imgobj.convert('RGBA')\n imgobj.thumbnail(size, Image.LANCZOS)\n imgobj = imgobj.convert('RGB')\n imgobj.save(thumb_name)\n\n\ndef make_thumbnail_video(args, video_name, thumb_name, size, duration):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_video(args, video_name, thumb_name, size, duration)\n\n\n<mask token>\n\n\ndef create_thumbnail_video(args, filename, thumbname, size, duration):\n delay = min(duration - 1, args.thumbnails.thumbdelay)\n sizearg = '%dx%d' % size\n command = (\n 'ffmpeg -y -v error -itsoffset -%d -i \"%s\" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s \"%s\"'\n )\n command = command % (delay, filename, sizearg, thumbname)\n result = os.system(command)\n try:\n img1 = Image.open(thumbname)\n except:\n warning('Unable to save thumbnail for', filename)\n return\n img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON)))\n width, height = img1.size\n img1.paste(img2, (6, height - 20 - 6), None)\n img1.save(thumbname)\n\n\n<mask token>\n\n\ndef create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir):\n\n def size_thumbnail(width, height, xmax, ymax):\n width2 = xmax\n height2 = int(round(xmax * height / width))\n if height2 < ymax:\n width2 = int(round(ymax * width / height))\n height2 = ymax\n return width2, height2\n thumblist = [os.path.basename(item.thumb) for item in items]\n widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size\n , thumblist)\n thumbnum = widthnum * heightnum\n img = Image.new('RGB', size, SUBDIR_BACKCOL)\n for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]):\n row = ind // widthnum\n col = ind % widthnum\n img2 = Image.open(os.path.join(thumbdir, thumb))\n w, h = size_thumbnail(*img2.size, width[col], height[row])\n cropdim = (w - width[col]) // 2, (h - height[row]) // 2, (w - width\n [col]) // 2 + width[col], (h - height[row]) // 2 + height[row]\n img2 = img2.resize((w, h), Image.LANCZOS)\n img2 = img2.crop(cropdim)\n img.paste(img2, (offsetx[col], offsety[row]))\n if os.path.exists(thumb_name):\n imgref = Image.open(thumb_name)\n byteio = io.BytesIO()\n img.save(byteio, 'JPEG')\n byteio.seek(0)\n imgnew = Image.open(byteio)\n diff = ImageChops.difference(imgnew, imgref)\n if diff.getbbox() is None:\n return\n img.save(thumb_name)\n\n\n<mask token>\n\n\ndef list_of_htmlfiles_in_items(itemlist):\n htmlist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n htmlist.append(item.htmname)\n htmlist.extend(list_of_htmlfiles_in_items(item.sublist))\n return htmlist\n\n\ndef list_of_thumbnails(posts, diary=False):\n thumblist = list()\n for post in posts:\n thumblist.extend(list_of_thumbnails_in_items(post.medias))\n if diary is False:\n thumblist.extend(list_of_thumbnails_in_items(post.dcim))\n return thumblist\n\n\ndef list_of_thumbnails_in_items(itemlist):\n thumblist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n thumblist.append(os.path.basename(item.thumb))\n thumblist.extend(list_of_thumbnails_in_items(item.sublist))\n else:\n thumblist.append(os.path.basename(item.thumb))\n return thumblist\n\n\ndef purge_htmlfiles(args, posts):\n \"\"\"\n Purge root dir from irrelevant html files\n \"\"\"\n htmlist = list_of_htmlfiles(args, posts)\n html_to_remove = list()\n for fullname in glob.glob(os.path.join(args.root, '*.htm*')):\n if fullname not in htmlist:\n html_to_remove.append(fullname)\n if len(html_to_remove) > args.thumbnails.threshold_htmlfiles:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(\n f'{len(html_to_remove)} html files to remove. Continue [y|n]? '\n ).lower()\n if inpt == 'n':\n return\n for name in html_to_remove:\n print('Removing html files', name)\n os.remove(name)\n\n\ndef purge_thumbnails(args, thumbdir, posts, diary=False):\n \"\"\"\n Purge thumbnail dir from irrelevant thumbnails\n \"\"\"\n thumblist = list_of_thumbnails(posts, diary)\n thumbs_to_remove = list()\n for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')):\n if os.path.basename(fullname) not in thumblist:\n thumbs_to_remove.append(fullname)\n if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(\n f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? '\n ).lower()\n if inpt == 'n':\n return\n for name in thumbs_to_remove:\n print('Removing thumbnail', name)\n os.remove(name)\n info_fullname = os.path.splitext(name)[0] + '.info'\n if os.path.exists(info_fullname):\n os.remove(info_fullname)\n\n\ndef is_media_within_dates(fullname, dates):\n if is_media(fullname):\n if type(dates) == tuple:\n return dates[0] <= date_from_item(fullname) <= dates[1]\n else:\n return True\n else:\n return False\n\n\ndef sorted_listdir(filelist):\n like_windows_explorer = True\n if not filelist:\n return filelist\n if like_windows_explorer:\n maxlen = max(len(os.path.splitext(name)[0]) for name in filelist)\n\n def keyfunc(name):\n root, ext = os.path.splitext(name.lower())\n return root.ljust(maxlen, ' ') + ext\n else:\n keyfunc = str.lower\n return sorted(filelist, key=keyfunc)\n\n\n<mask token>\n\n\ndef list_of_medias(args, sourcedir, recursive):\n \"\"\"\n Return the list of full paths for pictures and movies in source directory\n \"\"\"\n files = list_of_files(sourcedir, recursive)\n return [_ for _ in files if is_media_within_dates(_, args.dates)]\n\n\n<mask token>\n\n\ndef dispatch_post_items(list_of_post_items):\n subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir]\n medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir]\n return subdirs, medias\n\n\ndef create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax):\n if os.path.isfile(media_fullname):\n if is_image_file(media_fullname):\n return create_item_image(args, media_fullname, sourcedir,\n thumbdir, key, thumbmax)\n else:\n return create_item_video(args, media_fullname, sourcedir,\n thumbdir, key, thumbmax)\n else:\n return create_item_subdir(args, media_fullname, sourcedir, thumbdir,\n key, thumbmax)\n\n\ndef create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax\n ):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n try:\n info, infofmt = get_image_info(media_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize)\n return PostImage(None, media_fullname, '/'.join((args.thumbrep,\n thumb_basename)), thumbsize, infofmt)\n except PIL.UnidentifiedImageError:\n warning('Unable to read image', media_fullname)\n return None\n\n\ndef create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax\n ):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n info_fullname = os.path.splitext(thumb_fullname)[0] + '.info'\n try:\n info, infofmt = get_video_info(media_fullname, info_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_video(args, media_fullname, thumb_fullname,\n thumbsize, duration=info[5])\n return PostVideo(None, media_fullname, '/'.join((args.thumbrep,\n thumb_basename)), thumbsize, infofmt)\n except CalledProcessError:\n warning('Unable to read video', media_fullname)\n return None\n\n\n<mask token>\n\n\ndef relative_name(media_fullname, sourcedir):\n \"\"\"\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg\n -->\n deeper2_deepest_OCT_20000112_000004.jpg\n\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest\n -->\n deeper2_deepest\n \"\"\"\n x = os.path.relpath(media_fullname, sourcedir)\n x = x.replace('\\\\', '_').replace('/', '_').replace('#', '_')\n return x\n\n\n<mask token>\n\n\ndef make_posts_from_diary(args):\n md_filename = os.path.join(args.root, 'index.md')\n if os.path.exists(md_filename):\n title, posts = parse_markdown(md_filename)\n else:\n error('File not found', md_filename)\n for post in posts:\n for media in post.medias:\n media_fullname = os.path.join(args.root, media.uri)\n item = create_item(args, media_fullname, args.root, args.\n thumbdir, 'post', 400)\n media.thumb = item.thumb\n media.thumbsize = item.thumbsize\n media.descr = item.descr\n return title, posts\n\n\n<mask token>\n\n\ndef make_posts_from_subdir(args, dirname):\n if args.bydir is False:\n medias_ext = list_of_medias(args, dirname, args.recursive)\n else:\n medias_ext = list_of_medias_ext(args, dirname)\n postmedias = list()\n for item in medias_ext:\n postmedia = create_item(args, item, args.sourcedir, args.thumbdir,\n 'dcim', 300)\n if postmedia is not None:\n postmedias.append(postmedia)\n post = Post(date='00000000', text='', medias=[])\n post.dcim = postmedias\n posts = [post]\n title = os.path.basename(args.sourcedir) or os.path.splitdrive(args.\n sourcedir)[0]\n return title, posts\n\n\n<mask token>\n\n\ndef create_gallery(args):\n title, posts = make_posts(args, args.sourcedir)\n print_html(args, posts, title, os.path.join(args.dest, args.rootname),\n 'regular')\n purge_htmlfiles(args, posts)\n if args.diary and not args.sourcedir:\n purge_thumbnails(args, args.thumbdir, posts, diary=True)\n else:\n purge_thumbnails(args, args.thumbdir, posts)\n\n\ndef create_diary(args):\n medias = list_of_medias(args, args.sourcedir, args.recursive)\n if args.dates == 'diary':\n assert 0\n else:\n required_dates = {date_from_item(media) for media in medias}\n if type(args.dates) == tuple:\n date1, date2 = args.dates\n required_dates = {date for date in required_dates if date1 <=\n date <= date2}\n title = args.sourcedir\n posts = list()\n for date in sorted(required_dates):\n posts.append(Post.from_date(date))\n os.makedirs(args.root, exist_ok=True)\n print_markdown(posts, title, os.path.join(args.root, 'index.md'))\n\n\n<mask token>\n\n\ndef compare_image_buffers(imgbuf1, imgbuf2):\n \"\"\"\n return True if images read on file are identical, False otherwise\n \"\"\"\n with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2:\n img1 = Image.open(imgio1)\n img2 = Image.open(imgio2)\n diff = ImageChops.difference(img1, img2)\n return not diff.getbbox()\n\n\ndef check_images(args, posts, online_images):\n result = True\n for post in posts:\n for media in post.medias:\n if type(media) is PostImage:\n if media.basename in online_images:\n with open(os.path.join(args.root, media.uri), 'rb') as f:\n imgbuf1 = f.read()\n try:\n with urlopen(online_images[media.basename][0]) as u:\n imgbuf2 = u.read()\n except FileNotFoundError:\n print('File not found', online_images[media.\n basename][0])\n next\n if compare_image_buffers(imgbuf1, imgbuf2) is False:\n print('Files are different, upload', media.basename)\n elif 1:\n print('File already online', media.basename)\n else:\n print('File is absent, upload', media.basename)\n result = False\n elif type(media) is PostVideo:\n print('Video not checked', media.basename)\n else:\n assert False\n return result\n\n\n<mask token>\n\n\ndef idempotence(args):\n \"\"\"\n For testing identity between a diary file and the fle obtained after reading\n and printing it. See testing.\n \"\"\"\n title, posts = parse_markdown(os.path.join(args.root, 'index.md'))\n print_markdown(posts, title, os.path.join(args.dest, 'index.md'))\n\n\n<mask token>\n\n\nclass MyConfigParser(ConfigParser):\n \"\"\"Add input checking.\"\"\"\n\n def __init__(self):\n ConfigParser.__init__(self, inline_comment_prefixes=(';',))\n\n def error(self, section, entry):\n error('Missing or incorrect config value:', '[%s]%s' % (section, entry)\n )\n\n def getint(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getint(self, section, entry)\n else:\n return ConfigParser.getint(self, section, entry, raw=True,\n vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n def getboolean(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getboolean(self, section, entry)\n else:\n return ConfigParser.getboolean(self, section, entry, raw=\n True, vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n\ndef configfilename(params):\n return os.path.join(params.root, '.config.ini')\n\n\ndef createconfig(config_filename):\n with open(config_filename, 'wt') as f:\n f.writelines(CONFIG_DEFAULTS)\n\n\ndef read_config(params):\n config_filename = configfilename(params)\n try:\n if not os.path.exists(config_filename) or params.resetcfg:\n createconfig(config_filename)\n except:\n error('Error creating configuration file')\n try:\n getconfig(params, config_filename)\n except Exception as e:\n error('Error reading configuration file.', str(e), 'Use --resetcfg')\n\n\n<mask token>\n\n\ndef setconfig_cmd(args):\n config_filename = configfilename(args)\n setconfig(config_filename, *args.setcfg)\n\n\ndef update_config(args):\n updates = ('sourcedir', args.sourcedir), ('bydir', BOOL[args.bydir]), (\n 'bydate', BOOL[args.bydate]), ('diary', BOOL[args.diary]), ('recursive'\n , BOOL[args.recursive]), ('dates', args.dates), ('github_pages',\n BOOL[args.github_pages])\n cfgname = configfilename(args)\n with open(cfgname) as f:\n cfglines = [_.strip() for _ in f.readlines()]\n for key, value in updates:\n for iline, line in enumerate(cfglines):\n if line.startswith(key):\n cfglines[iline] = f'{key} = {value}'\n break\n with open(cfgname, 'wt') as f:\n for line in cfglines:\n print(line, file=f)\n\n\ndef warning(*msg):\n print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + ' '.join(msg),\n colorama.Style.RESET_ALL)\n\n\n<mask token>\n\n\ndef errorcode(msg):\n return ERRORS.splitlines().index(msg) + 1\n\n\ndef error(*msg):\n print(colorama.Fore.RED + colorama.Style.BRIGHT + ' '.join(msg),\n colorama.Style.RESET_ALL)\n sys.exit(errorcode(msg[0]))\n\n\n<mask token>\n\n\ndef setup_part1(args):\n \"\"\"\n Made before reading config file (config file located in args.root).\n Check and normalize root path.\n \"\"\"\n args.rootarg = args.root\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext == '':\n pass\n else:\n args.root = os.path.dirname(args.root)\n if args.root:\n args.root = os.path.abspath(args.root)\n if not os.path.isdir(args.root):\n if args.gallery:\n os.mkdir(args.root)\n else:\n error('Directory not found', args.root)\n\n\ndef setup_part2(args):\n \"\"\"\n Made after reading config file.\n Check for ffmpeg in path.\n Create .thumbnails dir if necessary and create .nomedia in it.\n Copy photobox file to destination dir.\n Handle priority between command line and config file.\n \"\"\"\n if args.update:\n args.sourcedir = args.source.sourcedir\n args.bydir = args.source.bydir\n args.bydate = args.source.bydate\n args.diary = args.source.diary\n args.recursive = args.source.recursive\n args.dates = args.source.dates\n args.github_pages = args.source.github_pages\n elif args.gallery:\n args.source.sourcedir = args.sourcedir\n args.source.bydir = args.bydir\n args.source.bydate = args.bydate\n args.source.diary = args.diary\n args.source.recursive = args.recursive\n args.source.dates = args.dates\n args.source.github_pages = args.github_pages\n update_config(args)\n if args.github_pages:\n args.html_suffix = '.html'\n else:\n args.html_suffix = '.htm'\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext:\n args.rootname = os.path.basename(args.rootarg)\n else:\n args.rootname = 'index' + args.html_suffix\n if args.sourcedir:\n args.sourcedir = os.path.abspath(args.sourcedir)\n if os.path.splitdrive(args.sourcedir)[0]:\n drive, rest = os.path.splitdrive(args.sourcedir)\n args.sourcedir = drive.upper() + rest\n if not os.path.isdir(args.sourcedir):\n error('Directory not found', args.sourcedir)\n elif args.gallery and args.diary is False and args.update is None:\n error('Directory not found', 'Use --sourcedir')\n if args.dest:\n args.dest = os.path.abspath(args.dest)\n if args.dest is None:\n args.dest = args.root\n if args.blogger and args.urlblogger is None:\n error('No blogger url (--url)')\n if args.gallery or args.update:\n for exe in ('ffmpeg', 'ffprobe'):\n try:\n check_output([exe, '-version'])\n except FileNotFoundError:\n error('File not found', exe)\n if args.github_pages:\n args.thumbrep = 'thumbnails'\n else:\n args.thumbrep = '.thumbnails'\n args.thumbdir = os.path.join(args.dest, args.thumbrep)\n if not os.path.exists(args.thumbdir):\n os.mkdir(args.thumbdir)\n open(os.path.join(args.thumbdir, '.nomedia'), 'a').close()\n favicondst = os.path.join(args.dest, 'favicon.ico')\n if not os.path.isfile(favicondst):\n faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico')\n shutil.copyfile(faviconsrc, favicondst)\n photoboxdir = os.path.join(args.dest, 'photobox')\n if not os.path.exists(photoboxdir):\n photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox')\n shutil.copytree(photoboxsrc, photoboxdir)\n if args.dates:\n if not (args.gallery or args.create):\n pass\n if args.dates == 'source':\n pass\n elif args.dates == 'diary':\n if args.create:\n error('Incorrect date format', args.dates)\n elif re.match('\\\\d+-\\\\d+', args.dates):\n date1, date2 = args.dates.split('-')\n if validate_date(date1) and validate_date(date2):\n args.dates = date1, date2\n else:\n error('Incorrect date format', args.dates)\n else:\n error('Incorrect date format', args.dates)\n\n\ndef main(argstring=None):\n colorama.init()\n args = parse_command_line(argstring)\n setup_part1(args)\n read_config(args)\n setup_part2(args)\n try:\n if args.gallery or args.update:\n create_gallery(args)\n elif args.create:\n create_diary(args)\n elif args.blogger:\n prepare_for_blogger(args)\n elif args.idem:\n idempotence(args)\n elif args.setcfg:\n setconfig_cmd(args)\n except KeyboardInterrupt:\n warning('Interrupted by user.')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Post:\n\n def __init__(self, date, text, medias):\n self.date = date\n self.text = text\n self.medias = medias\n self.dcim = []\n self.daterank = 0\n self.extra = False\n\n def __lt__(self, other):\n return self.date < other.date\n\n @classmethod\n def from_markdown(cls, post):\n m = re.match('\\\\[(\\\\d\\\\d\\\\d\\\\d/\\\\d\\\\d/\\\\d\\\\d)\\\\]\\\\n*', post[0])\n if m:\n date = m.group(1).replace('/', '')\n if not validate_date(date):\n error('Incorrect date value:', date)\n del post[0]\n else:\n error('No date in post', ' '.join(post))\n while post and not post[0].strip():\n del post[0]\n text = ''\n while post and not re.match('!?\\\\[\\\\]', post[0]):\n text += post[0]\n del post[0]\n text = re.sub('\\\\n\\\\n$', '\\n', text)\n medias = list()\n while post and (match := re.match('!?\\\\[\\\\]\\\\((.*)\\\\)', post[0])):\n media = match.group(1)\n caption = None\n del post[0]\n if post and not re.match('!?\\\\[\\\\]', post[0]):\n caption = post[0].strip()\n del post[0]\n if match.group(0)[0] == '!':\n medias.append(PostImage(caption, media))\n else:\n medias.append(PostVideo(caption, media))\n return cls(date, text, medias)\n\n @classmethod\n def from_date(cls, date):\n dt = datetime.datetime.strptime(date, '%Y%m%d')\n datetext = dt.strftime('%A %d %B %Y').capitalize()\n post = cls(date, text=datetext, medias=[])\n post.daterank = 1\n return post\n\n def to_html(self, args, target='regular'):\n if target == 'regular':\n if args.diary:\n return self.to_html_diary(args)\n else:\n return self.to_html_regular(args)\n if target == 'blogger':\n return self.to_html_blogger()\n\n def to_html_regular(self, args):\n html = list()\n if self.text:\n html.append(markdown.markdown(self.text))\n subdirs, dcim = dispatch_post_items(self.dcim)\n if self.dcim:\n html.append(SEP)\n for media in subdirs:\n html.append(media.to_html_dcim(args))\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n html.append(SEP)\n return html\n\n def to_html_diary(self, args):\n html = list()\n if self.extra:\n html.append('<div class=\"extra\">')\n if self.text:\n html.append(markdown.markdown(self.text))\n if self.medias:\n html.append(f'<div id=\"gallery-blog-{self.date}-{self.daterank}\">')\n for media in self.medias:\n html.append(media.to_html_post(args))\n html.append('</div>')\n _, dcim = dispatch_post_items(self.dcim)\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n html.append(SEP)\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n html.append(SEP)\n if self.extra:\n html.append('</div>')\n return html\n\n def to_html_blogger(self):\n html = list()\n html.append(markdown.markdown(self.text))\n for image in self.medias:\n html.append(image.to_html_blogger())\n html.append(SEP)\n return html\n\n\nclass PostItem:\n\n def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''):\n self.caption = caption\n self.uri = uri\n self.basename = os.path.basename(uri)\n self.thumb = thumb\n self.thumbsize = thumbsize\n self.descr = descr\n self.resized_url = None\n\n\nclass PostImage(PostItem):\n\n def to_markdown(self):\n if not self.caption:\n return '![](%s)' % (self.uri,)\n else:\n return '![](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize,\n descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, *\n self.thumbsize, descr)\n\n def to_html_blogger(self):\n if not self.caption:\n return BIMGPAT % (self.uri, self.resized_url)\n else:\n return f'{BIMGPAT}\\n{CAPTION_PAT}' % (self.uri, self.\n resized_url, self.caption)\n\n\nclass PostVideo(PostItem):\n\n def to_markdown(self):\n if not self.caption:\n return '[](%s)' % (self.uri,)\n else:\n return '[](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize,\n descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, *\n self.thumbsize, descr)\n\n def to_html_blogger(self):\n x = f'<p style=\"text-align: center;\">{self.iframe}</p>'\n if not self.caption:\n return x\n else:\n return f'%s\\n{CAPTION_PAT}' % (x, self.caption)\n\n\nclass PostSubdir(PostItem):\n\n def to_html_dcim(self, args):\n basename = os.path.basename(self.htmname)\n posts = self.posts\n title = self.caption\n print_html(args, posts, title, self.htmname)\n if not self.caption:\n return DIRPOST % (basename, self.thumb, *self.thumbsize)\n else:\n return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize,\n self.caption)\n\n\n<mask token>\n\n\ndef parse_markdown(filename):\n \"\"\"\n Generate Post objects from markdown. Date must be present in each post and\n posts must be ordrered by date.\n \"\"\"\n if not os.path.exists(filename):\n error('File not found', filename)\n posts = list()\n with open(filename, encoding='utf-8') as f:\n line = next(f)\n if line.startswith('# '):\n title = line[2:].strip()\n record = []\n next(f)\n else:\n title = None\n record = [line]\n for line in f:\n if not line.startswith('___'):\n record.append(line)\n else:\n posts.append(Post.from_markdown(record))\n record = []\n daterank = defaultdict(int)\n for post in posts:\n daterank[post.date] += 1\n post.daterank = daterank[post.date]\n for post1, post2 in zip(posts[:-1], posts[1:]):\n if post1.date > post2.date:\n error('Posts are not ordered', f'{post1.date} > {post2.date}')\n return title, posts\n\n\ndef print_markdown(posts, title, fullname):\n with open(fullname, 'wt', encoding='utf-8') as fdst:\n print(f'# {title}\\n', file=fdst)\n for post in posts:\n date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]'\n print(date, file=fdst)\n if post.text:\n print(file=fdst)\n for line in post.text.splitlines():\n if not line:\n print(file=fdst)\n else:\n for chunk in textwrap.wrap(line, width=78):\n print(chunk, file=fdst)\n if post.medias:\n print(file=fdst)\n for media in post.medias:\n print(media.to_markdown(), file=fdst)\n print('______', file=fdst)\n\n\n<mask token>\n\n\ndef print_html(args, posts, title, html_name, target='regular'):\n assert target in ('regular', 'blogger')\n with io.StringIO() as f:\n print_html_to_stream(args, posts, title, f, target)\n html = f.getvalue()\n if html_name:\n if os.path.exists(html_name):\n with open(html_name, 'rt', encoding='utf-8') as f:\n html0 = f.read()\n if html == html0:\n return None\n with open(html_name, 'wt', encoding='utf-8') as f:\n f.write(html)\n return None\n else:\n return html\n\n\n<mask token>\n\n\ndef is_image_file(name):\n return os.path.splitext(name)[1].lower() in ('.jpg', '.jpeg', '.png',\n '.gif', '.bmp', '.webp', '.tif')\n\n\n<mask token>\n\n\ndef is_media(name):\n return is_image_file(name) or is_video_file(name)\n\n\n<mask token>\n\n\ndef date_from_name(name):\n if (match := re.search('(?:\\\\D|^)(\\\\d{8})(?:\\\\D|$)', name, re.ASCII)):\n digits = match.group(1)\n if validate_date(digits):\n return digits\n return None\n\n\ndef date_from_item(filename):\n if (date := date_from_name(filename)):\n return date\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d')\n\n\ndef time_from_name(name):\n if (match := re.search('(?:\\\\D|^)(\\\\d{8})\\\\D(\\\\d{6})(?:\\\\D|$)', name,\n re.ASCII)):\n digits = match.group(2)\n hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits\n [4:6])\n if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60:\n return digits\n return None\n\n\ndef time_from_item(filename):\n if (time := time_from_name(filename)):\n return time\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S')\n\n\n<mask token>\n\n\ndef get_image_info(filename):\n date = date_from_item(filename)\n time = time_from_item(filename)\n img = Image.open(filename)\n width, height = img.size\n size = round(os.path.getsize(filename) / 1000000.0, 1)\n return (date, time, width, height, size\n ), f'{date} {time}, dim={width}x{height}, {size} MB'\n\n\ndef get_video_info(filename, info_fullname):\n if os.path.exists(info_fullname):\n with open(info_fullname) as f:\n info = f.readline().split()\n date, time, width, height, size, duration, fps = info[0], info[1], int(\n info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6]\n )\n formatted_info = format_video_info(date, time, width, height, size,\n duration, fps)\n return (date, time, width, height, size, duration, fps), formatted_info\n else:\n info, formatted_info = make_video_info(filename, info_fullname)\n with open(info_fullname, 'wt') as f:\n print(' '.join([str(_) for _ in info]), file=f)\n return info, formatted_info\n\n\ndef make_video_info(filename, info_fullname):\n date = date_from_item(filename)\n time = time_from_item(filename)\n command = [*FFPROBE_CMD.split(), filename]\n try:\n output = check_output(command, stderr=STDOUT).decode()\n width, height, fps, duration = parse_ffprobe_output(output)\n size = round(os.path.getsize(filename) / 1000000.0, 1)\n output = format_video_info(date, time, width, height, size,\n duration, fps)\n except CalledProcessError as e:\n output = e.output.decode()\n warning(output)\n raise\n return (date, time, width, height, size, duration, fps), output\n\n\ndef parse_ffprobe_output(ffprobe_output):\n match = re.match(\n '(\\\\d+),(\\\\d+),(\\\\d+)/(\\\\d+),(\\\\d+/\\\\d+).*\\\\s(\\\\d+\\\\.\\\\d+)',\n ffprobe_output, re.DOTALL)\n width = int(match.group(1))\n height = int(match.group(2))\n fps = round(int(match.group(3)) / int(match.group(4)), 1)\n duration = round(float(match.group(6)))\n return width, height, fps, duration\n\n\ndef format_video_info(date, time, width, height, size, duration, fps):\n return (\n f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB'\n )\n\n\n<mask token>\n\n\ndef thumbname(name, key):\n return key + '-' + name + '.jpg'\n\n\ndef size_thumbnail(width, height, maxdim):\n if width >= height:\n return maxdim, int(round(maxdim * height / width))\n else:\n return int(round(maxdim * width / height)), maxdim\n\n\ndef make_thumbnail_image(args, image_name, thumb_name, size):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_image(image_name, thumb_name, size)\n\n\ndef create_thumbnail_image(image_name, thumb_name, size):\n imgobj = Image.open(image_name)\n if imgobj.mode != 'RGBA' and image_name.endswith('.jpg') and not (\n image_name.endswith('.gif') and imgobj.info.get('transparency')):\n imgobj = imgobj.convert('RGBA')\n imgobj.thumbnail(size, Image.LANCZOS)\n imgobj = imgobj.convert('RGB')\n imgobj.save(thumb_name)\n\n\ndef make_thumbnail_video(args, video_name, thumb_name, size, duration):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_video(args, video_name, thumb_name, size, duration)\n\n\n<mask token>\n\n\ndef create_thumbnail_video(args, filename, thumbname, size, duration):\n delay = min(duration - 1, args.thumbnails.thumbdelay)\n sizearg = '%dx%d' % size\n command = (\n 'ffmpeg -y -v error -itsoffset -%d -i \"%s\" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s \"%s\"'\n )\n command = command % (delay, filename, sizearg, thumbname)\n result = os.system(command)\n try:\n img1 = Image.open(thumbname)\n except:\n warning('Unable to save thumbnail for', filename)\n return\n img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON)))\n width, height = img1.size\n img1.paste(img2, (6, height - 20 - 6), None)\n img1.save(thumbname)\n\n\n<mask token>\n\n\ndef create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir):\n\n def size_thumbnail(width, height, xmax, ymax):\n width2 = xmax\n height2 = int(round(xmax * height / width))\n if height2 < ymax:\n width2 = int(round(ymax * width / height))\n height2 = ymax\n return width2, height2\n thumblist = [os.path.basename(item.thumb) for item in items]\n widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size\n , thumblist)\n thumbnum = widthnum * heightnum\n img = Image.new('RGB', size, SUBDIR_BACKCOL)\n for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]):\n row = ind // widthnum\n col = ind % widthnum\n img2 = Image.open(os.path.join(thumbdir, thumb))\n w, h = size_thumbnail(*img2.size, width[col], height[row])\n cropdim = (w - width[col]) // 2, (h - height[row]) // 2, (w - width\n [col]) // 2 + width[col], (h - height[row]) // 2 + height[row]\n img2 = img2.resize((w, h), Image.LANCZOS)\n img2 = img2.crop(cropdim)\n img.paste(img2, (offsetx[col], offsety[row]))\n if os.path.exists(thumb_name):\n imgref = Image.open(thumb_name)\n byteio = io.BytesIO()\n img.save(byteio, 'JPEG')\n byteio.seek(0)\n imgnew = Image.open(byteio)\n diff = ImageChops.difference(imgnew, imgref)\n if diff.getbbox() is None:\n return\n img.save(thumb_name)\n\n\ndef mosaic_geometry(size, thumblist):\n if len(thumblist) == 1:\n widthnum = 1\n heightnum = 1\n elif len(thumblist) <= 3:\n widthnum = 1\n heightnum = 2\n elif len(thumblist) <= 8:\n widthnum = 2\n heightnum = 2\n else:\n widthnum = 3\n heightnum = 3\n if widthnum == 1:\n width = [size[0] - 2]\n else:\n width = [size[0] // widthnum - 2] * (widthnum - 1)\n width.append(size[0] - (1 + sum(width) + 2 * len(width) + 1))\n if heightnum == 1:\n height = [size[1] - 2]\n else:\n height = [size[1] // heightnum - 2] * (heightnum - 1)\n height.append(size[1] - (1 + sum(height) + 2 * len(height) + 1))\n offsetx = [1]\n for w in width[:-1]:\n offsetx.append(offsetx[-1] + w + 2)\n offsety = [1]\n for h in height[:-1]:\n offsety.append(offsety[-1] + h + 2)\n return widthnum, heightnum, width, height, offsetx, offsety\n\n\n<mask token>\n\n\ndef list_of_htmlfiles_in_items(itemlist):\n htmlist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n htmlist.append(item.htmname)\n htmlist.extend(list_of_htmlfiles_in_items(item.sublist))\n return htmlist\n\n\ndef list_of_thumbnails(posts, diary=False):\n thumblist = list()\n for post in posts:\n thumblist.extend(list_of_thumbnails_in_items(post.medias))\n if diary is False:\n thumblist.extend(list_of_thumbnails_in_items(post.dcim))\n return thumblist\n\n\ndef list_of_thumbnails_in_items(itemlist):\n thumblist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n thumblist.append(os.path.basename(item.thumb))\n thumblist.extend(list_of_thumbnails_in_items(item.sublist))\n else:\n thumblist.append(os.path.basename(item.thumb))\n return thumblist\n\n\ndef purge_htmlfiles(args, posts):\n \"\"\"\n Purge root dir from irrelevant html files\n \"\"\"\n htmlist = list_of_htmlfiles(args, posts)\n html_to_remove = list()\n for fullname in glob.glob(os.path.join(args.root, '*.htm*')):\n if fullname not in htmlist:\n html_to_remove.append(fullname)\n if len(html_to_remove) > args.thumbnails.threshold_htmlfiles:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(\n f'{len(html_to_remove)} html files to remove. Continue [y|n]? '\n ).lower()\n if inpt == 'n':\n return\n for name in html_to_remove:\n print('Removing html files', name)\n os.remove(name)\n\n\ndef purge_thumbnails(args, thumbdir, posts, diary=False):\n \"\"\"\n Purge thumbnail dir from irrelevant thumbnails\n \"\"\"\n thumblist = list_of_thumbnails(posts, diary)\n thumbs_to_remove = list()\n for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')):\n if os.path.basename(fullname) not in thumblist:\n thumbs_to_remove.append(fullname)\n if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(\n f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? '\n ).lower()\n if inpt == 'n':\n return\n for name in thumbs_to_remove:\n print('Removing thumbnail', name)\n os.remove(name)\n info_fullname = os.path.splitext(name)[0] + '.info'\n if os.path.exists(info_fullname):\n os.remove(info_fullname)\n\n\ndef is_media_within_dates(fullname, dates):\n if is_media(fullname):\n if type(dates) == tuple:\n return dates[0] <= date_from_item(fullname) <= dates[1]\n else:\n return True\n else:\n return False\n\n\ndef sorted_listdir(filelist):\n like_windows_explorer = True\n if not filelist:\n return filelist\n if like_windows_explorer:\n maxlen = max(len(os.path.splitext(name)[0]) for name in filelist)\n\n def keyfunc(name):\n root, ext = os.path.splitext(name.lower())\n return root.ljust(maxlen, ' ') + ext\n else:\n keyfunc = str.lower\n return sorted(filelist, key=keyfunc)\n\n\n<mask token>\n\n\ndef list_of_medias(args, sourcedir, recursive):\n \"\"\"\n Return the list of full paths for pictures and movies in source directory\n \"\"\"\n files = list_of_files(sourcedir, recursive)\n return [_ for _ in files if is_media_within_dates(_, args.dates)]\n\n\n<mask token>\n\n\ndef dispatch_post_items(list_of_post_items):\n subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir]\n medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir]\n return subdirs, medias\n\n\ndef create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax):\n if os.path.isfile(media_fullname):\n if is_image_file(media_fullname):\n return create_item_image(args, media_fullname, sourcedir,\n thumbdir, key, thumbmax)\n else:\n return create_item_video(args, media_fullname, sourcedir,\n thumbdir, key, thumbmax)\n else:\n return create_item_subdir(args, media_fullname, sourcedir, thumbdir,\n key, thumbmax)\n\n\ndef create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax\n ):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n try:\n info, infofmt = get_image_info(media_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize)\n return PostImage(None, media_fullname, '/'.join((args.thumbrep,\n thumb_basename)), thumbsize, infofmt)\n except PIL.UnidentifiedImageError:\n warning('Unable to read image', media_fullname)\n return None\n\n\ndef create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax\n ):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n info_fullname = os.path.splitext(thumb_fullname)[0] + '.info'\n try:\n info, infofmt = get_video_info(media_fullname, info_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_video(args, media_fullname, thumb_fullname,\n thumbsize, duration=info[5])\n return PostVideo(None, media_fullname, '/'.join((args.thumbrep,\n thumb_basename)), thumbsize, infofmt)\n except CalledProcessError:\n warning('Unable to read video', media_fullname)\n return None\n\n\n<mask token>\n\n\ndef relative_name(media_fullname, sourcedir):\n \"\"\"\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg\n -->\n deeper2_deepest_OCT_20000112_000004.jpg\n\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest\n -->\n deeper2_deepest\n \"\"\"\n x = os.path.relpath(media_fullname, sourcedir)\n x = x.replace('\\\\', '_').replace('/', '_').replace('#', '_')\n return x\n\n\n<mask token>\n\n\ndef make_posts_from_diary(args):\n md_filename = os.path.join(args.root, 'index.md')\n if os.path.exists(md_filename):\n title, posts = parse_markdown(md_filename)\n else:\n error('File not found', md_filename)\n for post in posts:\n for media in post.medias:\n media_fullname = os.path.join(args.root, media.uri)\n item = create_item(args, media_fullname, args.root, args.\n thumbdir, 'post', 400)\n media.thumb = item.thumb\n media.thumbsize = item.thumbsize\n media.descr = item.descr\n return title, posts\n\n\n<mask token>\n\n\ndef make_posts_from_subdir(args, dirname):\n if args.bydir is False:\n medias_ext = list_of_medias(args, dirname, args.recursive)\n else:\n medias_ext = list_of_medias_ext(args, dirname)\n postmedias = list()\n for item in medias_ext:\n postmedia = create_item(args, item, args.sourcedir, args.thumbdir,\n 'dcim', 300)\n if postmedia is not None:\n postmedias.append(postmedia)\n post = Post(date='00000000', text='', medias=[])\n post.dcim = postmedias\n posts = [post]\n title = os.path.basename(args.sourcedir) or os.path.splitdrive(args.\n sourcedir)[0]\n return title, posts\n\n\n<mask token>\n\n\ndef create_gallery(args):\n title, posts = make_posts(args, args.sourcedir)\n print_html(args, posts, title, os.path.join(args.dest, args.rootname),\n 'regular')\n purge_htmlfiles(args, posts)\n if args.diary and not args.sourcedir:\n purge_thumbnails(args, args.thumbdir, posts, diary=True)\n else:\n purge_thumbnails(args, args.thumbdir, posts)\n\n\ndef create_diary(args):\n medias = list_of_medias(args, args.sourcedir, args.recursive)\n if args.dates == 'diary':\n assert 0\n else:\n required_dates = {date_from_item(media) for media in medias}\n if type(args.dates) == tuple:\n date1, date2 = args.dates\n required_dates = {date for date in required_dates if date1 <=\n date <= date2}\n title = args.sourcedir\n posts = list()\n for date in sorted(required_dates):\n posts.append(Post.from_date(date))\n os.makedirs(args.root, exist_ok=True)\n print_markdown(posts, title, os.path.join(args.root, 'index.md'))\n\n\n<mask token>\n\n\ndef compare_image_buffers(imgbuf1, imgbuf2):\n \"\"\"\n return True if images read on file are identical, False otherwise\n \"\"\"\n with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2:\n img1 = Image.open(imgio1)\n img2 = Image.open(imgio2)\n diff = ImageChops.difference(img1, img2)\n return not diff.getbbox()\n\n\ndef check_images(args, posts, online_images):\n result = True\n for post in posts:\n for media in post.medias:\n if type(media) is PostImage:\n if media.basename in online_images:\n with open(os.path.join(args.root, media.uri), 'rb') as f:\n imgbuf1 = f.read()\n try:\n with urlopen(online_images[media.basename][0]) as u:\n imgbuf2 = u.read()\n except FileNotFoundError:\n print('File not found', online_images[media.\n basename][0])\n next\n if compare_image_buffers(imgbuf1, imgbuf2) is False:\n print('Files are different, upload', media.basename)\n elif 1:\n print('File already online', media.basename)\n else:\n print('File is absent, upload', media.basename)\n result = False\n elif type(media) is PostVideo:\n print('Video not checked', media.basename)\n else:\n assert False\n return result\n\n\ndef compose_blogger_html(args, title, posts, imgdata, online_videos):\n \"\"\" Compose html with blogger image urls\n \"\"\"\n for post in posts:\n for media in post.medias:\n if type(media) is PostImage:\n if media.uri not in imgdata:\n print('Image missing: ', media.uri)\n else:\n img_url, resized_url = imgdata[media.uri]\n media.uri = img_url\n media.resized_url = resized_url\n elif type(media) is PostVideo:\n if not online_videos:\n print('Video missing: ', media.uri)\n else:\n media.iframe = online_videos[0]\n del online_videos[0]\n else:\n assert False\n return print_html(args, posts, title, '', target='blogger')\n\n\ndef prepare_for_blogger(args):\n \"\"\"\n Export blogger html to clipboard.\n If --full, export complete html, otherwise export html extract ready to\n paste into blogger edit mode.\n \"\"\"\n title, posts = parse_markdown(os.path.join(args.root, 'index.md'))\n online_images, online_videos = online_images_url(args)\n if args.check_images and check_images(args, posts, online_images) is False:\n pass\n html = compose_blogger_html(args, title, posts, online_images,\n online_videos)\n if args.full is False:\n html = re.search('<body>(.*)?</body>', html, flags=re.DOTALL).group(1)\n html = re.sub('<script>.*?</script>', '', html, flags=re.DOTALL)\n html = STYLE.replace('%%', '%') + html\n if args.dest:\n with open(args.dest, 'wt', encoding='utf-8') as f:\n f.write(html)\n else:\n clipboard.copy(html)\n\n\ndef idempotence(args):\n \"\"\"\n For testing identity between a diary file and the fle obtained after reading\n and printing it. See testing.\n \"\"\"\n title, posts = parse_markdown(os.path.join(args.root, 'index.md'))\n print_markdown(posts, title, os.path.join(args.dest, 'index.md'))\n\n\n<mask token>\n\n\nclass MyConfigParser(ConfigParser):\n \"\"\"Add input checking.\"\"\"\n\n def __init__(self):\n ConfigParser.__init__(self, inline_comment_prefixes=(';',))\n\n def error(self, section, entry):\n error('Missing or incorrect config value:', '[%s]%s' % (section, entry)\n )\n\n def getint(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getint(self, section, entry)\n else:\n return ConfigParser.getint(self, section, entry, raw=True,\n vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n def getboolean(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getboolean(self, section, entry)\n else:\n return ConfigParser.getboolean(self, section, entry, raw=\n True, vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n\ndef configfilename(params):\n return os.path.join(params.root, '.config.ini')\n\n\ndef createconfig(config_filename):\n with open(config_filename, 'wt') as f:\n f.writelines(CONFIG_DEFAULTS)\n\n\ndef read_config(params):\n config_filename = configfilename(params)\n try:\n if not os.path.exists(config_filename) or params.resetcfg:\n createconfig(config_filename)\n except:\n error('Error creating configuration file')\n try:\n getconfig(params, config_filename)\n except Exception as e:\n error('Error reading configuration file.', str(e), 'Use --resetcfg')\n\n\n<mask token>\n\n\ndef setconfig_cmd(args):\n config_filename = configfilename(args)\n setconfig(config_filename, *args.setcfg)\n\n\ndef update_config(args):\n updates = ('sourcedir', args.sourcedir), ('bydir', BOOL[args.bydir]), (\n 'bydate', BOOL[args.bydate]), ('diary', BOOL[args.diary]), ('recursive'\n , BOOL[args.recursive]), ('dates', args.dates), ('github_pages',\n BOOL[args.github_pages])\n cfgname = configfilename(args)\n with open(cfgname) as f:\n cfglines = [_.strip() for _ in f.readlines()]\n for key, value in updates:\n for iline, line in enumerate(cfglines):\n if line.startswith(key):\n cfglines[iline] = f'{key} = {value}'\n break\n with open(cfgname, 'wt') as f:\n for line in cfglines:\n print(line, file=f)\n\n\ndef warning(*msg):\n print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + ' '.join(msg),\n colorama.Style.RESET_ALL)\n\n\n<mask token>\n\n\ndef errorcode(msg):\n return ERRORS.splitlines().index(msg) + 1\n\n\ndef error(*msg):\n print(colorama.Fore.RED + colorama.Style.BRIGHT + ' '.join(msg),\n colorama.Style.RESET_ALL)\n sys.exit(errorcode(msg[0]))\n\n\n<mask token>\n\n\ndef setup_part1(args):\n \"\"\"\n Made before reading config file (config file located in args.root).\n Check and normalize root path.\n \"\"\"\n args.rootarg = args.root\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext == '':\n pass\n else:\n args.root = os.path.dirname(args.root)\n if args.root:\n args.root = os.path.abspath(args.root)\n if not os.path.isdir(args.root):\n if args.gallery:\n os.mkdir(args.root)\n else:\n error('Directory not found', args.root)\n\n\ndef setup_part2(args):\n \"\"\"\n Made after reading config file.\n Check for ffmpeg in path.\n Create .thumbnails dir if necessary and create .nomedia in it.\n Copy photobox file to destination dir.\n Handle priority between command line and config file.\n \"\"\"\n if args.update:\n args.sourcedir = args.source.sourcedir\n args.bydir = args.source.bydir\n args.bydate = args.source.bydate\n args.diary = args.source.diary\n args.recursive = args.source.recursive\n args.dates = args.source.dates\n args.github_pages = args.source.github_pages\n elif args.gallery:\n args.source.sourcedir = args.sourcedir\n args.source.bydir = args.bydir\n args.source.bydate = args.bydate\n args.source.diary = args.diary\n args.source.recursive = args.recursive\n args.source.dates = args.dates\n args.source.github_pages = args.github_pages\n update_config(args)\n if args.github_pages:\n args.html_suffix = '.html'\n else:\n args.html_suffix = '.htm'\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext:\n args.rootname = os.path.basename(args.rootarg)\n else:\n args.rootname = 'index' + args.html_suffix\n if args.sourcedir:\n args.sourcedir = os.path.abspath(args.sourcedir)\n if os.path.splitdrive(args.sourcedir)[0]:\n drive, rest = os.path.splitdrive(args.sourcedir)\n args.sourcedir = drive.upper() + rest\n if not os.path.isdir(args.sourcedir):\n error('Directory not found', args.sourcedir)\n elif args.gallery and args.diary is False and args.update is None:\n error('Directory not found', 'Use --sourcedir')\n if args.dest:\n args.dest = os.path.abspath(args.dest)\n if args.dest is None:\n args.dest = args.root\n if args.blogger and args.urlblogger is None:\n error('No blogger url (--url)')\n if args.gallery or args.update:\n for exe in ('ffmpeg', 'ffprobe'):\n try:\n check_output([exe, '-version'])\n except FileNotFoundError:\n error('File not found', exe)\n if args.github_pages:\n args.thumbrep = 'thumbnails'\n else:\n args.thumbrep = '.thumbnails'\n args.thumbdir = os.path.join(args.dest, args.thumbrep)\n if not os.path.exists(args.thumbdir):\n os.mkdir(args.thumbdir)\n open(os.path.join(args.thumbdir, '.nomedia'), 'a').close()\n favicondst = os.path.join(args.dest, 'favicon.ico')\n if not os.path.isfile(favicondst):\n faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico')\n shutil.copyfile(faviconsrc, favicondst)\n photoboxdir = os.path.join(args.dest, 'photobox')\n if not os.path.exists(photoboxdir):\n photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox')\n shutil.copytree(photoboxsrc, photoboxdir)\n if args.dates:\n if not (args.gallery or args.create):\n pass\n if args.dates == 'source':\n pass\n elif args.dates == 'diary':\n if args.create:\n error('Incorrect date format', args.dates)\n elif re.match('\\\\d+-\\\\d+', args.dates):\n date1, date2 = args.dates.split('-')\n if validate_date(date1) and validate_date(date2):\n args.dates = date1, date2\n else:\n error('Incorrect date format', args.dates)\n else:\n error('Incorrect date format', args.dates)\n\n\ndef main(argstring=None):\n colorama.init()\n args = parse_command_line(argstring)\n setup_part1(args)\n read_config(args)\n setup_part2(args)\n try:\n if args.gallery or args.update:\n create_gallery(args)\n elif args.create:\n create_diary(args)\n elif args.blogger:\n prepare_for_blogger(args)\n elif args.idem:\n idempotence(args)\n elif args.setcfg:\n setconfig_cmd(args)\n except KeyboardInterrupt:\n warning('Interrupted by user.')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Post:\n\n def __init__(self, date, text, medias):\n self.date = date\n self.text = text\n self.medias = medias\n self.dcim = []\n self.daterank = 0\n self.extra = False\n\n def __lt__(self, other):\n return self.date < other.date\n\n @classmethod\n def from_markdown(cls, post):\n m = re.match('\\\\[(\\\\d\\\\d\\\\d\\\\d/\\\\d\\\\d/\\\\d\\\\d)\\\\]\\\\n*', post[0])\n if m:\n date = m.group(1).replace('/', '')\n if not validate_date(date):\n error('Incorrect date value:', date)\n del post[0]\n else:\n error('No date in post', ' '.join(post))\n while post and not post[0].strip():\n del post[0]\n text = ''\n while post and not re.match('!?\\\\[\\\\]', post[0]):\n text += post[0]\n del post[0]\n text = re.sub('\\\\n\\\\n$', '\\n', text)\n medias = list()\n while post and (match := re.match('!?\\\\[\\\\]\\\\((.*)\\\\)', post[0])):\n media = match.group(1)\n caption = None\n del post[0]\n if post and not re.match('!?\\\\[\\\\]', post[0]):\n caption = post[0].strip()\n del post[0]\n if match.group(0)[0] == '!':\n medias.append(PostImage(caption, media))\n else:\n medias.append(PostVideo(caption, media))\n return cls(date, text, medias)\n\n @classmethod\n def from_date(cls, date):\n dt = datetime.datetime.strptime(date, '%Y%m%d')\n datetext = dt.strftime('%A %d %B %Y').capitalize()\n post = cls(date, text=datetext, medias=[])\n post.daterank = 1\n return post\n\n def to_html(self, args, target='regular'):\n if target == 'regular':\n if args.diary:\n return self.to_html_diary(args)\n else:\n return self.to_html_regular(args)\n if target == 'blogger':\n return self.to_html_blogger()\n\n def to_html_regular(self, args):\n html = list()\n if self.text:\n html.append(markdown.markdown(self.text))\n subdirs, dcim = dispatch_post_items(self.dcim)\n if self.dcim:\n html.append(SEP)\n for media in subdirs:\n html.append(media.to_html_dcim(args))\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n html.append(SEP)\n return html\n\n def to_html_diary(self, args):\n html = list()\n if self.extra:\n html.append('<div class=\"extra\">')\n if self.text:\n html.append(markdown.markdown(self.text))\n if self.medias:\n html.append(f'<div id=\"gallery-blog-{self.date}-{self.daterank}\">')\n for media in self.medias:\n html.append(media.to_html_post(args))\n html.append('</div>')\n _, dcim = dispatch_post_items(self.dcim)\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n html.append(SEP)\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n html.append(SEP)\n if self.extra:\n html.append('</div>')\n return html\n\n def to_html_blogger(self):\n html = list()\n html.append(markdown.markdown(self.text))\n for image in self.medias:\n html.append(image.to_html_blogger())\n html.append(SEP)\n return html\n\n\nclass PostItem:\n\n def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''):\n self.caption = caption\n self.uri = uri\n self.basename = os.path.basename(uri)\n self.thumb = thumb\n self.thumbsize = thumbsize\n self.descr = descr\n self.resized_url = None\n\n\nclass PostImage(PostItem):\n\n def to_markdown(self):\n if not self.caption:\n return '![](%s)' % (self.uri,)\n else:\n return '![](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize,\n descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, *\n self.thumbsize, descr)\n\n def to_html_blogger(self):\n if not self.caption:\n return BIMGPAT % (self.uri, self.resized_url)\n else:\n return f'{BIMGPAT}\\n{CAPTION_PAT}' % (self.uri, self.\n resized_url, self.caption)\n\n\nclass PostVideo(PostItem):\n\n def to_markdown(self):\n if not self.caption:\n return '[](%s)' % (self.uri,)\n else:\n return '[](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize,\n descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, *\n self.thumbsize, descr)\n\n def to_html_blogger(self):\n x = f'<p style=\"text-align: center;\">{self.iframe}</p>'\n if not self.caption:\n return x\n else:\n return f'%s\\n{CAPTION_PAT}' % (x, self.caption)\n\n\nclass PostSubdir(PostItem):\n\n def to_html_dcim(self, args):\n basename = os.path.basename(self.htmname)\n posts = self.posts\n title = self.caption\n print_html(args, posts, title, self.htmname)\n if not self.caption:\n return DIRPOST % (basename, self.thumb, *self.thumbsize)\n else:\n return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize,\n self.caption)\n\n\n<mask token>\n\n\ndef parse_markdown(filename):\n \"\"\"\n Generate Post objects from markdown. Date must be present in each post and\n posts must be ordrered by date.\n \"\"\"\n if not os.path.exists(filename):\n error('File not found', filename)\n posts = list()\n with open(filename, encoding='utf-8') as f:\n line = next(f)\n if line.startswith('# '):\n title = line[2:].strip()\n record = []\n next(f)\n else:\n title = None\n record = [line]\n for line in f:\n if not line.startswith('___'):\n record.append(line)\n else:\n posts.append(Post.from_markdown(record))\n record = []\n daterank = defaultdict(int)\n for post in posts:\n daterank[post.date] += 1\n post.daterank = daterank[post.date]\n for post1, post2 in zip(posts[:-1], posts[1:]):\n if post1.date > post2.date:\n error('Posts are not ordered', f'{post1.date} > {post2.date}')\n return title, posts\n\n\ndef print_markdown(posts, title, fullname):\n with open(fullname, 'wt', encoding='utf-8') as fdst:\n print(f'# {title}\\n', file=fdst)\n for post in posts:\n date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]'\n print(date, file=fdst)\n if post.text:\n print(file=fdst)\n for line in post.text.splitlines():\n if not line:\n print(file=fdst)\n else:\n for chunk in textwrap.wrap(line, width=78):\n print(chunk, file=fdst)\n if post.medias:\n print(file=fdst)\n for media in post.medias:\n print(media.to_markdown(), file=fdst)\n print('______', file=fdst)\n\n\n<mask token>\n\n\ndef print_html(args, posts, title, html_name, target='regular'):\n assert target in ('regular', 'blogger')\n with io.StringIO() as f:\n print_html_to_stream(args, posts, title, f, target)\n html = f.getvalue()\n if html_name:\n if os.path.exists(html_name):\n with open(html_name, 'rt', encoding='utf-8') as f:\n html0 = f.read()\n if html == html0:\n return None\n with open(html_name, 'wt', encoding='utf-8') as f:\n f.write(html)\n return None\n else:\n return html\n\n\n<mask token>\n\n\ndef is_image_file(name):\n return os.path.splitext(name)[1].lower() in ('.jpg', '.jpeg', '.png',\n '.gif', '.bmp', '.webp', '.tif')\n\n\n<mask token>\n\n\ndef is_media(name):\n return is_image_file(name) or is_video_file(name)\n\n\n<mask token>\n\n\ndef date_from_name(name):\n if (match := re.search('(?:\\\\D|^)(\\\\d{8})(?:\\\\D|$)', name, re.ASCII)):\n digits = match.group(1)\n if validate_date(digits):\n return digits\n return None\n\n\ndef date_from_item(filename):\n if (date := date_from_name(filename)):\n return date\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d')\n\n\ndef time_from_name(name):\n if (match := re.search('(?:\\\\D|^)(\\\\d{8})\\\\D(\\\\d{6})(?:\\\\D|$)', name,\n re.ASCII)):\n digits = match.group(2)\n hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits\n [4:6])\n if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60:\n return digits\n return None\n\n\ndef time_from_item(filename):\n if (time := time_from_name(filename)):\n return time\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S')\n\n\n<mask token>\n\n\ndef get_image_info(filename):\n date = date_from_item(filename)\n time = time_from_item(filename)\n img = Image.open(filename)\n width, height = img.size\n size = round(os.path.getsize(filename) / 1000000.0, 1)\n return (date, time, width, height, size\n ), f'{date} {time}, dim={width}x{height}, {size} MB'\n\n\ndef get_video_info(filename, info_fullname):\n if os.path.exists(info_fullname):\n with open(info_fullname) as f:\n info = f.readline().split()\n date, time, width, height, size, duration, fps = info[0], info[1], int(\n info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6]\n )\n formatted_info = format_video_info(date, time, width, height, size,\n duration, fps)\n return (date, time, width, height, size, duration, fps), formatted_info\n else:\n info, formatted_info = make_video_info(filename, info_fullname)\n with open(info_fullname, 'wt') as f:\n print(' '.join([str(_) for _ in info]), file=f)\n return info, formatted_info\n\n\ndef make_video_info(filename, info_fullname):\n date = date_from_item(filename)\n time = time_from_item(filename)\n command = [*FFPROBE_CMD.split(), filename]\n try:\n output = check_output(command, stderr=STDOUT).decode()\n width, height, fps, duration = parse_ffprobe_output(output)\n size = round(os.path.getsize(filename) / 1000000.0, 1)\n output = format_video_info(date, time, width, height, size,\n duration, fps)\n except CalledProcessError as e:\n output = e.output.decode()\n warning(output)\n raise\n return (date, time, width, height, size, duration, fps), output\n\n\ndef parse_ffprobe_output(ffprobe_output):\n match = re.match(\n '(\\\\d+),(\\\\d+),(\\\\d+)/(\\\\d+),(\\\\d+/\\\\d+).*\\\\s(\\\\d+\\\\.\\\\d+)',\n ffprobe_output, re.DOTALL)\n width = int(match.group(1))\n height = int(match.group(2))\n fps = round(int(match.group(3)) / int(match.group(4)), 1)\n duration = round(float(match.group(6)))\n return width, height, fps, duration\n\n\ndef format_video_info(date, time, width, height, size, duration, fps):\n return (\n f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB'\n )\n\n\n<mask token>\n\n\ndef thumbname(name, key):\n return key + '-' + name + '.jpg'\n\n\ndef size_thumbnail(width, height, maxdim):\n if width >= height:\n return maxdim, int(round(maxdim * height / width))\n else:\n return int(round(maxdim * width / height)), maxdim\n\n\ndef make_thumbnail_image(args, image_name, thumb_name, size):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_image(image_name, thumb_name, size)\n\n\ndef create_thumbnail_image(image_name, thumb_name, size):\n imgobj = Image.open(image_name)\n if imgobj.mode != 'RGBA' and image_name.endswith('.jpg') and not (\n image_name.endswith('.gif') and imgobj.info.get('transparency')):\n imgobj = imgobj.convert('RGBA')\n imgobj.thumbnail(size, Image.LANCZOS)\n imgobj = imgobj.convert('RGB')\n imgobj.save(thumb_name)\n\n\ndef make_thumbnail_video(args, video_name, thumb_name, size, duration):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_video(args, video_name, thumb_name, size, duration)\n\n\n<mask token>\n\n\ndef create_thumbnail_video(args, filename, thumbname, size, duration):\n delay = min(duration - 1, args.thumbnails.thumbdelay)\n sizearg = '%dx%d' % size\n command = (\n 'ffmpeg -y -v error -itsoffset -%d -i \"%s\" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s \"%s\"'\n )\n command = command % (delay, filename, sizearg, thumbname)\n result = os.system(command)\n try:\n img1 = Image.open(thumbname)\n except:\n warning('Unable to save thumbnail for', filename)\n return\n img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON)))\n width, height = img1.size\n img1.paste(img2, (6, height - 20 - 6), None)\n img1.save(thumbname)\n\n\n<mask token>\n\n\ndef create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir):\n\n def size_thumbnail(width, height, xmax, ymax):\n width2 = xmax\n height2 = int(round(xmax * height / width))\n if height2 < ymax:\n width2 = int(round(ymax * width / height))\n height2 = ymax\n return width2, height2\n thumblist = [os.path.basename(item.thumb) for item in items]\n widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size\n , thumblist)\n thumbnum = widthnum * heightnum\n img = Image.new('RGB', size, SUBDIR_BACKCOL)\n for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]):\n row = ind // widthnum\n col = ind % widthnum\n img2 = Image.open(os.path.join(thumbdir, thumb))\n w, h = size_thumbnail(*img2.size, width[col], height[row])\n cropdim = (w - width[col]) // 2, (h - height[row]) // 2, (w - width\n [col]) // 2 + width[col], (h - height[row]) // 2 + height[row]\n img2 = img2.resize((w, h), Image.LANCZOS)\n img2 = img2.crop(cropdim)\n img.paste(img2, (offsetx[col], offsety[row]))\n if os.path.exists(thumb_name):\n imgref = Image.open(thumb_name)\n byteio = io.BytesIO()\n img.save(byteio, 'JPEG')\n byteio.seek(0)\n imgnew = Image.open(byteio)\n diff = ImageChops.difference(imgnew, imgref)\n if diff.getbbox() is None:\n return\n img.save(thumb_name)\n\n\ndef mosaic_geometry(size, thumblist):\n if len(thumblist) == 1:\n widthnum = 1\n heightnum = 1\n elif len(thumblist) <= 3:\n widthnum = 1\n heightnum = 2\n elif len(thumblist) <= 8:\n widthnum = 2\n heightnum = 2\n else:\n widthnum = 3\n heightnum = 3\n if widthnum == 1:\n width = [size[0] - 2]\n else:\n width = [size[0] // widthnum - 2] * (widthnum - 1)\n width.append(size[0] - (1 + sum(width) + 2 * len(width) + 1))\n if heightnum == 1:\n height = [size[1] - 2]\n else:\n height = [size[1] // heightnum - 2] * (heightnum - 1)\n height.append(size[1] - (1 + sum(height) + 2 * len(height) + 1))\n offsetx = [1]\n for w in width[:-1]:\n offsetx.append(offsetx[-1] + w + 2)\n offsety = [1]\n for h in height[:-1]:\n offsety.append(offsety[-1] + h + 2)\n return widthnum, heightnum, width, height, offsetx, offsety\n\n\n<mask token>\n\n\ndef list_of_htmlfiles_in_items(itemlist):\n htmlist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n htmlist.append(item.htmname)\n htmlist.extend(list_of_htmlfiles_in_items(item.sublist))\n return htmlist\n\n\ndef list_of_thumbnails(posts, diary=False):\n thumblist = list()\n for post in posts:\n thumblist.extend(list_of_thumbnails_in_items(post.medias))\n if diary is False:\n thumblist.extend(list_of_thumbnails_in_items(post.dcim))\n return thumblist\n\n\ndef list_of_thumbnails_in_items(itemlist):\n thumblist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n thumblist.append(os.path.basename(item.thumb))\n thumblist.extend(list_of_thumbnails_in_items(item.sublist))\n else:\n thumblist.append(os.path.basename(item.thumb))\n return thumblist\n\n\ndef purge_htmlfiles(args, posts):\n \"\"\"\n Purge root dir from irrelevant html files\n \"\"\"\n htmlist = list_of_htmlfiles(args, posts)\n html_to_remove = list()\n for fullname in glob.glob(os.path.join(args.root, '*.htm*')):\n if fullname not in htmlist:\n html_to_remove.append(fullname)\n if len(html_to_remove) > args.thumbnails.threshold_htmlfiles:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(\n f'{len(html_to_remove)} html files to remove. Continue [y|n]? '\n ).lower()\n if inpt == 'n':\n return\n for name in html_to_remove:\n print('Removing html files', name)\n os.remove(name)\n\n\ndef purge_thumbnails(args, thumbdir, posts, diary=False):\n \"\"\"\n Purge thumbnail dir from irrelevant thumbnails\n \"\"\"\n thumblist = list_of_thumbnails(posts, diary)\n thumbs_to_remove = list()\n for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')):\n if os.path.basename(fullname) not in thumblist:\n thumbs_to_remove.append(fullname)\n if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(\n f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? '\n ).lower()\n if inpt == 'n':\n return\n for name in thumbs_to_remove:\n print('Removing thumbnail', name)\n os.remove(name)\n info_fullname = os.path.splitext(name)[0] + '.info'\n if os.path.exists(info_fullname):\n os.remove(info_fullname)\n\n\ndef is_media_within_dates(fullname, dates):\n if is_media(fullname):\n if type(dates) == tuple:\n return dates[0] <= date_from_item(fullname) <= dates[1]\n else:\n return True\n else:\n return False\n\n\ndef sorted_listdir(filelist):\n like_windows_explorer = True\n if not filelist:\n return filelist\n if like_windows_explorer:\n maxlen = max(len(os.path.splitext(name)[0]) for name in filelist)\n\n def keyfunc(name):\n root, ext = os.path.splitext(name.lower())\n return root.ljust(maxlen, ' ') + ext\n else:\n keyfunc = str.lower\n return sorted(filelist, key=keyfunc)\n\n\ndef list_of_files(sourcedir, recursive):\n \"\"\"\n Return the list of full paths for files in source directory\n \"\"\"\n result = list()\n if recursive is False:\n listdir = sorted_listdir(os.listdir(sourcedir))\n if '.nomedia' not in listdir:\n for basename in listdir:\n result.append(os.path.join(sourcedir, basename))\n else:\n for root, dirs, files in os.walk(sourcedir):\n if '.nomedia' not in files:\n for basename in sorted_listdir(files):\n result.append(os.path.join(root, basename))\n return result\n\n\ndef list_of_medias(args, sourcedir, recursive):\n \"\"\"\n Return the list of full paths for pictures and movies in source directory\n \"\"\"\n files = list_of_files(sourcedir, recursive)\n return [_ for _ in files if is_media_within_dates(_, args.dates)]\n\n\n<mask token>\n\n\ndef dispatch_post_items(list_of_post_items):\n subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir]\n medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir]\n return subdirs, medias\n\n\ndef create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax):\n if os.path.isfile(media_fullname):\n if is_image_file(media_fullname):\n return create_item_image(args, media_fullname, sourcedir,\n thumbdir, key, thumbmax)\n else:\n return create_item_video(args, media_fullname, sourcedir,\n thumbdir, key, thumbmax)\n else:\n return create_item_subdir(args, media_fullname, sourcedir, thumbdir,\n key, thumbmax)\n\n\ndef create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax\n ):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n try:\n info, infofmt = get_image_info(media_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize)\n return PostImage(None, media_fullname, '/'.join((args.thumbrep,\n thumb_basename)), thumbsize, infofmt)\n except PIL.UnidentifiedImageError:\n warning('Unable to read image', media_fullname)\n return None\n\n\ndef create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax\n ):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n info_fullname = os.path.splitext(thumb_fullname)[0] + '.info'\n try:\n info, infofmt = get_video_info(media_fullname, info_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_video(args, media_fullname, thumb_fullname,\n thumbsize, duration=info[5])\n return PostVideo(None, media_fullname, '/'.join((args.thumbrep,\n thumb_basename)), thumbsize, infofmt)\n except CalledProcessError:\n warning('Unable to read video', media_fullname)\n return None\n\n\n<mask token>\n\n\ndef relative_name(media_fullname, sourcedir):\n \"\"\"\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg\n -->\n deeper2_deepest_OCT_20000112_000004.jpg\n\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest\n -->\n deeper2_deepest\n \"\"\"\n x = os.path.relpath(media_fullname, sourcedir)\n x = x.replace('\\\\', '_').replace('/', '_').replace('#', '_')\n return x\n\n\n<mask token>\n\n\ndef make_posts_from_diary(args):\n md_filename = os.path.join(args.root, 'index.md')\n if os.path.exists(md_filename):\n title, posts = parse_markdown(md_filename)\n else:\n error('File not found', md_filename)\n for post in posts:\n for media in post.medias:\n media_fullname = os.path.join(args.root, media.uri)\n item = create_item(args, media_fullname, args.root, args.\n thumbdir, 'post', 400)\n media.thumb = item.thumb\n media.thumbsize = item.thumbsize\n media.descr = item.descr\n return title, posts\n\n\ndef create_items_by_date(args, medias, posts):\n if args.dates == 'diary':\n required_dates = {post.date for post in posts}\n else:\n required_dates = {date_from_item(media) for media in medias}\n if type(args.dates) == tuple:\n date1, date2 = args.dates\n required_dates = {date for date in required_dates if date1 <=\n date <= date2}\n bydate = defaultdict(list)\n for media_fullname in medias:\n date = date_from_item(media_fullname)\n if date in required_dates:\n item = create_item(args, media_fullname, args.sourcedir, args.\n thumbdir, 'dcim', 300)\n if item:\n bydate[date].append(item)\n for date, liste in bydate.items():\n liste.sort(key=lambda item: time_from_item(item.uri))\n return bydate\n\n\n<mask token>\n\n\ndef make_posts_from_subdir(args, dirname):\n if args.bydir is False:\n medias_ext = list_of_medias(args, dirname, args.recursive)\n else:\n medias_ext = list_of_medias_ext(args, dirname)\n postmedias = list()\n for item in medias_ext:\n postmedia = create_item(args, item, args.sourcedir, args.thumbdir,\n 'dcim', 300)\n if postmedia is not None:\n postmedias.append(postmedia)\n post = Post(date='00000000', text='', medias=[])\n post.dcim = postmedias\n posts = [post]\n title = os.path.basename(args.sourcedir) or os.path.splitdrive(args.\n sourcedir)[0]\n return title, posts\n\n\n<mask token>\n\n\ndef create_gallery(args):\n title, posts = make_posts(args, args.sourcedir)\n print_html(args, posts, title, os.path.join(args.dest, args.rootname),\n 'regular')\n purge_htmlfiles(args, posts)\n if args.diary and not args.sourcedir:\n purge_thumbnails(args, args.thumbdir, posts, diary=True)\n else:\n purge_thumbnails(args, args.thumbdir, posts)\n\n\ndef create_diary(args):\n medias = list_of_medias(args, args.sourcedir, args.recursive)\n if args.dates == 'diary':\n assert 0\n else:\n required_dates = {date_from_item(media) for media in medias}\n if type(args.dates) == tuple:\n date1, date2 = args.dates\n required_dates = {date for date in required_dates if date1 <=\n date <= date2}\n title = args.sourcedir\n posts = list()\n for date in sorted(required_dates):\n posts.append(Post.from_date(date))\n os.makedirs(args.root, exist_ok=True)\n print_markdown(posts, title, os.path.join(args.root, 'index.md'))\n\n\ndef online_images_url(args):\n try:\n if args.urlblogger.startswith('http:') or args.urlblogger.startswith(\n 'https:'):\n with urlopen(args.urlblogger) as u:\n buffer = u.read()\n else:\n with open(args.urlblogger, 'rb') as f:\n buffer = f.read()\n except:\n error('Unable to read url', args.urlblogger)\n buffer = buffer.decode('utf-8')\n online_images = dict()\n for match in re.finditer('<div class=\"separator\"((?!<div).)*?</div>',\n buffer, flags=re.DOTALL):\n div_separator = match.group(0)\n div_separator = div_separator.replace('&nbsp;', '')\n elem_div = objectify.fromstring(div_separator)\n for elem_a in elem_div.iterchildren(tag='a'):\n href = elem_a.get('href')\n thumb = elem_a.img.get('src')\n online_images[os.path.basename(href)] = href, thumb\n online_videos = list()\n for match in re.finditer(\n '<iframe allowfullscreen=\"allowfullscreen\".*?</iframe>', buffer,\n flags=re.DOTALL):\n iframe = match.group(0)\n online_videos.append(iframe)\n return online_images, online_videos\n\n\ndef compare_image_buffers(imgbuf1, imgbuf2):\n \"\"\"\n return True if images read on file are identical, False otherwise\n \"\"\"\n with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2:\n img1 = Image.open(imgio1)\n img2 = Image.open(imgio2)\n diff = ImageChops.difference(img1, img2)\n return not diff.getbbox()\n\n\ndef check_images(args, posts, online_images):\n result = True\n for post in posts:\n for media in post.medias:\n if type(media) is PostImage:\n if media.basename in online_images:\n with open(os.path.join(args.root, media.uri), 'rb') as f:\n imgbuf1 = f.read()\n try:\n with urlopen(online_images[media.basename][0]) as u:\n imgbuf2 = u.read()\n except FileNotFoundError:\n print('File not found', online_images[media.\n basename][0])\n next\n if compare_image_buffers(imgbuf1, imgbuf2) is False:\n print('Files are different, upload', media.basename)\n elif 1:\n print('File already online', media.basename)\n else:\n print('File is absent, upload', media.basename)\n result = False\n elif type(media) is PostVideo:\n print('Video not checked', media.basename)\n else:\n assert False\n return result\n\n\ndef compose_blogger_html(args, title, posts, imgdata, online_videos):\n \"\"\" Compose html with blogger image urls\n \"\"\"\n for post in posts:\n for media in post.medias:\n if type(media) is PostImage:\n if media.uri not in imgdata:\n print('Image missing: ', media.uri)\n else:\n img_url, resized_url = imgdata[media.uri]\n media.uri = img_url\n media.resized_url = resized_url\n elif type(media) is PostVideo:\n if not online_videos:\n print('Video missing: ', media.uri)\n else:\n media.iframe = online_videos[0]\n del online_videos[0]\n else:\n assert False\n return print_html(args, posts, title, '', target='blogger')\n\n\ndef prepare_for_blogger(args):\n \"\"\"\n Export blogger html to clipboard.\n If --full, export complete html, otherwise export html extract ready to\n paste into blogger edit mode.\n \"\"\"\n title, posts = parse_markdown(os.path.join(args.root, 'index.md'))\n online_images, online_videos = online_images_url(args)\n if args.check_images and check_images(args, posts, online_images) is False:\n pass\n html = compose_blogger_html(args, title, posts, online_images,\n online_videos)\n if args.full is False:\n html = re.search('<body>(.*)?</body>', html, flags=re.DOTALL).group(1)\n html = re.sub('<script>.*?</script>', '', html, flags=re.DOTALL)\n html = STYLE.replace('%%', '%') + html\n if args.dest:\n with open(args.dest, 'wt', encoding='utf-8') as f:\n f.write(html)\n else:\n clipboard.copy(html)\n\n\ndef idempotence(args):\n \"\"\"\n For testing identity between a diary file and the fle obtained after reading\n and printing it. See testing.\n \"\"\"\n title, posts = parse_markdown(os.path.join(args.root, 'index.md'))\n print_markdown(posts, title, os.path.join(args.dest, 'index.md'))\n\n\n<mask token>\n\n\nclass MyConfigParser(ConfigParser):\n \"\"\"Add input checking.\"\"\"\n\n def __init__(self):\n ConfigParser.__init__(self, inline_comment_prefixes=(';',))\n\n def error(self, section, entry):\n error('Missing or incorrect config value:', '[%s]%s' % (section, entry)\n )\n\n def getint(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getint(self, section, entry)\n else:\n return ConfigParser.getint(self, section, entry, raw=True,\n vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n def getboolean(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getboolean(self, section, entry)\n else:\n return ConfigParser.getboolean(self, section, entry, raw=\n True, vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n\ndef configfilename(params):\n return os.path.join(params.root, '.config.ini')\n\n\ndef createconfig(config_filename):\n with open(config_filename, 'wt') as f:\n f.writelines(CONFIG_DEFAULTS)\n\n\ndef read_config(params):\n config_filename = configfilename(params)\n try:\n if not os.path.exists(config_filename) or params.resetcfg:\n createconfig(config_filename)\n except:\n error('Error creating configuration file')\n try:\n getconfig(params, config_filename)\n except Exception as e:\n error('Error reading configuration file.', str(e), 'Use --resetcfg')\n\n\ndef getconfig(options, config_filename):\n\n\n class Section:\n pass\n options.source = Section()\n options.thumbnails = Section()\n options.photobox = Section()\n config = MyConfigParser()\n config.read(config_filename)\n options.source.sourcedir = config.get('source', 'sourcedir')\n options.source.bydir = config.getboolean('source', 'bydir')\n options.source.bydate = config.getboolean('source', 'bydate')\n options.source.diary = config.getboolean('source', 'diary')\n options.source.recursive = config.getboolean('source', 'recursive')\n options.source.dates = config.get('source', 'dates')\n options.source.github_pages = config.getboolean('source',\n 'github_pages', default=False)\n options.thumbnails.media_description = config.getboolean('thumbnails',\n 'media_description')\n options.thumbnails.subdir_caption = config.getboolean('thumbnails',\n 'subdir_caption')\n options.thumbnails.thumbdelay = config.getint('thumbnails', 'thumbdelay')\n options.thumbnails.threshold_thumbs = config.getint('thumbnails',\n 'threshold_thumbs')\n options.thumbnails.threshold_htmlfiles = config.getint('thumbnails',\n 'threshold_htmlfiles', default=3)\n options.photobox.loop = config.getboolean('photobox', 'loop')\n options.photobox.thumbs = config.getboolean('photobox', 'thumbs')\n options.photobox.autoplay = config.getboolean('photobox', 'autoplay')\n options.photobox.time = config.getint('photobox', 'time')\n options.photobox.zoomable = config.getboolean('photobox', 'zoomable')\n options.photobox.rotatable = config.getboolean('photobox', 'rotatable')\n options.photobox.wheelNextPrev = config.getboolean('photobox',\n 'wheelNextPrev')\n\n\n<mask token>\n\n\ndef setconfig_cmd(args):\n config_filename = configfilename(args)\n setconfig(config_filename, *args.setcfg)\n\n\ndef update_config(args):\n updates = ('sourcedir', args.sourcedir), ('bydir', BOOL[args.bydir]), (\n 'bydate', BOOL[args.bydate]), ('diary', BOOL[args.diary]), ('recursive'\n , BOOL[args.recursive]), ('dates', args.dates), ('github_pages',\n BOOL[args.github_pages])\n cfgname = configfilename(args)\n with open(cfgname) as f:\n cfglines = [_.strip() for _ in f.readlines()]\n for key, value in updates:\n for iline, line in enumerate(cfglines):\n if line.startswith(key):\n cfglines[iline] = f'{key} = {value}'\n break\n with open(cfgname, 'wt') as f:\n for line in cfglines:\n print(line, file=f)\n\n\ndef warning(*msg):\n print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + ' '.join(msg),\n colorama.Style.RESET_ALL)\n\n\n<mask token>\n\n\ndef errorcode(msg):\n return ERRORS.splitlines().index(msg) + 1\n\n\ndef error(*msg):\n print(colorama.Fore.RED + colorama.Style.BRIGHT + ' '.join(msg),\n colorama.Style.RESET_ALL)\n sys.exit(errorcode(msg[0]))\n\n\n<mask token>\n\n\ndef setup_part1(args):\n \"\"\"\n Made before reading config file (config file located in args.root).\n Check and normalize root path.\n \"\"\"\n args.rootarg = args.root\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext == '':\n pass\n else:\n args.root = os.path.dirname(args.root)\n if args.root:\n args.root = os.path.abspath(args.root)\n if not os.path.isdir(args.root):\n if args.gallery:\n os.mkdir(args.root)\n else:\n error('Directory not found', args.root)\n\n\ndef setup_part2(args):\n \"\"\"\n Made after reading config file.\n Check for ffmpeg in path.\n Create .thumbnails dir if necessary and create .nomedia in it.\n Copy photobox file to destination dir.\n Handle priority between command line and config file.\n \"\"\"\n if args.update:\n args.sourcedir = args.source.sourcedir\n args.bydir = args.source.bydir\n args.bydate = args.source.bydate\n args.diary = args.source.diary\n args.recursive = args.source.recursive\n args.dates = args.source.dates\n args.github_pages = args.source.github_pages\n elif args.gallery:\n args.source.sourcedir = args.sourcedir\n args.source.bydir = args.bydir\n args.source.bydate = args.bydate\n args.source.diary = args.diary\n args.source.recursive = args.recursive\n args.source.dates = args.dates\n args.source.github_pages = args.github_pages\n update_config(args)\n if args.github_pages:\n args.html_suffix = '.html'\n else:\n args.html_suffix = '.htm'\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext:\n args.rootname = os.path.basename(args.rootarg)\n else:\n args.rootname = 'index' + args.html_suffix\n if args.sourcedir:\n args.sourcedir = os.path.abspath(args.sourcedir)\n if os.path.splitdrive(args.sourcedir)[0]:\n drive, rest = os.path.splitdrive(args.sourcedir)\n args.sourcedir = drive.upper() + rest\n if not os.path.isdir(args.sourcedir):\n error('Directory not found', args.sourcedir)\n elif args.gallery and args.diary is False and args.update is None:\n error('Directory not found', 'Use --sourcedir')\n if args.dest:\n args.dest = os.path.abspath(args.dest)\n if args.dest is None:\n args.dest = args.root\n if args.blogger and args.urlblogger is None:\n error('No blogger url (--url)')\n if args.gallery or args.update:\n for exe in ('ffmpeg', 'ffprobe'):\n try:\n check_output([exe, '-version'])\n except FileNotFoundError:\n error('File not found', exe)\n if args.github_pages:\n args.thumbrep = 'thumbnails'\n else:\n args.thumbrep = '.thumbnails'\n args.thumbdir = os.path.join(args.dest, args.thumbrep)\n if not os.path.exists(args.thumbdir):\n os.mkdir(args.thumbdir)\n open(os.path.join(args.thumbdir, '.nomedia'), 'a').close()\n favicondst = os.path.join(args.dest, 'favicon.ico')\n if not os.path.isfile(favicondst):\n faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico')\n shutil.copyfile(faviconsrc, favicondst)\n photoboxdir = os.path.join(args.dest, 'photobox')\n if not os.path.exists(photoboxdir):\n photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox')\n shutil.copytree(photoboxsrc, photoboxdir)\n if args.dates:\n if not (args.gallery or args.create):\n pass\n if args.dates == 'source':\n pass\n elif args.dates == 'diary':\n if args.create:\n error('Incorrect date format', args.dates)\n elif re.match('\\\\d+-\\\\d+', args.dates):\n date1, date2 = args.dates.split('-')\n if validate_date(date1) and validate_date(date2):\n args.dates = date1, date2\n else:\n error('Incorrect date format', args.dates)\n else:\n error('Incorrect date format', args.dates)\n\n\ndef main(argstring=None):\n colorama.init()\n args = parse_command_line(argstring)\n setup_part1(args)\n read_config(args)\n setup_part2(args)\n try:\n if args.gallery or args.update:\n create_gallery(args)\n elif args.create:\n create_diary(args)\n elif args.blogger:\n prepare_for_blogger(args)\n elif args.idem:\n idempotence(args)\n elif args.setcfg:\n setconfig_cmd(args)\n except KeyboardInterrupt:\n warning('Interrupted by user.')\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass Post:\n\n def __init__(self, date, text, medias):\n self.date = date\n self.text = text\n self.medias = medias\n self.dcim = []\n self.daterank = 0\n self.extra = False\n\n def __lt__(self, other):\n return self.date < other.date\n\n @classmethod\n def from_markdown(cls, post):\n m = re.match('\\\\[(\\\\d\\\\d\\\\d\\\\d/\\\\d\\\\d/\\\\d\\\\d)\\\\]\\\\n*', post[0])\n if m:\n date = m.group(1).replace('/', '')\n if not validate_date(date):\n error('Incorrect date value:', date)\n del post[0]\n else:\n error('No date in post', ' '.join(post))\n while post and not post[0].strip():\n del post[0]\n text = ''\n while post and not re.match('!?\\\\[\\\\]', post[0]):\n text += post[0]\n del post[0]\n text = re.sub('\\\\n\\\\n$', '\\n', text)\n medias = list()\n while post and (match := re.match('!?\\\\[\\\\]\\\\((.*)\\\\)', post[0])):\n media = match.group(1)\n caption = None\n del post[0]\n if post and not re.match('!?\\\\[\\\\]', post[0]):\n caption = post[0].strip()\n del post[0]\n if match.group(0)[0] == '!':\n medias.append(PostImage(caption, media))\n else:\n medias.append(PostVideo(caption, media))\n return cls(date, text, medias)\n\n @classmethod\n def from_date(cls, date):\n dt = datetime.datetime.strptime(date, '%Y%m%d')\n datetext = dt.strftime('%A %d %B %Y').capitalize()\n post = cls(date, text=datetext, medias=[])\n post.daterank = 1\n return post\n\n def to_html(self, args, target='regular'):\n if target == 'regular':\n if args.diary:\n return self.to_html_diary(args)\n else:\n return self.to_html_regular(args)\n if target == 'blogger':\n return self.to_html_blogger()\n\n def to_html_regular(self, args):\n html = list()\n if self.text:\n html.append(markdown.markdown(self.text))\n subdirs, dcim = dispatch_post_items(self.dcim)\n if self.dcim:\n html.append(SEP)\n for media in subdirs:\n html.append(media.to_html_dcim(args))\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n html.append(SEP)\n return html\n\n def to_html_diary(self, args):\n html = list()\n if self.extra:\n html.append('<div class=\"extra\">')\n if self.text:\n html.append(markdown.markdown(self.text))\n if self.medias:\n html.append(f'<div id=\"gallery-blog-{self.date}-{self.daterank}\">')\n for media in self.medias:\n html.append(media.to_html_post(args))\n html.append('</div>')\n _, dcim = dispatch_post_items(self.dcim)\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n html.append(SEP)\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n html.append(SEP)\n if self.extra:\n html.append('</div>')\n return html\n\n def to_html_blogger(self):\n html = list()\n html.append(markdown.markdown(self.text))\n for image in self.medias:\n html.append(image.to_html_blogger())\n html.append(SEP)\n return html\n\n\nclass PostItem:\n\n def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''):\n self.caption = caption\n self.uri = uri\n self.basename = os.path.basename(uri)\n self.thumb = thumb\n self.thumbsize = thumbsize\n self.descr = descr\n self.resized_url = None\n\n\nclass PostImage(PostItem):\n\n def to_markdown(self):\n if not self.caption:\n return '![](%s)' % (self.uri,)\n else:\n return '![](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize,\n descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, *\n self.thumbsize, descr)\n\n def to_html_blogger(self):\n if not self.caption:\n return BIMGPAT % (self.uri, self.resized_url)\n else:\n return f'{BIMGPAT}\\n{CAPTION_PAT}' % (self.uri, self.\n resized_url, self.caption)\n\n\nclass PostVideo(PostItem):\n\n def to_markdown(self):\n if not self.caption:\n return '[](%s)' % (self.uri,)\n else:\n return '[](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize,\n descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, *\n self.thumbsize, descr)\n\n def to_html_blogger(self):\n x = f'<p style=\"text-align: center;\">{self.iframe}</p>'\n if not self.caption:\n return x\n else:\n return f'%s\\n{CAPTION_PAT}' % (x, self.caption)\n\n\nclass PostSubdir(PostItem):\n\n def to_html_dcim(self, args):\n basename = os.path.basename(self.htmname)\n posts = self.posts\n title = self.caption\n print_html(args, posts, title, self.htmname)\n if not self.caption:\n return DIRPOST % (basename, self.thumb, *self.thumbsize)\n else:\n return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize,\n self.caption)\n\n\ndef relative_url(path, root):\n \"\"\"\n returns a normalized url to path relative from root\n \"\"\"\n try:\n url = os.path.relpath(path, root)\n except:\n error('Unable to make a relative url:', url, root)\n url = url.replace('\\\\', '/') if os.sep == '\\\\' else url\n return urllib.parse.quote(url)\n\n\ndef parse_markdown(filename):\n \"\"\"\n Generate Post objects from markdown. Date must be present in each post and\n posts must be ordrered by date.\n \"\"\"\n if not os.path.exists(filename):\n error('File not found', filename)\n posts = list()\n with open(filename, encoding='utf-8') as f:\n line = next(f)\n if line.startswith('# '):\n title = line[2:].strip()\n record = []\n next(f)\n else:\n title = None\n record = [line]\n for line in f:\n if not line.startswith('___'):\n record.append(line)\n else:\n posts.append(Post.from_markdown(record))\n record = []\n daterank = defaultdict(int)\n for post in posts:\n daterank[post.date] += 1\n post.daterank = daterank[post.date]\n for post1, post2 in zip(posts[:-1], posts[1:]):\n if post1.date > post2.date:\n error('Posts are not ordered', f'{post1.date} > {post2.date}')\n return title, posts\n\n\ndef print_markdown(posts, title, fullname):\n with open(fullname, 'wt', encoding='utf-8') as fdst:\n print(f'# {title}\\n', file=fdst)\n for post in posts:\n date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]'\n print(date, file=fdst)\n if post.text:\n print(file=fdst)\n for line in post.text.splitlines():\n if not line:\n print(file=fdst)\n else:\n for chunk in textwrap.wrap(line, width=78):\n print(chunk, file=fdst)\n if post.medias:\n print(file=fdst)\n for media in post.medias:\n print(media.to_markdown(), file=fdst)\n print('______', file=fdst)\n\n\ndef compose_html_reduced(args, posts, title, target):\n html = list()\n html.append(START % title)\n for post in posts:\n for line in post.to_html(args, target):\n html.append(line.strip())\n html.append('')\n html.append(END)\n return html\n\n\ndef compose_html_full(args, posts, title, target):\n html = list()\n html.append(START % title)\n if args.diary:\n html.append(BUTTONS)\n for post in posts:\n for line in post.to_html(args, target):\n html.append(line.strip())\n html.append('')\n html.append('<script>')\n for post in posts:\n if post.medias:\n gallery_id = f'gallery-blog-{post.date}-{post.daterank}'\n html.append(gallery_call(args, gallery_id))\n if post.dcim:\n gallery_id = f'gallery-dcim-{post.date}-{post.daterank}'\n html.append(gallery_call(args, gallery_id))\n html.append('</script>')\n html.append(END)\n return html\n\n\ndef print_html_to_stream(args, posts, title, stream, target):\n if target == 'regular':\n for line in compose_html_full(args, posts, title, target):\n print(line, file=stream)\n else:\n for line in compose_html_reduced(args, posts, title, target):\n print(line, file=stream)\n\n\ndef print_html(args, posts, title, html_name, target='regular'):\n assert target in ('regular', 'blogger')\n with io.StringIO() as f:\n print_html_to_stream(args, posts, title, f, target)\n html = f.getvalue()\n if html_name:\n if os.path.exists(html_name):\n with open(html_name, 'rt', encoding='utf-8') as f:\n html0 = f.read()\n if html == html0:\n return None\n with open(html_name, 'wt', encoding='utf-8') as f:\n f.write(html)\n return None\n else:\n return html\n\n\n<mask token>\n\n\ndef is_image_file(name):\n return os.path.splitext(name)[1].lower() in ('.jpg', '.jpeg', '.png',\n '.gif', '.bmp', '.webp', '.tif')\n\n\ndef is_video_file(name):\n return os.path.splitext(name)[1].lower() in ('.mp4', '.webm', '.mkv',\n '.flv', '.m4v', '.avi', '.wmv', '.mts', '.vob', '.divx')\n\n\ndef is_media(name):\n return is_image_file(name) or is_video_file(name)\n\n\ndef validate_date(datestr):\n try:\n datetime.datetime.strptime(datestr, '%Y%m%d')\n return True\n except ValueError:\n return False\n\n\ndef date_from_name(name):\n if (match := re.search('(?:\\\\D|^)(\\\\d{8})(?:\\\\D|$)', name, re.ASCII)):\n digits = match.group(1)\n if validate_date(digits):\n return digits\n return None\n\n\ndef date_from_item(filename):\n if (date := date_from_name(filename)):\n return date\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d')\n\n\ndef time_from_name(name):\n if (match := re.search('(?:\\\\D|^)(\\\\d{8})\\\\D(\\\\d{6})(?:\\\\D|$)', name,\n re.ASCII)):\n digits = match.group(2)\n hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits\n [4:6])\n if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60:\n return digits\n return None\n\n\ndef time_from_item(filename):\n if (time := time_from_name(filename)):\n return time\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S')\n\n\n<mask token>\n\n\ndef get_image_info(filename):\n date = date_from_item(filename)\n time = time_from_item(filename)\n img = Image.open(filename)\n width, height = img.size\n size = round(os.path.getsize(filename) / 1000000.0, 1)\n return (date, time, width, height, size\n ), f'{date} {time}, dim={width}x{height}, {size} MB'\n\n\ndef get_video_info(filename, info_fullname):\n if os.path.exists(info_fullname):\n with open(info_fullname) as f:\n info = f.readline().split()\n date, time, width, height, size, duration, fps = info[0], info[1], int(\n info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6]\n )\n formatted_info = format_video_info(date, time, width, height, size,\n duration, fps)\n return (date, time, width, height, size, duration, fps), formatted_info\n else:\n info, formatted_info = make_video_info(filename, info_fullname)\n with open(info_fullname, 'wt') as f:\n print(' '.join([str(_) for _ in info]), file=f)\n return info, formatted_info\n\n\ndef make_video_info(filename, info_fullname):\n date = date_from_item(filename)\n time = time_from_item(filename)\n command = [*FFPROBE_CMD.split(), filename]\n try:\n output = check_output(command, stderr=STDOUT).decode()\n width, height, fps, duration = parse_ffprobe_output(output)\n size = round(os.path.getsize(filename) / 1000000.0, 1)\n output = format_video_info(date, time, width, height, size,\n duration, fps)\n except CalledProcessError as e:\n output = e.output.decode()\n warning(output)\n raise\n return (date, time, width, height, size, duration, fps), output\n\n\ndef parse_ffprobe_output(ffprobe_output):\n match = re.match(\n '(\\\\d+),(\\\\d+),(\\\\d+)/(\\\\d+),(\\\\d+/\\\\d+).*\\\\s(\\\\d+\\\\.\\\\d+)',\n ffprobe_output, re.DOTALL)\n width = int(match.group(1))\n height = int(match.group(2))\n fps = round(int(match.group(3)) / int(match.group(4)), 1)\n duration = round(float(match.group(6)))\n return width, height, fps, duration\n\n\ndef format_video_info(date, time, width, height, size, duration, fps):\n return (\n f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB'\n )\n\n\ndef format_duration(duration):\n mn = duration // 60\n sec = duration % 60\n if mn <= 59:\n return f'm:s={mn:02}:{sec:02}'\n else:\n hour = mn // 60\n mn = mn % 60\n return f'h:m:s={hour:02}:{mn:02}:{sec:02}'\n\n\ndef thumbname(name, key):\n return key + '-' + name + '.jpg'\n\n\ndef size_thumbnail(width, height, maxdim):\n if width >= height:\n return maxdim, int(round(maxdim * height / width))\n else:\n return int(round(maxdim * width / height)), maxdim\n\n\ndef make_thumbnail_image(args, image_name, thumb_name, size):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_image(image_name, thumb_name, size)\n\n\ndef create_thumbnail_image(image_name, thumb_name, size):\n imgobj = Image.open(image_name)\n if imgobj.mode != 'RGBA' and image_name.endswith('.jpg') and not (\n image_name.endswith('.gif') and imgobj.info.get('transparency')):\n imgobj = imgobj.convert('RGBA')\n imgobj.thumbnail(size, Image.LANCZOS)\n imgobj = imgobj.convert('RGB')\n imgobj.save(thumb_name)\n\n\ndef make_thumbnail_video(args, video_name, thumb_name, size, duration):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_video(args, video_name, thumb_name, size, duration)\n\n\n<mask token>\n\n\ndef create_thumbnail_video(args, filename, thumbname, size, duration):\n delay = min(duration - 1, args.thumbnails.thumbdelay)\n sizearg = '%dx%d' % size\n command = (\n 'ffmpeg -y -v error -itsoffset -%d -i \"%s\" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s \"%s\"'\n )\n command = command % (delay, filename, sizearg, thumbname)\n result = os.system(command)\n try:\n img1 = Image.open(thumbname)\n except:\n warning('Unable to save thumbnail for', filename)\n return\n img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON)))\n width, height = img1.size\n img1.paste(img2, (6, height - 20 - 6), None)\n img1.save(thumbname)\n\n\ndef make_thumbnail_subdir(args, subdir_name, thumb_name, size, items, thumbdir\n ):\n print('Making thumbnail:', thumb_name)\n create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir)\n\n\ndef create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir):\n\n def size_thumbnail(width, height, xmax, ymax):\n width2 = xmax\n height2 = int(round(xmax * height / width))\n if height2 < ymax:\n width2 = int(round(ymax * width / height))\n height2 = ymax\n return width2, height2\n thumblist = [os.path.basename(item.thumb) for item in items]\n widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size\n , thumblist)\n thumbnum = widthnum * heightnum\n img = Image.new('RGB', size, SUBDIR_BACKCOL)\n for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]):\n row = ind // widthnum\n col = ind % widthnum\n img2 = Image.open(os.path.join(thumbdir, thumb))\n w, h = size_thumbnail(*img2.size, width[col], height[row])\n cropdim = (w - width[col]) // 2, (h - height[row]) // 2, (w - width\n [col]) // 2 + width[col], (h - height[row]) // 2 + height[row]\n img2 = img2.resize((w, h), Image.LANCZOS)\n img2 = img2.crop(cropdim)\n img.paste(img2, (offsetx[col], offsety[row]))\n if os.path.exists(thumb_name):\n imgref = Image.open(thumb_name)\n byteio = io.BytesIO()\n img.save(byteio, 'JPEG')\n byteio.seek(0)\n imgnew = Image.open(byteio)\n diff = ImageChops.difference(imgnew, imgref)\n if diff.getbbox() is None:\n return\n img.save(thumb_name)\n\n\ndef mosaic_geometry(size, thumblist):\n if len(thumblist) == 1:\n widthnum = 1\n heightnum = 1\n elif len(thumblist) <= 3:\n widthnum = 1\n heightnum = 2\n elif len(thumblist) <= 8:\n widthnum = 2\n heightnum = 2\n else:\n widthnum = 3\n heightnum = 3\n if widthnum == 1:\n width = [size[0] - 2]\n else:\n width = [size[0] // widthnum - 2] * (widthnum - 1)\n width.append(size[0] - (1 + sum(width) + 2 * len(width) + 1))\n if heightnum == 1:\n height = [size[1] - 2]\n else:\n height = [size[1] // heightnum - 2] * (heightnum - 1)\n height.append(size[1] - (1 + sum(height) + 2 * len(height) + 1))\n offsetx = [1]\n for w in width[:-1]:\n offsetx.append(offsetx[-1] + w + 2)\n offsety = [1]\n for h in height[:-1]:\n offsety.append(offsety[-1] + h + 2)\n return widthnum, heightnum, width, height, offsetx, offsety\n\n\n<mask token>\n\n\ndef list_of_htmlfiles_in_items(itemlist):\n htmlist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n htmlist.append(item.htmname)\n htmlist.extend(list_of_htmlfiles_in_items(item.sublist))\n return htmlist\n\n\ndef list_of_thumbnails(posts, diary=False):\n thumblist = list()\n for post in posts:\n thumblist.extend(list_of_thumbnails_in_items(post.medias))\n if diary is False:\n thumblist.extend(list_of_thumbnails_in_items(post.dcim))\n return thumblist\n\n\ndef list_of_thumbnails_in_items(itemlist):\n thumblist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n thumblist.append(os.path.basename(item.thumb))\n thumblist.extend(list_of_thumbnails_in_items(item.sublist))\n else:\n thumblist.append(os.path.basename(item.thumb))\n return thumblist\n\n\ndef purge_htmlfiles(args, posts):\n \"\"\"\n Purge root dir from irrelevant html files\n \"\"\"\n htmlist = list_of_htmlfiles(args, posts)\n html_to_remove = list()\n for fullname in glob.glob(os.path.join(args.root, '*.htm*')):\n if fullname not in htmlist:\n html_to_remove.append(fullname)\n if len(html_to_remove) > args.thumbnails.threshold_htmlfiles:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(\n f'{len(html_to_remove)} html files to remove. Continue [y|n]? '\n ).lower()\n if inpt == 'n':\n return\n for name in html_to_remove:\n print('Removing html files', name)\n os.remove(name)\n\n\ndef purge_thumbnails(args, thumbdir, posts, diary=False):\n \"\"\"\n Purge thumbnail dir from irrelevant thumbnails\n \"\"\"\n thumblist = list_of_thumbnails(posts, diary)\n thumbs_to_remove = list()\n for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')):\n if os.path.basename(fullname) not in thumblist:\n thumbs_to_remove.append(fullname)\n if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(\n f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? '\n ).lower()\n if inpt == 'n':\n return\n for name in thumbs_to_remove:\n print('Removing thumbnail', name)\n os.remove(name)\n info_fullname = os.path.splitext(name)[0] + '.info'\n if os.path.exists(info_fullname):\n os.remove(info_fullname)\n\n\ndef is_media_within_dates(fullname, dates):\n if is_media(fullname):\n if type(dates) == tuple:\n return dates[0] <= date_from_item(fullname) <= dates[1]\n else:\n return True\n else:\n return False\n\n\ndef sorted_listdir(filelist):\n like_windows_explorer = True\n if not filelist:\n return filelist\n if like_windows_explorer:\n maxlen = max(len(os.path.splitext(name)[0]) for name in filelist)\n\n def keyfunc(name):\n root, ext = os.path.splitext(name.lower())\n return root.ljust(maxlen, ' ') + ext\n else:\n keyfunc = str.lower\n return sorted(filelist, key=keyfunc)\n\n\ndef list_of_files(sourcedir, recursive):\n \"\"\"\n Return the list of full paths for files in source directory\n \"\"\"\n result = list()\n if recursive is False:\n listdir = sorted_listdir(os.listdir(sourcedir))\n if '.nomedia' not in listdir:\n for basename in listdir:\n result.append(os.path.join(sourcedir, basename))\n else:\n for root, dirs, files in os.walk(sourcedir):\n if '.nomedia' not in files:\n for basename in sorted_listdir(files):\n result.append(os.path.join(root, basename))\n return result\n\n\ndef list_of_medias(args, sourcedir, recursive):\n \"\"\"\n Return the list of full paths for pictures and movies in source directory\n \"\"\"\n files = list_of_files(sourcedir, recursive)\n return [_ for _ in files if is_media_within_dates(_, args.dates)]\n\n\n<mask token>\n\n\ndef dispatch_post_items(list_of_post_items):\n subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir]\n medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir]\n return subdirs, medias\n\n\ndef create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax):\n if os.path.isfile(media_fullname):\n if is_image_file(media_fullname):\n return create_item_image(args, media_fullname, sourcedir,\n thumbdir, key, thumbmax)\n else:\n return create_item_video(args, media_fullname, sourcedir,\n thumbdir, key, thumbmax)\n else:\n return create_item_subdir(args, media_fullname, sourcedir, thumbdir,\n key, thumbmax)\n\n\ndef create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax\n ):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n try:\n info, infofmt = get_image_info(media_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize)\n return PostImage(None, media_fullname, '/'.join((args.thumbrep,\n thumb_basename)), thumbsize, infofmt)\n except PIL.UnidentifiedImageError:\n warning('Unable to read image', media_fullname)\n return None\n\n\ndef create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax\n ):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n info_fullname = os.path.splitext(thumb_fullname)[0] + '.info'\n try:\n info, infofmt = get_video_info(media_fullname, info_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_video(args, media_fullname, thumb_fullname,\n thumbsize, duration=info[5])\n return PostVideo(None, media_fullname, '/'.join((args.thumbrep,\n thumb_basename)), thumbsize, infofmt)\n except CalledProcessError:\n warning('Unable to read video', media_fullname)\n return None\n\n\n<mask token>\n\n\ndef relative_name(media_fullname, sourcedir):\n \"\"\"\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg\n -->\n deeper2_deepest_OCT_20000112_000004.jpg\n\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest\n -->\n deeper2_deepest\n \"\"\"\n x = os.path.relpath(media_fullname, sourcedir)\n x = x.replace('\\\\', '_').replace('/', '_').replace('#', '_')\n return x\n\n\ndef make_posts(args, dirname):\n if args.diary is True:\n if not args.sourcedir:\n return make_posts_from_diary(args)\n else:\n return make_posts_from_diary_and_dir(args)\n elif args.bydate is False:\n return make_posts_from_subdir(args, dirname)\n else:\n return make_posts_from_subdir_and_date(args, dirname)\n\n\ndef make_posts_from_diary(args):\n md_filename = os.path.join(args.root, 'index.md')\n if os.path.exists(md_filename):\n title, posts = parse_markdown(md_filename)\n else:\n error('File not found', md_filename)\n for post in posts:\n for media in post.medias:\n media_fullname = os.path.join(args.root, media.uri)\n item = create_item(args, media_fullname, args.root, args.\n thumbdir, 'post', 400)\n media.thumb = item.thumb\n media.thumbsize = item.thumbsize\n media.descr = item.descr\n return title, posts\n\n\ndef create_items_by_date(args, medias, posts):\n if args.dates == 'diary':\n required_dates = {post.date for post in posts}\n else:\n required_dates = {date_from_item(media) for media in medias}\n if type(args.dates) == tuple:\n date1, date2 = args.dates\n required_dates = {date for date in required_dates if date1 <=\n date <= date2}\n bydate = defaultdict(list)\n for media_fullname in medias:\n date = date_from_item(media_fullname)\n if date in required_dates:\n item = create_item(args, media_fullname, args.sourcedir, args.\n thumbdir, 'dcim', 300)\n if item:\n bydate[date].append(item)\n for date, liste in bydate.items():\n liste.sort(key=lambda item: time_from_item(item.uri))\n return bydate\n\n\n<mask token>\n\n\ndef make_posts_from_subdir(args, dirname):\n if args.bydir is False:\n medias_ext = list_of_medias(args, dirname, args.recursive)\n else:\n medias_ext = list_of_medias_ext(args, dirname)\n postmedias = list()\n for item in medias_ext:\n postmedia = create_item(args, item, args.sourcedir, args.thumbdir,\n 'dcim', 300)\n if postmedia is not None:\n postmedias.append(postmedia)\n post = Post(date='00000000', text='', medias=[])\n post.dcim = postmedias\n posts = [post]\n title = os.path.basename(args.sourcedir) or os.path.splitdrive(args.\n sourcedir)[0]\n return title, posts\n\n\ndef make_posts_from_subdir_and_date(args, dirname):\n if args.bydir is False:\n medias = list_of_medias(args, dirname, args.recursive)\n subdirs = []\n else:\n medias_ext = list_of_medias_ext(args, dirname)\n medias = [_ for _ in medias_ext if is_media(_)]\n subdirs = [_ for _ in medias_ext if not is_media(_)]\n posts = list()\n items = list()\n for media_fullname in subdirs:\n item = create_item(args, media_fullname, args.sourcedir, args.\n thumbdir, 'dcim', 300)\n if item:\n items.append(item)\n if items:\n post = Post(date='00000000', text='', medias=[])\n post.dcim = items\n posts.append(post)\n bydate = create_items_by_date(args, medias, posts)\n for date in sorted(bydate):\n post = Post.from_date(date)\n post.dcim = bydate[post.date]\n posts.append(post)\n title = os.path.basename(args.sourcedir) or os.path.splitdrive(args.\n sourcedir)[0]\n return title, posts\n\n\ndef create_gallery(args):\n title, posts = make_posts(args, args.sourcedir)\n print_html(args, posts, title, os.path.join(args.dest, args.rootname),\n 'regular')\n purge_htmlfiles(args, posts)\n if args.diary and not args.sourcedir:\n purge_thumbnails(args, args.thumbdir, posts, diary=True)\n else:\n purge_thumbnails(args, args.thumbdir, posts)\n\n\ndef create_diary(args):\n medias = list_of_medias(args, args.sourcedir, args.recursive)\n if args.dates == 'diary':\n assert 0\n else:\n required_dates = {date_from_item(media) for media in medias}\n if type(args.dates) == tuple:\n date1, date2 = args.dates\n required_dates = {date for date in required_dates if date1 <=\n date <= date2}\n title = args.sourcedir\n posts = list()\n for date in sorted(required_dates):\n posts.append(Post.from_date(date))\n os.makedirs(args.root, exist_ok=True)\n print_markdown(posts, title, os.path.join(args.root, 'index.md'))\n\n\ndef online_images_url(args):\n try:\n if args.urlblogger.startswith('http:') or args.urlblogger.startswith(\n 'https:'):\n with urlopen(args.urlblogger) as u:\n buffer = u.read()\n else:\n with open(args.urlblogger, 'rb') as f:\n buffer = f.read()\n except:\n error('Unable to read url', args.urlblogger)\n buffer = buffer.decode('utf-8')\n online_images = dict()\n for match in re.finditer('<div class=\"separator\"((?!<div).)*?</div>',\n buffer, flags=re.DOTALL):\n div_separator = match.group(0)\n div_separator = div_separator.replace('&nbsp;', '')\n elem_div = objectify.fromstring(div_separator)\n for elem_a in elem_div.iterchildren(tag='a'):\n href = elem_a.get('href')\n thumb = elem_a.img.get('src')\n online_images[os.path.basename(href)] = href, thumb\n online_videos = list()\n for match in re.finditer(\n '<iframe allowfullscreen=\"allowfullscreen\".*?</iframe>', buffer,\n flags=re.DOTALL):\n iframe = match.group(0)\n online_videos.append(iframe)\n return online_images, online_videos\n\n\ndef compare_image_buffers(imgbuf1, imgbuf2):\n \"\"\"\n return True if images read on file are identical, False otherwise\n \"\"\"\n with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2:\n img1 = Image.open(imgio1)\n img2 = Image.open(imgio2)\n diff = ImageChops.difference(img1, img2)\n return not diff.getbbox()\n\n\ndef check_images(args, posts, online_images):\n result = True\n for post in posts:\n for media in post.medias:\n if type(media) is PostImage:\n if media.basename in online_images:\n with open(os.path.join(args.root, media.uri), 'rb') as f:\n imgbuf1 = f.read()\n try:\n with urlopen(online_images[media.basename][0]) as u:\n imgbuf2 = u.read()\n except FileNotFoundError:\n print('File not found', online_images[media.\n basename][0])\n next\n if compare_image_buffers(imgbuf1, imgbuf2) is False:\n print('Files are different, upload', media.basename)\n elif 1:\n print('File already online', media.basename)\n else:\n print('File is absent, upload', media.basename)\n result = False\n elif type(media) is PostVideo:\n print('Video not checked', media.basename)\n else:\n assert False\n return result\n\n\ndef compose_blogger_html(args, title, posts, imgdata, online_videos):\n \"\"\" Compose html with blogger image urls\n \"\"\"\n for post in posts:\n for media in post.medias:\n if type(media) is PostImage:\n if media.uri not in imgdata:\n print('Image missing: ', media.uri)\n else:\n img_url, resized_url = imgdata[media.uri]\n media.uri = img_url\n media.resized_url = resized_url\n elif type(media) is PostVideo:\n if not online_videos:\n print('Video missing: ', media.uri)\n else:\n media.iframe = online_videos[0]\n del online_videos[0]\n else:\n assert False\n return print_html(args, posts, title, '', target='blogger')\n\n\ndef prepare_for_blogger(args):\n \"\"\"\n Export blogger html to clipboard.\n If --full, export complete html, otherwise export html extract ready to\n paste into blogger edit mode.\n \"\"\"\n title, posts = parse_markdown(os.path.join(args.root, 'index.md'))\n online_images, online_videos = online_images_url(args)\n if args.check_images and check_images(args, posts, online_images) is False:\n pass\n html = compose_blogger_html(args, title, posts, online_images,\n online_videos)\n if args.full is False:\n html = re.search('<body>(.*)?</body>', html, flags=re.DOTALL).group(1)\n html = re.sub('<script>.*?</script>', '', html, flags=re.DOTALL)\n html = STYLE.replace('%%', '%') + html\n if args.dest:\n with open(args.dest, 'wt', encoding='utf-8') as f:\n f.write(html)\n else:\n clipboard.copy(html)\n\n\ndef idempotence(args):\n \"\"\"\n For testing identity between a diary file and the fle obtained after reading\n and printing it. See testing.\n \"\"\"\n title, posts = parse_markdown(os.path.join(args.root, 'index.md'))\n print_markdown(posts, title, os.path.join(args.dest, 'index.md'))\n\n\n<mask token>\n\n\nclass MyConfigParser(ConfigParser):\n \"\"\"Add input checking.\"\"\"\n\n def __init__(self):\n ConfigParser.__init__(self, inline_comment_prefixes=(';',))\n\n def error(self, section, entry):\n error('Missing or incorrect config value:', '[%s]%s' % (section, entry)\n )\n\n def getint(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getint(self, section, entry)\n else:\n return ConfigParser.getint(self, section, entry, raw=True,\n vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n def getboolean(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getboolean(self, section, entry)\n else:\n return ConfigParser.getboolean(self, section, entry, raw=\n True, vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n\ndef configfilename(params):\n return os.path.join(params.root, '.config.ini')\n\n\ndef createconfig(config_filename):\n with open(config_filename, 'wt') as f:\n f.writelines(CONFIG_DEFAULTS)\n\n\ndef read_config(params):\n config_filename = configfilename(params)\n try:\n if not os.path.exists(config_filename) or params.resetcfg:\n createconfig(config_filename)\n except:\n error('Error creating configuration file')\n try:\n getconfig(params, config_filename)\n except Exception as e:\n error('Error reading configuration file.', str(e), 'Use --resetcfg')\n\n\ndef getconfig(options, config_filename):\n\n\n class Section:\n pass\n options.source = Section()\n options.thumbnails = Section()\n options.photobox = Section()\n config = MyConfigParser()\n config.read(config_filename)\n options.source.sourcedir = config.get('source', 'sourcedir')\n options.source.bydir = config.getboolean('source', 'bydir')\n options.source.bydate = config.getboolean('source', 'bydate')\n options.source.diary = config.getboolean('source', 'diary')\n options.source.recursive = config.getboolean('source', 'recursive')\n options.source.dates = config.get('source', 'dates')\n options.source.github_pages = config.getboolean('source',\n 'github_pages', default=False)\n options.thumbnails.media_description = config.getboolean('thumbnails',\n 'media_description')\n options.thumbnails.subdir_caption = config.getboolean('thumbnails',\n 'subdir_caption')\n options.thumbnails.thumbdelay = config.getint('thumbnails', 'thumbdelay')\n options.thumbnails.threshold_thumbs = config.getint('thumbnails',\n 'threshold_thumbs')\n options.thumbnails.threshold_htmlfiles = config.getint('thumbnails',\n 'threshold_htmlfiles', default=3)\n options.photobox.loop = config.getboolean('photobox', 'loop')\n options.photobox.thumbs = config.getboolean('photobox', 'thumbs')\n options.photobox.autoplay = config.getboolean('photobox', 'autoplay')\n options.photobox.time = config.getint('photobox', 'time')\n options.photobox.zoomable = config.getboolean('photobox', 'zoomable')\n options.photobox.rotatable = config.getboolean('photobox', 'rotatable')\n options.photobox.wheelNextPrev = config.getboolean('photobox',\n 'wheelNextPrev')\n\n\ndef setconfig(cfgname, section, key, value):\n config = MyConfigParser()\n config.read(cfgname)\n config.set(section, key, value)\n with open(cfgname, 'wt') as configfile:\n config.write(configfile)\n\n\ndef setconfig_cmd(args):\n config_filename = configfilename(args)\n setconfig(config_filename, *args.setcfg)\n\n\ndef update_config(args):\n updates = ('sourcedir', args.sourcedir), ('bydir', BOOL[args.bydir]), (\n 'bydate', BOOL[args.bydate]), ('diary', BOOL[args.diary]), ('recursive'\n , BOOL[args.recursive]), ('dates', args.dates), ('github_pages',\n BOOL[args.github_pages])\n cfgname = configfilename(args)\n with open(cfgname) as f:\n cfglines = [_.strip() for _ in f.readlines()]\n for key, value in updates:\n for iline, line in enumerate(cfglines):\n if line.startswith(key):\n cfglines[iline] = f'{key} = {value}'\n break\n with open(cfgname, 'wt') as f:\n for line in cfglines:\n print(line, file=f)\n\n\ndef warning(*msg):\n print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + ' '.join(msg),\n colorama.Style.RESET_ALL)\n\n\n<mask token>\n\n\ndef errorcode(msg):\n return ERRORS.splitlines().index(msg) + 1\n\n\ndef error(*msg):\n print(colorama.Fore.RED + colorama.Style.BRIGHT + ' '.join(msg),\n colorama.Style.RESET_ALL)\n sys.exit(errorcode(msg[0]))\n\n\n<mask token>\n\n\ndef parse_command_line(argstring):\n parser = argparse.ArgumentParser(description=None, usage=USAGE)\n agroup = parser.add_argument_group('Commands')\n xgroup = agroup.add_mutually_exclusive_group()\n xgroup.add_argument('--gallery', help='source in --sourcedir', action=\n 'store', metavar='<root-dir>')\n agroup.add_argument('--update', help=\n 'updates gallery with parameters in config file', action='store',\n metavar='<root-dir>')\n xgroup.add_argument('--create', help=\n 'create journal from medias in --sourcedir', action='store',\n metavar='<root-dir>')\n xgroup.add_argument('--resetcfg', help='reset config file to defaults',\n action='store', metavar='<root-dir>')\n xgroup.add_argument('--setcfg', help=argparse.SUPPRESS, action='store',\n nargs=4, metavar='<root-dir>')\n xgroup.add_argument('--idem', help=argparse.SUPPRESS, action='store',\n metavar='<root-dir>')\n xgroup.add_argument('--blogger', help=\n 'input md, html blogger ready in clipboard', action='store',\n metavar='<root-dir>')\n agroup = parser.add_argument_group('Parameters')\n agroup.add_argument('--bydir', help='organize gallery by subdirectory',\n action='store', default=None, choices=BOOL)\n agroup.add_argument('--bydate', help='organize gallery by date', action\n ='store', default=None, choices=BOOL)\n agroup.add_argument('--diary', help=\n 'organize gallery using markdown file diary', action='store',\n default=None, choices=BOOL)\n agroup.add_argument('--recursive', help='--sourcedir scans recursively',\n action='store', default=None, choices=BOOL)\n agroup.add_argument('--dates', help='dates interval', action='store',\n default=None)\n agroup.add_argument('--sourcedir', help='media directory', action=\n 'store', default=None)\n agroup.add_argument('--github_pages', help='github Pages compatibility',\n action='store', default=None, choices=BOOL)\n agroup.add_argument('--dest', help='output directory', action='store')\n agroup.add_argument('--forcethumb', help=\n 'force calculation of thumbnails', action='store_true', default=False)\n agroup.add_argument('--full', help=\n 'full html (versus blogger ready html)', action='store_true',\n default=False)\n agroup.add_argument('--check', dest='check_images', help=\n 'check availability of medias on blogger', action='store_true')\n agroup.add_argument('--url', dest='urlblogger', help='blogger post url',\n action='store')\n if argstring is None:\n print('Type \"galerie -h\" for help')\n sys.exit(1)\n else:\n args = parser.parse_args(argstring.split())\n if args.update and (args.bydir or args.bydate or args.diary or args.\n sourcedir or args.recursive or args.dates or args.github_pages):\n error('Incorrect parameters:',\n '--update cannot be used with creation parameters, use explicit command'\n )\n args.bydir = args.bydir == 'true'\n args.bydate = args.bydate == 'true'\n args.diary = args.diary == 'true'\n args.recursive = args.recursive == 'true'\n args.dates = 'source' if args.dates is None else args.dates\n args.github_pages = args.github_pages == 'true'\n args.root = (args.create or args.gallery or args.update or args.blogger or\n args.idem or args.resetcfg)\n if args.setcfg:\n args.root = args.setcfg[0]\n args.setcfg = args.setcfg[1:]\n return args\n\n\ndef setup_part1(args):\n \"\"\"\n Made before reading config file (config file located in args.root).\n Check and normalize root path.\n \"\"\"\n args.rootarg = args.root\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext == '':\n pass\n else:\n args.root = os.path.dirname(args.root)\n if args.root:\n args.root = os.path.abspath(args.root)\n if not os.path.isdir(args.root):\n if args.gallery:\n os.mkdir(args.root)\n else:\n error('Directory not found', args.root)\n\n\ndef setup_part2(args):\n \"\"\"\n Made after reading config file.\n Check for ffmpeg in path.\n Create .thumbnails dir if necessary and create .nomedia in it.\n Copy photobox file to destination dir.\n Handle priority between command line and config file.\n \"\"\"\n if args.update:\n args.sourcedir = args.source.sourcedir\n args.bydir = args.source.bydir\n args.bydate = args.source.bydate\n args.diary = args.source.diary\n args.recursive = args.source.recursive\n args.dates = args.source.dates\n args.github_pages = args.source.github_pages\n elif args.gallery:\n args.source.sourcedir = args.sourcedir\n args.source.bydir = args.bydir\n args.source.bydate = args.bydate\n args.source.diary = args.diary\n args.source.recursive = args.recursive\n args.source.dates = args.dates\n args.source.github_pages = args.github_pages\n update_config(args)\n if args.github_pages:\n args.html_suffix = '.html'\n else:\n args.html_suffix = '.htm'\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext:\n args.rootname = os.path.basename(args.rootarg)\n else:\n args.rootname = 'index' + args.html_suffix\n if args.sourcedir:\n args.sourcedir = os.path.abspath(args.sourcedir)\n if os.path.splitdrive(args.sourcedir)[0]:\n drive, rest = os.path.splitdrive(args.sourcedir)\n args.sourcedir = drive.upper() + rest\n if not os.path.isdir(args.sourcedir):\n error('Directory not found', args.sourcedir)\n elif args.gallery and args.diary is False and args.update is None:\n error('Directory not found', 'Use --sourcedir')\n if args.dest:\n args.dest = os.path.abspath(args.dest)\n if args.dest is None:\n args.dest = args.root\n if args.blogger and args.urlblogger is None:\n error('No blogger url (--url)')\n if args.gallery or args.update:\n for exe in ('ffmpeg', 'ffprobe'):\n try:\n check_output([exe, '-version'])\n except FileNotFoundError:\n error('File not found', exe)\n if args.github_pages:\n args.thumbrep = 'thumbnails'\n else:\n args.thumbrep = '.thumbnails'\n args.thumbdir = os.path.join(args.dest, args.thumbrep)\n if not os.path.exists(args.thumbdir):\n os.mkdir(args.thumbdir)\n open(os.path.join(args.thumbdir, '.nomedia'), 'a').close()\n favicondst = os.path.join(args.dest, 'favicon.ico')\n if not os.path.isfile(favicondst):\n faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico')\n shutil.copyfile(faviconsrc, favicondst)\n photoboxdir = os.path.join(args.dest, 'photobox')\n if not os.path.exists(photoboxdir):\n photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox')\n shutil.copytree(photoboxsrc, photoboxdir)\n if args.dates:\n if not (args.gallery or args.create):\n pass\n if args.dates == 'source':\n pass\n elif args.dates == 'diary':\n if args.create:\n error('Incorrect date format', args.dates)\n elif re.match('\\\\d+-\\\\d+', args.dates):\n date1, date2 = args.dates.split('-')\n if validate_date(date1) and validate_date(date2):\n args.dates = date1, date2\n else:\n error('Incorrect date format', args.dates)\n else:\n error('Incorrect date format', args.dates)\n\n\ndef main(argstring=None):\n colorama.init()\n args = parse_command_line(argstring)\n setup_part1(args)\n read_config(args)\n setup_part2(args)\n try:\n if args.gallery or args.update:\n create_gallery(args)\n elif args.create:\n create_diary(args)\n elif args.blogger:\n prepare_for_blogger(args)\n elif args.idem:\n idempotence(args)\n elif args.setcfg:\n setconfig_cmd(args)\n except KeyboardInterrupt:\n warning('Interrupted by user.')\n\n\n<mask token>\n", "step-5": "\"\"\"\nMake html galleries from media directories. Organize by dates, by subdirs or by\nthe content of a diary file. The diary file is a markdown file organized by\ndates, each day described by a text and some medias (photos and movies).\n\nThe diary file can be exported to:\n* an html file with the text and subset of medias associated with each day,\n* the previous html file extended with all medias in the media directory,\n* an html file ready to import into Blogger.\n\"\"\"\n\n\nimport sys\nimport os\nimport argparse\nimport glob\nimport shutil\nimport re\nimport io\nimport bisect\nimport locale\nimport textwrap\nimport base64\nimport datetime\nimport urllib\n\nfrom configparser import ConfigParser\nfrom collections import defaultdict\nfrom subprocess import check_output, CalledProcessError, STDOUT\nfrom urllib.request import urlopen\n\nimport colorama\nimport clipboard\nimport PIL\nfrom PIL import Image, ImageChops\nfrom lxml import objectify\nimport markdown\n\n\nUSAGE = \"\"\"\ngalerie --gallery <root-dir> [--sourcedir <media-dir>]\n [--bydir true|false*]\n [--bydate true|false*]\n [--diary true|false*]\n [--recursive true|false*]\n [--dates source*|diary|<yyyymmdd-yyyymmdd>]\n [--github_pages true|false]\n [--dest <directory>]\n [--forcethumb]\ngalerie --update <root-dir>\ngalerie --create <root-dir> --sourcedir <media-dir>\n [--recursive true|false*]\n [--dates source*|<yyyymmdd-yyyymmdd>]\ngalerie --blogger <root-dir> --url <url>\n [--check]\n [--full]\n [--dest <filename>]\n\nNotes:\n - * gives default\n - all options can be abbreviated if there is no conflict with other options (--gallery --> --gal)\n\n\"\"\"\n\n\n# -- Post objects -------------------------------------------------------------\n\n\nCAPTION_IMAGE_STYLE = '''\\\n<style type=\"text/css\">\n span { display:inline-table; }\n </style>\\\n'''\n\nSTYLE = '''\\\n<style type=\"text/css\">\n p { margin-top:0px; margin-bottom:0px; }\n h3 { font-size: 100%%; font-weight: bold; margin-top:0px; margin-bottom:0px; }\n </style>\n'''\n\nSTART = f'''\\\n<html>\n\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n <title>%s</title>\n <link rel=\"icon\" href=\"favicon.ico\" />\n <meta name=\"viewport\" content=\"width=device-width\">\n <link rel=\"stylesheet\" href=\"photobox/photobox.css\">\n <script src=\"photobox/jquery.min.js\"></script>\n <script src=\"photobox/jquery.photobox.js\"></script>\n{CAPTION_IMAGE_STYLE}\n{STYLE}\n</head>\n\n<body>\\\n'''\n\nBUTTONS = '''\\\n<button id=\"btn_full\" type=\"button\" style=\"position: fixed; width: 50px; top: 20px; right: 20px; background-color:white\">Full</button>\n<button id=\"btn_blog\" type=\"button\" style=\"position: fixed; width: 50px; top: 40px; right: 20px; background-color:white\">Diary</button>\n<button id=\"btn_text\" type=\"button\" style=\"position: fixed; width: 50px; top: 60px; right: 20px; background-color:white\">Text</button>\n\n<script>\n$('#btn_full').click(function() {\n $(\"[id^=gallery-blog]\").show();\n $(\"[id^=gallery-dcim]\").show();\n $(\"div.extra\").show();\n});\n$('#btn_text').click(function() {\n $(\"[id^=gallery-blog]\").hide();\n $(\"[id^=gallery-dcim]\").hide();\n $(\"div.extra\").hide();\n});\n$('#btn_blog').click(function() {\n $(\"[id^=gallery-blog]\").show();\n $(\"[id^=gallery-dcim]\").hide();\n $(\"div.extra\").hide();\n});\n</script>\n'''\n\nSUBDIR_BACKCOL = '#eee'\nEND = '</body>\\n</html>'\nSEP = '<hr color=\"#C0C0C0\" size=\"1\" />'\nIMGPOST = '<a href=\"%s\"><img src=\"%s\" width=\"%d\" height=\"%d\" title=\"%s\"/></a>'\nVIDPOST = '<a href=\"%s\" rel=\"video\"><img src=\"%s\" width=\"%d\" height=\"%d\" title=\"%s\"/></a>'\nIMGPOSTCAPTION = '''\\\n<span>\n<a href=\"%s\"><img src=%s width=\"%d\" height=\"%d\" title=\"%s\"/></a>\n<p>%s</p>\n</span>\n'''\nVIDPOSTCAPTION = '''\\\n<span>\n<a href=\"%s\" rel=\"video\"><img src=%s width=\"%d\" height=\"%d\" title=\"%s\"/></a>\n<p>%s</p>\n</span>\n'''\nIMGDCIM = '<a href=\"%s\"><img src=\"%s\" width=\"%d\" height=\"%d\" title=\"%s\"/></a>'\nVIDDCIM = '<a href=\"%s\" rel=\"video\"><img src=\"%s\" width=\"%d\" height=\"%d\" title=\"%s\"/></a>'\n\n# diminution de l'espace entre images, on utilise :\n# \"display: block;\", \"margin-bottom: 0em;\" et \"font-size: 0;\"\n# \"display: block;\" dans img : espacement correct ordi mais pas centré téléphone\n# \"display: block;\" dans a : ok\n\nDIRPOST = '<a href=\"%s\"><img src=\"%s\" width=\"%d\" height=\"%d\" style=\"border: 1px solid #C0C0C0;\" /></a>'\nDIRPOSTCAPTION = f'''\n<span style=\"background-color:{SUBDIR_BACKCOL}; margin-bottom: 8px; border: 1px solid #C0C0C0;\">\n<a href=\"%s\"><img src=\"%s\" width=\"%d\" height=\"%d\" style=\"border: 1px solid #C0C0C0;\" /></a>\n<p style=\"margin-left:2px;\">%s</p>\n</span>\n'''\nBIMGPAT = '''\\\n<div class=\"separator\" style=\"clear: both; text-align: center;\">\n<a href=\"%s\" style=\"clear: left; margin-bottom: 0em; margin-right: 1em; font-size: 0; display: block;\">\n<img border=\"0\" src=\"%s\" width=\"640\" />\n</a></div>\n'''\nCAPTION_PAT = '''\\\n<div class=\"separator\" style=\"clear: both; text-align: center;\">\n%s\n</div>\n'''\n\n\nclass Post:\n def __init__(self, date, text, medias):\n # date: yyyymmdd\n self.date = date\n self.text = text\n self.medias = medias\n self.dcim = []\n self.daterank = 0\n self.extra = False\n\n def __lt__(self, other):\n return self.date < other.date\n\n @classmethod\n def from_markdown(cls, post):\n m = re.match(r'\\[(\\d\\d\\d\\d/\\d\\d/\\d\\d)\\]\\n*', post[0])\n if m:\n date = m.group(1).replace('/', '')\n if not validate_date(date):\n error('Incorrect date value:', date)\n del post[0]\n else:\n error('No date in post', ' '.join(post))\n\n while post and not post[0].strip():\n del post[0]\n\n text = ''\n while post and not re.match(r'!?\\[\\]', post[0]):\n text += post[0]\n del post[0]\n\n # remove empty lines at end\n text = re.sub(r'\\n\\n$', '\\n', text)\n\n medias = list()\n while post and (match := re.match(r'!?\\[\\]\\((.*)\\)', post[0])):\n media = match.group(1)\n caption = None\n del post[0]\n if post and not re.match(r'!?\\[\\]', post[0]):\n caption = post[0].strip()\n del post[0]\n if match.group(0)[0] == '!':\n medias.append(PostImage(caption, media))\n else:\n medias.append(PostVideo(caption, media))\n\n return cls(date, text, medias)\n\n @classmethod\n def from_date(cls, date):\n dt = datetime.datetime.strptime(date, '%Y%m%d')\n datetext = dt.strftime(\"%A %d %B %Y\").capitalize()\n post = cls(date, text=datetext, medias=[])\n post.daterank = 1\n return post\n\n def to_html(self, args, target='regular'):\n if target == 'regular':\n if args.diary:\n return self.to_html_diary(args)\n else:\n return self.to_html_regular(args)\n if target == 'blogger':\n return self.to_html_blogger()\n\n def to_html_regular(self, args):\n html = list()\n if self.text:\n # possible with --bydate\n html.append(markdown.markdown(self.text))\n subdirs, dcim = dispatch_post_items(self.dcim)\n if self.dcim:\n html.append(SEP)\n for media in subdirs:\n html.append(media.to_html_dcim(args))\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n\n html.append(SEP)\n return html\n\n def to_html_diary(self, args):\n html = list()\n if self.extra:\n html.append('<div class=\"extra\">')\n\n if self.text:\n html.append(markdown.markdown(self.text))\n\n if self.medias:\n html.append(f'<div id=\"gallery-blog-{self.date}-{self.daterank}\">')\n for media in self.medias:\n html.append(media.to_html_post(args))\n html.append('</div>')\n\n _, dcim = dispatch_post_items(self.dcim)\n if dcim:\n html.append(f'<div id=\"gallery-dcim-{self.date}-{self.daterank}\">')\n html.append(SEP)\n for media in dcim:\n html.append(media.to_html_dcim(args))\n html.append('</div>')\n\n html.append(SEP)\n if self.extra:\n html.append('</div>')\n return html\n\n def to_html_blogger(self):\n html = list()\n html.append(markdown.markdown(self.text))\n for image in self.medias:\n html.append(image.to_html_blogger())\n html.append(SEP)\n return html\n\n\nclass PostItem:\n def __init__(self, caption, uri, thumb=None, thumbsize=None, descr=''):\n self.caption = caption\n self.uri = uri\n self.basename = os.path.basename(uri)\n self.thumb = thumb\n self.thumbsize = thumbsize\n self.descr = descr\n self.resized_url = None\n\n\nclass PostImage(PostItem):\n def to_markdown(self):\n if not self.caption:\n return '![](%s)' % (self.uri,)\n else:\n return '![](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return IMGPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return IMGPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return IMGDCIM % (relative_url(self.uri, args.root), self.thumb, *self.thumbsize, descr)\n\n def to_html_blogger(self):\n if not self.caption:\n return BIMGPAT % (self.uri, self.resized_url)\n else:\n return f'{BIMGPAT}\\n{CAPTION_PAT}' % (self.uri, self.resized_url, self.caption)\n\n\nclass PostVideo(PostItem):\n def to_markdown(self):\n if not self.caption:\n return '[](%s)' % (self.uri,)\n else:\n return '[](%s)\\n%s' % (self.uri, self.caption)\n\n def to_html_post(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n if not self.caption:\n return VIDPOST % (self.uri, self.thumb, *self.thumbsize, descr)\n else:\n return VIDPOSTCAPTION % (self.uri, self.thumb, *self.thumbsize, descr, self.caption)\n\n def to_html_dcim(self, args):\n descr = self.descr if args.thumbnails.media_description else ''\n return VIDDCIM % (relative_url(self.uri, args.root), self.thumb, *self.thumbsize, descr)\n\n def to_html_blogger(self):\n x = f'<p style=\"text-align: center;\">{self.iframe}</p>'\n if not self.caption:\n return x\n else:\n return f'%s\\n{CAPTION_PAT}' % (x, self.caption)\n\n\nclass PostSubdir(PostItem):\n def to_html_dcim(self, args):\n basename = os.path.basename(self.htmname)\n posts = self.posts\n title = self.caption\n print_html(args, posts, title, self.htmname)\n\n if not self.caption:\n return DIRPOST % (basename, self.thumb, *self.thumbsize)\n else:\n return DIRPOSTCAPTION % (basename, self.thumb, *self.thumbsize, self.caption)\n\n\ndef relative_url(path, root):\n \"\"\"\n returns a normalized url to path relative from root\n \"\"\"\n try:\n url = os.path.relpath(path, root)\n except:\n error('Unable to make a relative url:', url, root)\n\n url = url.replace('\\\\', '/') if os.sep == '\\\\' else url\n\n return urllib.parse.quote(url)\n\n\n# -- Markdown parser ----------------------------------------------------------\n\n\ndef parse_markdown(filename):\n \"\"\"\n Generate Post objects from markdown. Date must be present in each post and\n posts must be ordrered by date.\n \"\"\"\n if not os.path.exists(filename):\n error('File not found', filename)\n\n posts = list()\n with open(filename, encoding='utf-8') as f:\n line = next(f)\n if line.startswith('# '):\n title = line[2:].strip()\n record = []\n next(f)\n else:\n title = None\n record = [line]\n for line in f:\n if not line.startswith('___'):\n record.append(line)\n else:\n posts.append(Post.from_markdown(record))\n record = []\n\n # set rank of posts in date\n daterank = defaultdict(int)\n for post in posts:\n daterank[post.date] += 1\n post.daterank = daterank[post.date]\n\n # check post order\n for post1, post2 in zip(posts[:-1], posts[1:]):\n if post1.date > post2.date:\n error('Posts are not ordered', f'{post1.date} > {post2.date}')\n\n return title, posts\n\n\n# -- Markdown printer ---------------------------------------------------------\n\n\ndef print_markdown(posts, title, fullname):\n with open(fullname, 'wt', encoding='utf-8') as fdst:\n print(f'# {title}\\n', file=fdst)\n for post in posts:\n date = f'[{post.date[0:4]}/{post.date[4:6]}/{post.date[6:8]}]'\n print(date, file=fdst)\n if post.text:\n print(file=fdst)\n for line in post.text.splitlines():\n if not line:\n print(file=fdst)\n else:\n for chunk in textwrap.wrap(line, width=78):\n print(chunk, file=fdst)\n if post.medias:\n print(file=fdst)\n for media in post.medias:\n print(media.to_markdown(), file=fdst)\n print('______', file=fdst)\n\n\n# -- html printer -------------------------------------------------------------\n\n\ndef compose_html_reduced(args, posts, title, target):\n html = list()\n html.append(START % title)\n\n for post in posts:\n for line in post.to_html(args, target):\n html.append(line.strip())\n html.append('')\n\n html.append(END)\n return html\n\n\ndef compose_html_full(args, posts, title, target):\n html = list()\n html.append(START % title)\n\n if args.diary:\n html.append(BUTTONS)\n\n for post in posts:\n for line in post.to_html(args, target):\n html.append(line.strip())\n html.append('')\n\n html.append('<script>')\n for post in posts:\n if post.medias:\n gallery_id = f'gallery-blog-{post.date}-{post.daterank}'\n html.append(gallery_call(args, gallery_id))\n if post.dcim:\n gallery_id = f'gallery-dcim-{post.date}-{post.daterank}'\n html.append(gallery_call(args, gallery_id))\n html.append('</script>')\n\n html.append(END)\n return html\n\n\ndef print_html_to_stream(args, posts, title, stream, target):\n if target == 'regular':\n for line in compose_html_full(args, posts, title, target):\n print(line, file=stream)\n else:\n for line in compose_html_reduced(args, posts, title, target):\n print(line, file=stream)\n\n\ndef print_html(args, posts, title, html_name, target='regular'):\n assert target in ('regular', 'blogger')\n with io.StringIO() as f:\n print_html_to_stream(args, posts, title, f, target)\n html = f.getvalue()\n\n if html_name:\n if os.path.exists(html_name):\n # test if the generated html is identical to the one already on disk\n with open(html_name, 'rt', encoding='utf-8') as f:\n html0 = f.read()\n if html == html0:\n return None\n with open(html_name, 'wt', encoding='utf-8') as f:\n f.write(html)\n return None\n else:\n return html\n\n\nGALLERYCALL = \"\"\"\n$('#%s').photobox('a', {\nloop:%s,\nthumbs:%s,\nautoplay:%s,\ntime:%d,\nzoomable:%s ,\nrotatable:%s,\nwheelNextPrev:%s\n});\n\"\"\"\n\n\ndef gallery_call(args, gallery_id):\n return GALLERYCALL.replace('\\n', '') % (\n gallery_id,\n str(args.photobox.loop).lower(),\n str(args.photobox.thumbs).lower(),\n str(args.photobox.autoplay).lower(),\n args.photobox.time,\n str(args.photobox.zoomable).lower(),\n str(args.photobox.rotatable).lower(),\n str(args.photobox.wheelNextPrev).lower(),\n )\n\n\n# -- Media description --------------------------------------------------------\n\n\ndef is_image_file(name):\n return os.path.splitext(name)[1].lower() in (\n '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tif'\n )\n\n\ndef is_video_file(name):\n return os.path.splitext(name)[1].lower() in (\n '.mp4', '.webm', '.mkv', '.flv', '.m4v', '.avi', '.wmv', '.mts', '.vob', '.divx'\n )\n\n\ndef is_media(name):\n return is_image_file(name) or is_video_file(name)\n\n\ndef validate_date(datestr):\n # datestr = yyyymmdd\n try:\n datetime.datetime.strptime(datestr, '%Y%m%d')\n return True\n except ValueError:\n return False\n\n\ndef date_from_name(name):\n # heuristics\n if match := re.search(r'(?:\\D|^)(\\d{8})(?:\\D|$)', name, re.ASCII):\n digits = match.group(1)\n if validate_date(digits):\n return digits\n return None\n\n\ndef date_from_item(filename):\n if date := date_from_name(filename):\n return date\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%Y%m%d')\n\n\ndef time_from_name(name):\n # heuristics\n if match := re.search(r'(?:\\D|^)(\\d{8})\\D(\\d{6})(?:\\D|$)', name, re.ASCII):\n digits = match.group(2)\n hour, minute, second = int(digits[0:2]), int(digits[2:4]), int(digits[4:6])\n if 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60:\n return digits\n return None\n\n\ndef time_from_item(filename):\n if time := time_from_name(filename):\n return time\n else:\n timestamp = os.path.getmtime(filename)\n return datetime.datetime.fromtimestamp(timestamp).strftime('%H%M%S')\n\n\nFFPROBE_CMD = '''\\\n ffprobe -v error\n -select_streams v:0\n -show_entries stream=width,height,avg_frame_rate,r_frame_rate:format=duration\n -of csv=p=0\n'''\n\n\ndef get_image_info(filename):\n date = date_from_item(filename)\n time = time_from_item(filename)\n img = Image.open(filename)\n width, height = img.size\n size = round(os.path.getsize(filename) / 1e6, 1)\n return (date, time, width, height, size), f'{date} {time}, dim={width}x{height}, {size} MB'\n\n\ndef get_video_info(filename, info_fullname):\n if os.path.exists(info_fullname):\n with open(info_fullname) as f:\n info = f.readline().split()\n date, time, width, height, size, duration, fps = info[0], info[1], int(info[2]), int(info[3]), float(info[4]), int(info[5]), float(info[6])\n formatted_info = format_video_info(date, time, width, height, size, duration, fps)\n return (date, time, width, height, size, duration, fps), formatted_info\n else:\n info, formatted_info = make_video_info(filename, info_fullname)\n with open(info_fullname, 'wt') as f:\n print(' '.join([str(_) for _ in info]), file=f)\n return info, formatted_info\n\n\ndef make_video_info(filename, info_fullname):\n # ffmpeg must be in path\n date = date_from_item(filename)\n time = time_from_item(filename)\n command = [*FFPROBE_CMD.split(), filename]\n try:\n output = check_output(command, stderr=STDOUT).decode()\n width, height, fps, duration = parse_ffprobe_output(output)\n size = round(os.path.getsize(filename) / 1e6, 1)\n output = format_video_info(date, time, width, height, size, duration, fps)\n except CalledProcessError as e:\n output = e.output.decode()\n warning(output)\n raise\n return (date, time, width, height, size, duration, fps), output\n\n\ndef parse_ffprobe_output(ffprobe_output):\n # parse first channel data and last line for duration\n match = re.match(r'(\\d+),(\\d+),(\\d+)/(\\d+),(\\d+/\\d+).*\\s(\\d+\\.\\d+)', ffprobe_output, re.DOTALL)\n width = int(match.group(1))\n height = int(match.group(2))\n fps = round(int(match.group(3)) / int(match.group(4)), 1)\n duration = round(float(match.group(6)))\n return width, height, fps, duration\n\n\ndef format_video_info(date, time, width, height, size, duration, fps):\n return f'{date} {time}, dim={width}x{height}, {format_duration(duration)}, fps={fps}, {size} MB'\n\n\ndef format_duration(duration):\n mn = duration // 60\n sec = duration % 60\n if mn <= 59:\n return f'm:s={mn:02}:{sec:02}'\n else:\n hour = mn // 60\n mn = mn % 60\n return f'h:m:s={hour:02}:{mn:02}:{sec:02}'\n\n\n# -- Thumbnails (image and video) ---------------------------------------------\n\n\ndef thumbname(name, key):\n return key + '-' + name + '.jpg'\n\n\ndef size_thumbnail(width, height, maxdim):\n if width >= height:\n return maxdim, int(round(maxdim * height / width))\n else:\n return int(round(maxdim * width / height)), maxdim\n\n\ndef make_thumbnail_image(args, image_name, thumb_name, size):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_image(image_name, thumb_name, size)\n\n\ndef create_thumbnail_image(image_name, thumb_name, size):\n imgobj = Image.open(image_name)\n\n if (imgobj.mode != 'RGBA'\n and image_name.endswith('.jpg')\n and not (image_name.endswith('.gif') and imgobj.info.get('transparency'))\n ):\n imgobj = imgobj.convert('RGBA')\n\n imgobj.thumbnail(size, Image.LANCZOS)\n imgobj = imgobj.convert('RGB')\n imgobj.save(thumb_name)\n\n\ndef make_thumbnail_video(args, video_name, thumb_name, size, duration):\n if os.path.exists(thumb_name) and args.forcethumb is False:\n pass\n else:\n print('Making thumbnail:', thumb_name)\n create_thumbnail_video(args, video_name, thumb_name, size, duration)\n\n\n# base64 video.png\nVIDEO_ICON = '''\\\niVBORw0KGgoAAAANSUhEUgAAABgAAAAUCAAAAACy3qJfAAAA4UlEQVR4\n2m1QoRbCMAy88SaK69xscfuEWiS4SZBIcCCRfAL8An8AcnJzTOJSWdxwzJXSPUoHRPQlueYuucigxm\n9kDGaMf8AjopGcYn8LmmyLoihBWBiThb+5MTuUsc3aL56upneZ9sByAIg8Z8BEn96EeZ65iU7DvmbP\nPxqDcH6p1swXBC4l6yZskACkTN1WrQr2SlIFhTtgqeZa+zsOogLXegvEocZ5c/W5BcoVNNCg3hSudV\n/hEh4ofw6cEb00Km8i0dpRDUXfKiaQOEAdrUDo4dFp9C33jjaRac9/gDF/AlplVYtfWGCjAAAAAElF\nTkSuQmCC'''\n\n\ndef create_thumbnail_video(args, filename, thumbname, size, duration):\n # ffmpeg must be in path\n delay = min(duration - 1, args.thumbnails.thumbdelay)\n sizearg = '%dx%d' % size\n command = 'ffmpeg -y -v error -itsoffset -%d -i \"%s\" -vcodec mjpeg -vframes 1 -an -f rawvideo -s %s \"%s\"'\n command = command % (delay, filename, sizearg, thumbname)\n result = os.system(command)\n\n # add a movie icon to the thumbnail to identify videos\n try:\n img1 = Image.open(thumbname)\n except:\n # ffmpeg was unable to save thumbnail\n warning('Unable to save thumbnail for', filename)\n return\n img2 = Image.open(io.BytesIO(base64.b64decode(VIDEO_ICON)))\n width, height = img1.size\n img1.paste(img2, (6, height - 20 - 6), None)\n img1.save(thumbname)\n\n\ndef make_thumbnail_subdir(args, subdir_name, thumb_name, size, items, thumbdir):\n # subdir thumbnails are always created as they depend on the content of the\n # directory\n print('Making thumbnail:', thumb_name)\n create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir)\n\n\ndef create_thumbnail_subdir(subdir_name, thumb_name, size, items, thumbdir):\n\n def size_thumbnail(width, height, xmax, ymax):\n width2 = xmax\n height2 = int(round(xmax * height / width))\n if height2 < ymax:\n width2 = int(round(ymax * width / height))\n height2 = ymax\n return width2, height2\n\n thumblist = [os.path.basename(item.thumb) for item in items]\n widthnum, heightnum, width, height, offsetx, offsety = mosaic_geometry(size, thumblist)\n thumbnum = widthnum * heightnum\n img = Image.new('RGB', size, SUBDIR_BACKCOL)\n\n for ind, thumb in enumerate(thumblist[:min(thumbnum, len(thumblist))]):\n row = ind // widthnum\n col = ind % widthnum\n img2 = Image.open(os.path.join(thumbdir, thumb))\n w, h = size_thumbnail(*img2.size, width[col], height[row])\n cropdim = ((w - width[col]) // 2, (h - height[row]) // 2,\n (w - width[col]) // 2 + width[col], (h - height[row]) // 2 + height[row])\n img2 = img2.resize((w, h), Image.LANCZOS)\n img2 = img2.crop(cropdim)\n img.paste(img2, (offsetx[col], offsety[row]))\n\n if os.path.exists(thumb_name):\n # test if the generated thumbnail is identical to the one already on disk\n imgref = Image.open(thumb_name)\n\n # must save and reload before comparing\n byteio = io.BytesIO()\n img.save(byteio, \"JPEG\")\n byteio.seek(0)\n imgnew = Image.open(byteio)\n\n diff = ImageChops.difference(imgnew, imgref)\n if diff.getbbox() is None:\n return\n\n img.save(thumb_name)\n\n\ndef mosaic_geometry(size, thumblist):\n if len(thumblist) == 1:\n widthnum = 1\n heightnum = 1\n elif len(thumblist) <= 3:\n widthnum = 1\n heightnum = 2\n elif len(thumblist) <= 8:\n widthnum = 2\n heightnum = 2\n else:\n widthnum = 3\n heightnum = 3\n\n if widthnum == 1:\n width = [size[0] - 2]\n else:\n width = [size[0] // widthnum - 2] * (widthnum - 1)\n width.append(size[0] - (1 + sum(width) + 2 * len(width) + 1))\n\n if heightnum == 1:\n height = [size[1] - 2]\n else:\n height = [size[1] // heightnum - 2] * (heightnum - 1)\n height.append(size[1] - (1 + sum(height) + 2 * len(height) + 1))\n\n offsetx = [1]\n for w in width[:-1]:\n offsetx.append(offsetx[-1] + w + 2)\n\n offsety = [1]\n for h in height[:-1]:\n offsety.append(offsety[-1] + h + 2)\n\n return widthnum, heightnum, width, height, offsetx, offsety\n\n\ndef list_of_htmlfiles(args, posts):\n htmlist = list()\n htmlist.append(os.path.join(args.dest, args.rootname))\n for post in posts:\n htmlist.extend(list_of_htmlfiles_in_items(post.dcim))\n return htmlist\n\n\ndef list_of_htmlfiles_in_items(itemlist):\n htmlist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n htmlist.append(item.htmname)\n htmlist.extend(list_of_htmlfiles_in_items(item.sublist))\n return htmlist\n\n\ndef list_of_thumbnails(posts, diary=False):\n thumblist = list()\n for post in posts:\n thumblist.extend(list_of_thumbnails_in_items(post.medias))\n if diary is False:\n thumblist.extend(list_of_thumbnails_in_items(post.dcim))\n return thumblist\n\n\ndef list_of_thumbnails_in_items(itemlist):\n thumblist = list()\n for item in itemlist:\n if type(item) == PostSubdir:\n thumblist.append(os.path.basename(item.thumb))\n thumblist.extend(list_of_thumbnails_in_items(item.sublist))\n else:\n thumblist.append(os.path.basename(item.thumb))\n return thumblist\n\n\ndef purge_htmlfiles(args, posts):\n \"\"\"\n Purge root dir from irrelevant html files\n \"\"\"\n htmlist = list_of_htmlfiles(args, posts)\n html_to_remove = list()\n for fullname in glob.glob(os.path.join(args.root, '*.htm*')):\n if fullname not in htmlist:\n html_to_remove.append(fullname)\n\n if len(html_to_remove) > args.thumbnails.threshold_htmlfiles:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(f'{len(html_to_remove)} html files to remove. Continue [y|n]? ').lower()\n if inpt == 'n':\n return\n\n for name in html_to_remove:\n print('Removing html files', name)\n os.remove(name)\n\n\ndef purge_thumbnails(args, thumbdir, posts, diary=False):\n \"\"\"\n Purge thumbnail dir from irrelevant thumbnails\n \"\"\"\n thumblist = list_of_thumbnails(posts, diary)\n thumbs_to_remove = list()\n for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')):\n if os.path.basename(fullname) not in thumblist:\n thumbs_to_remove.append(fullname)\n\n if len(thumbs_to_remove) > args.thumbnails.threshold_thumbs:\n inpt = 'x'\n while inpt not in 'yn':\n inpt = input(f'{len(thumbs_to_remove)} thumbnails to remove. Continue [y|n]? ').lower()\n if inpt == 'n':\n return\n\n for name in thumbs_to_remove:\n print('Removing thumbnail', name)\n os.remove(name)\n info_fullname = os.path.splitext(name)[0] + '.info'\n if os.path.exists(info_fullname):\n os.remove(info_fullname)\n\n\n# -- List of medias helpers ---------------------------------------------------\n\n\ndef is_media_within_dates(fullname, dates):\n if is_media(fullname):\n if type(dates) == tuple:\n return dates[0] <= date_from_item(fullname) <= dates[1]\n else:\n return True\n else:\n return False\n\n\ndef sorted_listdir(filelist):\n like_windows_explorer = True\n\n if not filelist:\n return filelist\n\n if like_windows_explorer:\n maxlen = max(len(os.path.splitext(name)[0]) for name in filelist)\n def keyfunc(name):\n root, ext = os.path.splitext(name.lower())\n return root.ljust(maxlen, ' ') + ext\n else:\n keyfunc = str.lower\n\n return sorted(filelist, key=keyfunc)\n\n\ndef list_of_files(sourcedir, recursive):\n \"\"\"\n Return the list of full paths for files in source directory\n \"\"\"\n result = list()\n if recursive is False:\n listdir = sorted_listdir(os.listdir(sourcedir))\n if '.nomedia' not in listdir:\n for basename in listdir:\n result.append(os.path.join(sourcedir, basename))\n else:\n for root, dirs, files in os.walk(sourcedir):\n if '.nomedia' not in files:\n for basename in sorted_listdir(files):\n result.append(os.path.join(root, basename))\n return result\n\n\ndef list_of_medias(args, sourcedir, recursive):\n \"\"\"\n Return the list of full paths for pictures and movies in source directory\n \"\"\"\n files = list_of_files(sourcedir, recursive)\n return [_ for _ in files if is_media_within_dates(_, args.dates)]\n\n\ndef list_of_medias_ext(args, sourcedir):\n \"\"\"\n Return the list of full paths for pictures and movies in source directory\n plus subdirectories containing media\n \"\"\"\n result = list()\n listdir = sorted_listdir(os.listdir(sourcedir))\n if '.nomedia' not in listdir:\n for basename in listdir:\n fullname = os.path.join(sourcedir, basename)\n if os.path.isdir(fullname) and basename != '$RECYCLE.BIN' and contains_media(args, fullname):\n result.append(fullname)\n else:\n if is_media_within_dates(fullname, args.dates):\n result.append(fullname)\n return result\n\n\ndef contains_media(args, dirname):\n for root, dirs, files in os.walk(dirname):\n if '.nomedia' not in files:\n for basename in files:\n if is_media_within_dates(os.path.join(root, basename), args.dates):\n return True\n else:\n return False\n\n\ndef dispatch_post_items(list_of_post_items):\n subdirs = [_ for _ in list_of_post_items if type(_) is PostSubdir]\n medias = [_ for _ in list_of_post_items if type(_) is not PostSubdir]\n return subdirs, medias\n\n\n# -- Creation of gallery element ----------------------------------------------\n\n\ndef create_item(args, media_fullname, sourcedir, thumbdir, key, thumbmax):\n if os.path.isfile(media_fullname):\n if is_image_file(media_fullname):\n return create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax)\n else:\n return create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax)\n else:\n return create_item_subdir(args, media_fullname, sourcedir, thumbdir, key, thumbmax)\n\n\ndef create_item_image(args, media_fullname, sourcedir, thumbdir, key, thumbmax):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n\n try:\n info, infofmt = get_image_info(media_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_image(args, media_fullname, thumb_fullname, thumbsize)\n return PostImage(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)),\n thumbsize, infofmt)\n except PIL.UnidentifiedImageError:\n # corrupted image\n warning('Unable to read image', media_fullname)\n return None\n\n\ndef create_item_video(args, media_fullname, sourcedir, thumbdir, key, thumbmax):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n info_fullname = os.path.splitext(thumb_fullname)[0] + '.info'\n\n try:\n info, infofmt = get_video_info(media_fullname, info_fullname)\n infofmt = media_basename + ': ' + infofmt\n thumbsize = size_thumbnail(info[2], info[3], thumbmax)\n make_thumbnail_video(args, media_fullname, thumb_fullname, thumbsize, duration=info[5])\n return PostVideo(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)),\n thumbsize, infofmt)\n except CalledProcessError:\n # corrupted video\n warning('Unable to read video', media_fullname)\n return None\n\n\ndef create_item_subdir(args, media_fullname, sourcedir, thumbdir, key, thumbmax):\n media_basename = os.path.basename(media_fullname)\n media_relname = relative_name(media_fullname, sourcedir)\n thumb_basename = thumbname(media_relname, key)\n thumb_fullname = os.path.join(thumbdir, thumb_basename)\n\n info, infofmt = None, None\n thumbsize = (thumbmax, int(round(thumbmax / 640 * 480)))\n\n medias_ext = list_of_medias_ext(args, media_fullname)\n if not medias_ext:\n return None\n\n item = PostSubdir(None, media_fullname, '/'.join((args.thumbrep, thumb_basename)),\n thumbsize, infofmt)\n item.htmname = os.path.join(os.path.dirname(thumbdir), media_relname + args.html_suffix)\n if args.thumbnails.subdir_caption:\n item.caption = media_basename\n else:\n item.caption = ''\n\n _, posts = make_posts(args, media_fullname)\n item.posts = posts\n items = [item for post in posts for item in post.dcim]\n item.sublist = items\n\n make_thumbnail_subdir(args, media_fullname, thumb_fullname, thumbsize, items, thumbdir)\n return item\n\n\ndef relative_name(media_fullname, sourcedir):\n \"\"\"\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest/OCT_20000112_000004.jpg\n -->\n deeper2_deepest_OCT_20000112_000004.jpg\n\n /Gilles/Dev/journal/tests/subdir/deeper2/deepest\n -->\n deeper2_deepest\n \"\"\"\n x = os.path.relpath(media_fullname, sourcedir)\n x = x.replace('\\\\', '_').replace('/', '_').replace('#', '_')\n return x\n\n\n# -- Creation of posts --------------------------------------------------------\n\n\ndef make_posts(args, dirname):\n if args.diary is True:\n if not args.sourcedir:\n return make_posts_from_diary(args)\n else:\n return make_posts_from_diary_and_dir(args)\n elif args.bydate is False:\n return make_posts_from_subdir(args, dirname)\n else:\n return make_posts_from_subdir_and_date(args, dirname)\n\n\ndef make_posts_from_diary(args):\n md_filename = os.path.join(args.root, 'index.md')\n if os.path.exists(md_filename):\n title, posts = parse_markdown(md_filename)\n else:\n error('File not found', md_filename)\n\n for post in posts:\n for media in post.medias:\n media_fullname = os.path.join(args.root, media.uri)\n item = create_item(args, media_fullname, args.root, args.thumbdir, 'post', 400)\n media.thumb = item.thumb\n media.thumbsize = item.thumbsize\n media.descr = item.descr\n\n return title, posts\n\n\ndef create_items_by_date(args, medias, posts):\n # list of required dates\n if args.dates == 'diary':\n required_dates = {post.date for post in posts}\n else:\n required_dates = {date_from_item(media) for media in medias}\n if type(args.dates) == tuple:\n date1, date2 = args.dates\n required_dates = {date for date in required_dates if date1 <= date <= date2}\n\n bydate = defaultdict(list)\n for media_fullname in medias:\n date = date_from_item(media_fullname)\n if date in required_dates:\n item = create_item(args, media_fullname, args.sourcedir, args.thumbdir, 'dcim', 300)\n if item:\n bydate[date].append(item)\n\n for date, liste in bydate.items():\n liste.sort(key=lambda item: time_from_item(item.uri))\n\n return bydate\n\n\ndef make_posts_from_diary_and_dir(args):\n title, posts = make_posts_from_diary(args)\n\n # list of all pictures and movies\n medias = list_of_medias(args, args.sourcedir, args.recursive)\n\n bydate = create_items_by_date(args, medias, posts)\n\n # make list of extra dates (not in posts)\n extradates = set(bydate) - {post.date for post in posts}\n\n # complete posts with extra dates\n for date in extradates:\n post = Post.from_date(date)\n post.extra = True\n bisect.insort(posts, post)\n\n # several posts can have the same date, only the first one is completed with dcim medias\n for post in posts:\n if post.date in bydate and post.daterank == 1:\n post.dcim = bydate[post.date]\n\n return title, posts\n\n\ndef make_posts_from_subdir(args, dirname):\n # list of pictures and movies plus subdirectories\n if args.bydir is False:\n medias_ext = list_of_medias(args, dirname, args.recursive)\n else:\n medias_ext = list_of_medias_ext(args, dirname)\n\n #required_dates = get_required_dates(args, medias_ext, posts=None)\n #medias_ext_bis = []\n #for media in medias_ext:\n # if complies_with_required_dates(media):\n # medias_ext_bis.append(media)\n\n # complete posts\n postmedias = list()\n for item in medias_ext:\n postmedia = create_item(args, item, args.sourcedir, args.thumbdir, 'dcim', 300)\n if postmedia is not None:\n postmedias.append(postmedia)\n\n post = Post(date='00000000', text='', medias=[])\n post.dcim = postmedias\n posts = [post]\n title = os.path.basename(args.sourcedir) or os.path.splitdrive(args.sourcedir)[0]\n\n return title, posts\n\n\ndef make_posts_from_subdir_and_date(args, dirname):\n # list of all pictures and movies\n if args.bydir is False:\n medias = list_of_medias(args, dirname, args.recursive)\n subdirs = []\n else:\n medias_ext = list_of_medias_ext(args, dirname)\n medias = [_ for _ in medias_ext if is_media(_)]\n subdirs = [_ for _ in medias_ext if not is_media(_)]\n\n # create list of posts with a single post containing all subdirs\n posts = list()\n items = list()\n for media_fullname in subdirs:\n item = create_item(args, media_fullname, args.sourcedir, args.thumbdir, 'dcim', 300)\n if item:\n items.append(item)\n if items:\n post = Post(date='00000000', text='', medias=[])\n post.dcim = items\n posts.append(post)\n\n bydate = create_items_by_date(args, medias, posts)\n\n # add dates\n for date in sorted(bydate):\n post = Post.from_date(date)\n post.dcim = bydate[post.date]\n posts.append(post)\n title = os.path.basename(args.sourcedir) or os.path.splitdrive(args.sourcedir)[0]\n\n return title, posts\n\n\n# -- Creation of html page from directory tree --------------------------------\n\n\ndef create_gallery(args):\n title, posts = make_posts(args, args.sourcedir)\n print_html(args, posts, title, os.path.join(args.dest, args.rootname), 'regular')\n purge_htmlfiles(args, posts)\n if args.diary and not args.sourcedir:\n purge_thumbnails(args, args.thumbdir, posts, diary=True)\n else:\n purge_thumbnails(args, args.thumbdir, posts)\n\n\n# -- Creation of diary from medias --------------------------------------------\n\n\ndef create_diary(args):\n # list of all pictures and movies\n medias = list_of_medias(args, args.sourcedir, args.recursive)\n\n # list of required dates\n if args.dates == 'diary':\n assert 0\n else:\n required_dates = {date_from_item(media) for media in medias}\n if type(args.dates) == tuple:\n date1, date2 = args.dates\n required_dates = {date for date in required_dates if date1 <= date <= date2}\n\n title = args.sourcedir\n posts = list()\n for date in sorted(required_dates):\n posts.append(Post.from_date(date))\n\n os.makedirs(args.root, exist_ok=True)\n print_markdown(posts, title, os.path.join(args.root, 'index.md'))\n\n\n# -- Export to blogger---------------------------------------------------------\n\n\ndef online_images_url(args):\n try:\n if args.urlblogger.startswith('http:') or args.urlblogger.startswith('https:'):\n with urlopen(args.urlblogger) as u:\n buffer = u.read()\n else:\n with open(args.urlblogger, 'rb') as f:\n buffer = f.read()\n except:\n error('Unable to read url', args.urlblogger)\n buffer = buffer.decode('utf-8')\n\n online_images = dict()\n for match in re.finditer('<div class=\"separator\"((?!<div).)*?</div>', buffer, flags=re.DOTALL):\n div_separator = match.group(0)\n div_separator = div_separator.replace('&nbsp;', '')\n elem_div = objectify.fromstring(div_separator)\n for elem_a in elem_div.iterchildren(tag='a'):\n href = elem_a.get(\"href\")\n thumb = elem_a.img.get(\"src\")\n online_images[os.path.basename(href)] = (href, thumb)\n\n # video insertion relies only on video order\n online_videos = list()\n for match in re.finditer('<iframe allowfullscreen=\"allowfullscreen\".*?</iframe>', buffer, flags=re.DOTALL):\n iframe = match.group(0)\n online_videos.append(iframe)\n\n return online_images, online_videos\n\n\ndef compare_image_buffers(imgbuf1, imgbuf2):\n \"\"\"\n return True if images read on file are identical, False otherwise\n \"\"\"\n with io.BytesIO(imgbuf1) as imgio1, io.BytesIO(imgbuf2) as imgio2:\n img1 = Image.open(imgio1)\n img2 = Image.open(imgio2)\n diff = ImageChops.difference(img1, img2)\n return not diff.getbbox()\n\n\ndef check_images(args, posts, online_images):\n result = True\n for post in posts:\n for media in post.medias:\n if type(media) is PostImage:\n if media.basename in online_images:\n with open(os.path.join(args.root, media.uri), 'rb') as f:\n imgbuf1 = f.read()\n try:\n with urlopen(online_images[media.basename][0]) as u:\n imgbuf2 = u.read()\n except FileNotFoundError:\n print('File not found', online_images[media.basename][0])\n next\n if compare_image_buffers(imgbuf1, imgbuf2) is False:\n print('Files are different, upload', media.basename)\n else:\n if 1:\n print('File already online', media.basename)\n else:\n print('File is absent, upload', media.basename)\n result = False\n elif type(media) is PostVideo:\n # no check for the moment\n print('Video not checked', media.basename)\n else:\n assert False\n return result\n\n\ndef compose_blogger_html(args, title, posts, imgdata, online_videos):\n \"\"\" Compose html with blogger image urls\n \"\"\"\n for post in posts:\n for media in post.medias:\n if type(media) is PostImage:\n if media.uri not in imgdata:\n print('Image missing: ', media.uri)\n else:\n img_url, resized_url = imgdata[media.uri]\n media.uri = img_url\n media.resized_url = resized_url\n elif type(media) is PostVideo:\n if not online_videos:\n print('Video missing: ', media.uri)\n else:\n media.iframe = online_videos[0]\n del online_videos[0]\n else:\n assert False\n\n return print_html(args, posts, title, '', target='blogger')\n\n\ndef prepare_for_blogger(args):\n \"\"\"\n Export blogger html to clipboard.\n If --full, export complete html, otherwise export html extract ready to\n paste into blogger edit mode.\n \"\"\"\n title, posts = parse_markdown(os.path.join(args.root, 'index.md'))\n online_images, online_videos = online_images_url(args)\n\n if args.check_images and check_images(args, posts, online_images) is False:\n pass\n\n html = compose_blogger_html(args, title, posts, online_images, online_videos)\n\n if args.full is False:\n html = re.search('<body>(.*)?</body>', html, flags=re.DOTALL).group(1)\n html = re.sub('<script>.*?</script>', '', html, flags=re.DOTALL)\n html = STYLE.replace('%%', '%') + html\n\n if args.dest:\n with open(args.dest, 'wt', encoding='utf-8') as f:\n f.write(html)\n else:\n clipboard.copy(html)\n\n\n# -- Other commands -----------------------------------------------------------\n\n\ndef idempotence(args):\n \"\"\"\n For testing identity between a diary file and the fle obtained after reading\n and printing it. See testing.\n \"\"\"\n title, posts = parse_markdown(os.path.join(args.root, 'index.md'))\n print_markdown(posts, title, os.path.join(args.dest, 'index.md'))\n\n\n# -- Configuration file ------------------------------------------------------\n\n\n# The following docstring is used to create the configuration file.\nCONFIG_DEFAULTS = \"\"\"\\\n[source]\n\n; source directory\n; value: valid path\nsourcedir = .\n\n; one web page per directory\n; value: true or false\nbydir = false\n\n; dispatch medias by dates\n; value: true or false\nbydate = false\n\n; include text and medias from diary file\n; value: true or false\ndiary = false\n\n; include subdirectories recursively (used when bydir is false)\n; value: true or false\nrecursive = false\n\n; interval of dates to include\n; value: source|diary|yyyymmdd-yyyymmdd or empty (= source)\ndates =\n\n; github Pages compatibility (.htlml extension and no dot in directory names)\n; value: true or false\ngithub_pages = false\n\n[thumbnails]\n\n; specifies whether or not the gallery displays media description (size, dimension, etc)\n; value: true or false\nmedia_description = true\n\n; specifies whether subdir captions are empty or the name of the subdir\n; value: true or false\nsubdir_caption = true\n\n; timestamp of thumbnail in video\n; value: number of seconds\nthumbdelay = 5\n\n; maximum number of thumbnails to remove without user confirmation\n; value: integer\nthreshold_thumbs = 10\n\n[photobox]\n\n; Allows to navigate between first and last images\n; value: true or false\nloop = false\n\n; Show gallery thumbnails below the presented photo\n; value: true or false\nthumbs = true\n\n; Should autoplay on first time or not\n; value: true or false\nautoplay = false\n\n; Autoplay interval (less than 1000 will hide the autoplay button)\n; value: milliseconds\ntime = 3000\n\n; Disable/enable mousewheel image zooming\n; value: true or false\nzoomable = true\n\n; Allow rotation of the image\n; value: true or false\nrotatable = true\n\n; Change image using mousewheel left/right\n; value: true or false\nwheelNextPrev = true\n\"\"\"\n\n\nclass MyConfigParser (ConfigParser):\n \"\"\"Add input checking.\"\"\"\n def __init__(self):\n ConfigParser.__init__(self, inline_comment_prefixes=(';',))\n\n def error(self, section, entry):\n error('Missing or incorrect config value:', '[%s]%s' % (section, entry))\n\n def getint(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getint(self, section, entry)\n else:\n return ConfigParser.getint(self, section, entry, raw=True, vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n def getboolean(self, section, entry, default=None):\n try:\n if default is None:\n return ConfigParser.getboolean(self, section, entry)\n else:\n return ConfigParser.getboolean(self, section, entry, raw=True, vars=None, fallback=default)\n except Exception as e:\n print(e)\n self.error(section, entry)\n\n\ndef configfilename(params):\n return os.path.join(params.root, '.config.ini')\n\n\ndef createconfig(config_filename):\n with open(config_filename, 'wt') as f:\n f.writelines(CONFIG_DEFAULTS)\n\n\ndef read_config(params):\n config_filename = configfilename(params)\n\n try:\n if not os.path.exists(config_filename) or params.resetcfg:\n createconfig(config_filename)\n except:\n error('Error creating configuration file')\n\n try:\n getconfig(params, config_filename)\n except Exception as e:\n error('Error reading configuration file.', str(e), 'Use --resetcfg')\n\n\ndef getconfig(options, config_filename):\n class Section:\n pass\n\n options.source = Section()\n options.thumbnails = Section()\n options.photobox = Section()\n\n config = MyConfigParser()\n config.read(config_filename)\n\n # [source]\n options.source.sourcedir = config.get('source', 'sourcedir')\n options.source.bydir = config.getboolean('source', 'bydir')\n options.source.bydate = config.getboolean('source', 'bydate')\n options.source.diary = config.getboolean('source', 'diary')\n options.source.recursive = config.getboolean('source', 'recursive')\n options.source.dates = config.get('source', 'dates')\n options.source.github_pages = config.getboolean('source', 'github_pages', default=False)\n\n # [thumbnails]\n options.thumbnails.media_description = config.getboolean('thumbnails', 'media_description')\n options.thumbnails.subdir_caption = config.getboolean('thumbnails', 'subdir_caption')\n options.thumbnails.thumbdelay = config.getint('thumbnails', 'thumbdelay')\n options.thumbnails.threshold_thumbs = config.getint('thumbnails', 'threshold_thumbs')\n options.thumbnails.threshold_htmlfiles = config.getint('thumbnails', 'threshold_htmlfiles', default=3)\n\n # [photobox]\n options.photobox.loop = config.getboolean('photobox', 'loop')\n options.photobox.thumbs = config.getboolean('photobox', 'thumbs')\n options.photobox.autoplay = config.getboolean('photobox', 'autoplay')\n options.photobox.time = config.getint('photobox', 'time')\n options.photobox.zoomable = config.getboolean('photobox', 'zoomable')\n options.photobox.rotatable = config.getboolean('photobox', 'rotatable')\n options.photobox.wheelNextPrev = config.getboolean('photobox', 'wheelNextPrev')\n\n\ndef setconfig(cfgname, section, key, value):\n config = MyConfigParser()\n config.read(cfgname)\n config.set(section, key, value)\n with open(cfgname, 'wt') as configfile:\n config.write(configfile)\n\n\ndef setconfig_cmd(args):\n config_filename = configfilename(args)\n setconfig(config_filename, *args.setcfg)\n\n\ndef update_config(args):\n # update only entries which can be modified from the command line (source section)\n updates = (\n ('sourcedir', args.sourcedir),\n ('bydir', BOOL[args.bydir]),\n ('bydate', BOOL[args.bydate]),\n ('diary', BOOL[args.diary]),\n ('recursive', BOOL[args.recursive]),\n ('dates', args.dates),\n ('github_pages', BOOL[args.github_pages]),\n )\n\n # manual update to keep comments\n cfgname = configfilename(args)\n with open(cfgname) as f:\n cfglines = [_.strip() for _ in f.readlines()]\n\n for key, value in updates:\n for iline, line in enumerate(cfglines):\n if line.startswith(key):\n cfglines[iline] = f'{key} = {value}'\n break\n\n with open(cfgname, 'wt') as f:\n for line in cfglines:\n print(line, file=f)\n\n\n# -- Error handling -----------------------------------------------------------\n\n\ndef warning(*msg):\n print(colorama.Fore.YELLOW + colorama.Style.BRIGHT +\n ' '.join(msg),\n colorama.Style.RESET_ALL)\n\n\n# Every error message error must be declared here to give a return code to the error\nERRORS = '''\\\nFile not found\nDirectory not found\nNo date in post\nIncorrect date value:\nPosts are not ordered\nUnable to read url\nNo image source (--sourcedir)\nNo blogger url (--url)\nMissing or incorrect config value:\nError creating configuration file\nError reading configuration file.\nIncorrect date format\nIncorrect parameters:\n'''\n\n\ndef errorcode(msg):\n return ERRORS.splitlines().index(msg) + 1\n\n\ndef error(*msg):\n print(colorama.Fore.RED + colorama.Style.BRIGHT +\n ' '.join(msg),\n colorama.Style.RESET_ALL)\n sys.exit(errorcode(msg[0]))\n\n\n# -- Main ---------------------------------------------------------------------\n\n\nBOOL = ('false', 'true')\n\n\ndef parse_command_line(argstring):\n parser = argparse.ArgumentParser(description=None, usage=USAGE)\n\n agroup = parser.add_argument_group('Commands')\n xgroup = agroup.add_mutually_exclusive_group()\n xgroup.add_argument('--gallery', help='source in --sourcedir',\n action='store', metavar='<root-dir>')\n agroup.add_argument('--update', help='updates gallery with parameters in config file',\n action='store', metavar='<root-dir>')\n xgroup.add_argument('--create', help='create journal from medias in --sourcedir',\n action='store', metavar='<root-dir>')\n # testing\n xgroup.add_argument('--resetcfg', help='reset config file to defaults',\n action='store', metavar='<root-dir>')\n xgroup.add_argument('--setcfg', help=argparse.SUPPRESS,\n action='store', nargs=4, metavar='<root-dir>')\n xgroup.add_argument('--idem', help=argparse.SUPPRESS,\n action='store', metavar='<root-dir>')\n # blogger\n xgroup.add_argument('--blogger',\n help='input md, html blogger ready in clipboard',\n action='store', metavar='<root-dir>')\n\n agroup = parser.add_argument_group('Parameters')\n agroup.add_argument('--bydir', help='organize gallery by subdirectory',\n action='store', default=None, choices=BOOL)\n agroup.add_argument('--bydate', help='organize gallery by date',\n action='store', default=None, choices=BOOL)\n agroup.add_argument('--diary', help='organize gallery using markdown file diary',\n action='store', default=None, choices=BOOL)\n agroup.add_argument('--recursive', help='--sourcedir scans recursively',\n action='store', default=None, choices=BOOL)\n agroup.add_argument('--dates', help='dates interval',\n action='store', default=None)\n agroup.add_argument('--sourcedir', help='media directory',\n action='store', default=None)\n agroup.add_argument('--github_pages', help='github Pages compatibility',\n action='store', default=None, choices=BOOL)\n agroup.add_argument('--dest', help='output directory',\n action='store')\n agroup.add_argument('--forcethumb', help='force calculation of thumbnails',\n action='store_true', default=False)\n\n agroup.add_argument('--full', help='full html (versus blogger ready html)',\n action='store_true', default=False)\n agroup.add_argument('--check', dest='check_images', help='check availability of medias on blogger',\n action='store_true')\n agroup.add_argument('--url', dest='urlblogger', help='blogger post url',\n action='store')\n\n if argstring is None:\n print('Type \"galerie -h\" for help')\n sys.exit(1)\n else:\n args = parser.parse_args(argstring.split())\n\n if args.update and (args.bydir or args.bydate or args.diary or args.sourcedir or\n args.recursive or args.dates or args.github_pages):\n error('Incorrect parameters:',\n '--update cannot be used with creation parameters, use explicit command')\n\n args.bydir = args.bydir == 'true'\n args.bydate = args.bydate == 'true'\n args.diary = args.diary == 'true'\n args.recursive = args.recursive == 'true'\n args.dates = 'source' if (args.dates is None) else args.dates\n args.github_pages = args.github_pages == 'true'\n\n args.root = (\n args.create or args.gallery or args.update\n or args.blogger or args.idem or args.resetcfg\n )\n\n if args.setcfg:\n args.root = args.setcfg[0]\n args.setcfg = args.setcfg[1:]\n\n return args\n\n\ndef setup_part1(args):\n \"\"\"\n Made before reading config file (config file located in args.root).\n Check and normalize root path.\n \"\"\"\n args.rootarg = args.root\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext == '':\n pass\n else:\n args.root = os.path.dirname(args.root)\n\n if args.root:\n args.root = os.path.abspath(args.root)\n if not os.path.isdir(args.root):\n if args.gallery:\n os.mkdir(args.root)\n else:\n error('Directory not found', args.root)\n\n\ndef setup_part2(args):\n \"\"\"\n Made after reading config file.\n Check for ffmpeg in path.\n Create .thumbnails dir if necessary and create .nomedia in it.\n Copy photobox file to destination dir.\n Handle priority between command line and config file.\n \"\"\"\n if args.update:\n args.sourcedir = args.source.sourcedir\n args.bydir = args.source.bydir\n args.bydate = args.source.bydate\n args.diary = args.source.diary\n args.recursive = args.source.recursive\n args.dates = args.source.dates\n args.github_pages = args.source.github_pages\n elif args.gallery:\n args.source.sourcedir = args.sourcedir\n args.source.bydir = args.bydir\n args.source.bydate = args.bydate\n args.source.diary = args.diary\n args.source.recursive = args.recursive\n args.source.dates = args.dates\n args.source.github_pages = args.github_pages\n update_config(args)\n\n if args.github_pages:\n args.html_suffix = '.html'\n else:\n args.html_suffix = '.htm'\n\n rootext = os.path.splitext(args.rootarg)[1]\n if rootext:\n args.rootname = os.path.basename(args.rootarg)\n else:\n args.rootname = 'index' + args.html_suffix\n\n if args.sourcedir:\n args.sourcedir = os.path.abspath(args.sourcedir)\n if os.path.splitdrive(args.sourcedir)[0]:\n drive, rest = os.path.splitdrive(args.sourcedir)\n args.sourcedir = drive.upper() + rest\n if not os.path.isdir(args.sourcedir):\n error('Directory not found', args.sourcedir)\n else:\n if args.gallery and args.diary is False and args.update is None:\n error('Directory not found', 'Use --sourcedir')\n\n if args.dest:\n args.dest = os.path.abspath(args.dest)\n\n if args.dest is None:\n args.dest = args.root\n\n if args.blogger and args.urlblogger is None:\n error('No blogger url (--url)')\n\n if args.gallery or args.update:\n # check for ffmpeg and ffprobe in path\n for exe in ('ffmpeg', 'ffprobe'):\n try:\n check_output([exe, '-version'])\n except FileNotFoundError:\n error('File not found', exe)\n\n if args.github_pages:\n args.thumbrep = 'thumbnails'\n else:\n args.thumbrep = '.thumbnails'\n\n args.thumbdir = os.path.join(args.dest, args.thumbrep)\n if not os.path.exists(args.thumbdir):\n os.mkdir(args.thumbdir)\n open(os.path.join(args.thumbdir, '.nomedia'), 'a').close()\n\n favicondst = os.path.join(args.dest, 'favicon.ico')\n if not os.path.isfile(favicondst):\n faviconsrc = os.path.join(os.path.dirname(__file__), 'favicon.ico')\n shutil.copyfile(faviconsrc, favicondst)\n\n photoboxdir = os.path.join(args.dest, 'photobox')\n if not os.path.exists(photoboxdir):\n photoboxsrc = os.path.join(os.path.dirname(__file__), 'photobox')\n shutil.copytree(photoboxsrc, photoboxdir)\n\n if args.dates:\n if not(args.gallery or args.create):\n # silently ignored for the moment, otherwise all other commands will\n # launch a wanrning or an error on the default --dates value\n pass\n\n if args.dates == 'source':\n pass\n elif args.dates == 'diary':\n if args.create:\n error('Incorrect date format', args.dates)\n elif re.match(r'\\d+-\\d+', args.dates):\n date1, date2 = args.dates.split('-')\n if validate_date(date1) and validate_date(date2):\n args.dates = date1, date2\n else:\n error('Incorrect date format', args.dates)\n else:\n error('Incorrect date format', args.dates)\n\n\ndef main(argstring=None):\n colorama.init()\n args = parse_command_line(argstring)\n setup_part1(args)\n read_config(args)\n setup_part2(args)\n try:\n if args.gallery or args.update:\n create_gallery(args)\n\n elif args.create:\n create_diary(args)\n\n elif args.blogger:\n prepare_for_blogger(args)\n\n elif args.idem:\n idempotence(args)\n\n elif args.setcfg:\n setconfig_cmd(args)\n\n except KeyboardInterrupt:\n warning('Interrupted by user.')\n\n\nif __name__ == '__main__':\n main(' '.join(sys.argv[1:]))\n", "step-ids": [ 79, 84, 88, 100, 110 ] }
[ 79, 84, 88, 100, 110 ]
# Author: Sam Erickson # Date: 2/23/2016 # # Program Description: This program gives the integer coefficients x,y to the # equation ax+by=gcd(a,b) given by the extended Euclidean Algorithm. def extendedEuclid(a,b): """ Preconditions - a and b are both positive integers. Posconditions - The equation for ax+by=gcd(a,b) has been returned where x and y are solved. Input - a : int, b : int Output - ax+by=gcd(a,b) : string """ b,a=max(a,b),min(a,b) # Format of euclidList is for back-substitution euclidList=[[b%a,1,b,-1*(b//a),a]] while b%a>0: b,a=a,b%a euclidList.append([b%a,1,b,-1*(b//a),a]) if len(euclidList)>1: euclidList.pop() euclidList=euclidList[::-1] for i in range(1,len(euclidList)): euclidList[i][1]*=euclidList[i-1][3] euclidList[i][3]*=euclidList[i-1][3] euclidList[i][3]+=euclidList[i-1][1] expr=euclidList[len(euclidList)-1] strExpr=str(expr[1])+"*"+str(expr[2])+" + "+str(expr[3])+"*"+str(expr[4]) \ +" = "+str(euclidList[0][0]) return strExpr
normal
{ "blob_id": "36e5b0f40b8016f39120f839766db0ac518c9bed", "index": 4712, "step-1": "<mask token>\n", "step-2": "def extendedEuclid(a, b):\n \"\"\"\n Preconditions - a and b are both positive integers.\n Posconditions - The equation for ax+by=gcd(a,b) has been returned where\n x and y are solved.\n Input - a : int, b : int\n Output - ax+by=gcd(a,b) : string\n \"\"\"\n b, a = max(a, b), min(a, b)\n euclidList = [[b % a, 1, b, -1 * (b // a), a]]\n while b % a > 0:\n b, a = a, b % a\n euclidList.append([b % a, 1, b, -1 * (b // a), a])\n if len(euclidList) > 1:\n euclidList.pop()\n euclidList = euclidList[::-1]\n for i in range(1, len(euclidList)):\n euclidList[i][1] *= euclidList[i - 1][3]\n euclidList[i][3] *= euclidList[i - 1][3]\n euclidList[i][3] += euclidList[i - 1][1]\n expr = euclidList[len(euclidList) - 1]\n strExpr = str(expr[1]) + '*' + str(expr[2]) + ' + ' + str(expr[3]\n ) + '*' + str(expr[4]) + ' = ' + str(euclidList[0][0])\n return strExpr\n", "step-3": "# Author: Sam Erickson\n# Date: 2/23/2016\n#\n# Program Description: This program gives the integer coefficients x,y to the\n# equation ax+by=gcd(a,b) given by the extended Euclidean Algorithm. \n\ndef extendedEuclid(a,b):\n \"\"\"\n Preconditions - a and b are both positive integers.\n Posconditions - The equation for ax+by=gcd(a,b) has been returned where\n x and y are solved.\n Input - a : int, b : int\n Output - ax+by=gcd(a,b) : string\n \"\"\"\n b,a=max(a,b),min(a,b)\n # Format of euclidList is for back-substitution\n euclidList=[[b%a,1,b,-1*(b//a),a]]\n while b%a>0:\n b,a=a,b%a \n euclidList.append([b%a,1,b,-1*(b//a),a])\n if len(euclidList)>1:\n euclidList.pop()\n euclidList=euclidList[::-1]\n for i in range(1,len(euclidList)):\n euclidList[i][1]*=euclidList[i-1][3]\n euclidList[i][3]*=euclidList[i-1][3]\n euclidList[i][3]+=euclidList[i-1][1]\n \n expr=euclidList[len(euclidList)-1]\n strExpr=str(expr[1])+\"*\"+str(expr[2])+\" + \"+str(expr[3])+\"*\"+str(expr[4]) \\\n +\" = \"+str(euclidList[0][0])\n return strExpr\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> class Solution(object): <|reserved_special_token_0|> <|reserved_special_token_1|> class Solution(object): def gcdOfStrings(self, str1, str2): if str1 == str2: return str1 elif not str1 or not str2: return '' elif str1.startswith(str2): return self.gcdOfStrings(str1[len(str2):], str2) elif str2.startswith(str1): return self.gcdOfStrings(str1, str2[len(str1):]) else: return ''
flexible
{ "blob_id": "ab632c3c8a7f295a890de19af82fde87c6d600bc", "index": 1674, "step-1": "<mask token>\n", "step-2": "class Solution(object):\n <mask token>\n", "step-3": "class Solution(object):\n\n def gcdOfStrings(self, str1, str2):\n if str1 == str2:\n return str1\n elif not str1 or not str2:\n return ''\n elif str1.startswith(str2):\n return self.gcdOfStrings(str1[len(str2):], str2)\n elif str2.startswith(str1):\n return self.gcdOfStrings(str1, str2[len(str1):])\n else:\n return ''\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime archivo = open("salida2.csv", "a+") startTime = datetime.now() def mergeSort(alist): print("Splitting ",alist) if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) a=0 b=0 k=0 while a < len(lefthalf) and b < len(righthalf): if lefthalf[a] < righthalf[b]: alist[k]=lefthalf[a] a=a+1 else: alist[k]=righthalf[b] b=b+1 k=k+1 while a < len(lefthalf): alist[k]=lefthalf[a] a=a+1 k=k+1 while b < len(righthalf): alist[k]=righthalf[b] b=b+1 k=k+1 alist = [] N = int(input("")) nums = input("").split() for a in nums: alist.append(int(a)) mergeSort(alist) print(' '.join(str(a) for a in alist)+' \n') tiempo = datetime.now() - startTime archivo.write(str(N)+",") archivo.write(str(tiempo)+"\n") archivo.close()
normal
{ "blob_id": "9e98c6b59433369bca3d4f7ae261f7e7ab3aae6b", "index": 4161, "step-1": "<mask token>\n\n\ndef mergeSort(alist):\n print('Splitting ', alist)\n if len(alist) > 1:\n mid = len(alist) // 2\n lefthalf = alist[:mid]\n righthalf = alist[mid:]\n mergeSort(lefthalf)\n mergeSort(righthalf)\n a = 0\n b = 0\n k = 0\n while a < len(lefthalf) and b < len(righthalf):\n if lefthalf[a] < righthalf[b]:\n alist[k] = lefthalf[a]\n a = a + 1\n else:\n alist[k] = righthalf[b]\n b = b + 1\n k = k + 1\n while a < len(lefthalf):\n alist[k] = lefthalf[a]\n a = a + 1\n k = k + 1\n while b < len(righthalf):\n alist[k] = righthalf[b]\n b = b + 1\n k = k + 1\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef mergeSort(alist):\n print('Splitting ', alist)\n if len(alist) > 1:\n mid = len(alist) // 2\n lefthalf = alist[:mid]\n righthalf = alist[mid:]\n mergeSort(lefthalf)\n mergeSort(righthalf)\n a = 0\n b = 0\n k = 0\n while a < len(lefthalf) and b < len(righthalf):\n if lefthalf[a] < righthalf[b]:\n alist[k] = lefthalf[a]\n a = a + 1\n else:\n alist[k] = righthalf[b]\n b = b + 1\n k = k + 1\n while a < len(lefthalf):\n alist[k] = lefthalf[a]\n a = a + 1\n k = k + 1\n while b < len(righthalf):\n alist[k] = righthalf[b]\n b = b + 1\n k = k + 1\n\n\n<mask token>\nfor a in nums:\n alist.append(int(a))\nmergeSort(alist)\nprint(' '.join(str(a) for a in alist) + ' \\n')\n<mask token>\narchivo.write(str(N) + ',')\narchivo.write(str(tiempo) + '\\n')\narchivo.close()\n", "step-3": "<mask token>\narchivo = open('salida2.csv', 'a+')\nstartTime = datetime.now()\n\n\ndef mergeSort(alist):\n print('Splitting ', alist)\n if len(alist) > 1:\n mid = len(alist) // 2\n lefthalf = alist[:mid]\n righthalf = alist[mid:]\n mergeSort(lefthalf)\n mergeSort(righthalf)\n a = 0\n b = 0\n k = 0\n while a < len(lefthalf) and b < len(righthalf):\n if lefthalf[a] < righthalf[b]:\n alist[k] = lefthalf[a]\n a = a + 1\n else:\n alist[k] = righthalf[b]\n b = b + 1\n k = k + 1\n while a < len(lefthalf):\n alist[k] = lefthalf[a]\n a = a + 1\n k = k + 1\n while b < len(righthalf):\n alist[k] = righthalf[b]\n b = b + 1\n k = k + 1\n\n\nalist = []\nN = int(input(''))\nnums = input('').split()\nfor a in nums:\n alist.append(int(a))\nmergeSort(alist)\nprint(' '.join(str(a) for a in alist) + ' \\n')\ntiempo = datetime.now() - startTime\narchivo.write(str(N) + ',')\narchivo.write(str(tiempo) + '\\n')\narchivo.close()\n", "step-4": "from datetime import datetime\narchivo = open('salida2.csv', 'a+')\nstartTime = datetime.now()\n\n\ndef mergeSort(alist):\n print('Splitting ', alist)\n if len(alist) > 1:\n mid = len(alist) // 2\n lefthalf = alist[:mid]\n righthalf = alist[mid:]\n mergeSort(lefthalf)\n mergeSort(righthalf)\n a = 0\n b = 0\n k = 0\n while a < len(lefthalf) and b < len(righthalf):\n if lefthalf[a] < righthalf[b]:\n alist[k] = lefthalf[a]\n a = a + 1\n else:\n alist[k] = righthalf[b]\n b = b + 1\n k = k + 1\n while a < len(lefthalf):\n alist[k] = lefthalf[a]\n a = a + 1\n k = k + 1\n while b < len(righthalf):\n alist[k] = righthalf[b]\n b = b + 1\n k = k + 1\n\n\nalist = []\nN = int(input(''))\nnums = input('').split()\nfor a in nums:\n alist.append(int(a))\nmergeSort(alist)\nprint(' '.join(str(a) for a in alist) + ' \\n')\ntiempo = datetime.now() - startTime\narchivo.write(str(N) + ',')\narchivo.write(str(tiempo) + '\\n')\narchivo.close()\n", "step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\n\narchivo = open(\"salida2.csv\", \"a+\")\n\nstartTime = datetime.now()\ndef mergeSort(alist):\n print(\"Splitting \",alist)\n if len(alist)>1:\n mid = len(alist)//2\n lefthalf = alist[:mid]\n righthalf = alist[mid:]\n\n mergeSort(lefthalf)\n mergeSort(righthalf)\n\n a=0\n b=0\n k=0\n while a < len(lefthalf) and b < len(righthalf):\n if lefthalf[a] < righthalf[b]:\n alist[k]=lefthalf[a]\n a=a+1\n else:\n alist[k]=righthalf[b]\n b=b+1\n k=k+1\n\n while a < len(lefthalf):\n alist[k]=lefthalf[a]\n a=a+1\n k=k+1\n\n while b < len(righthalf):\n alist[k]=righthalf[b]\n b=b+1\n k=k+1\n\nalist = []\nN = int(input(\"\"))\nnums = input(\"\").split()\nfor a in nums:\n alist.append(int(a))\nmergeSort(alist)\nprint(' '.join(str(a) for a in alist)+' \\n')\ntiempo = datetime.now() - startTime\n\narchivo.write(str(N)+\",\")\narchivo.write(str(tiempo)+\"\\n\")\narchivo.close()", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
import sys sys.setrecursionlimit(10 ** 6) n, s = map(int, input().split()) value = list(map(int, input().split())) count = 0 def recursive(index, sum): global count if index == n: if sum == s: count += 1 return recursive(index + 1, sum + value[index]) recursive(index + 1, sum) recursive(0, 0) if s == 0: count -= 1 print(count)
normal
{ "blob_id": "f1aa12ec4ee2482db8abf1121a3443502544e1a2", "index": 2815, "step-1": "<mask token>\n\n\ndef recursive(index, sum):\n global count\n if index == n:\n if sum == s:\n count += 1\n return\n recursive(index + 1, sum + value[index])\n recursive(index + 1, sum)\n\n\n<mask token>\n", "step-2": "<mask token>\nsys.setrecursionlimit(10 ** 6)\n<mask token>\n\n\ndef recursive(index, sum):\n global count\n if index == n:\n if sum == s:\n count += 1\n return\n recursive(index + 1, sum + value[index])\n recursive(index + 1, sum)\n\n\nrecursive(0, 0)\nif s == 0:\n count -= 1\nprint(count)\n", "step-3": "<mask token>\nsys.setrecursionlimit(10 ** 6)\nn, s = map(int, input().split())\nvalue = list(map(int, input().split()))\ncount = 0\n\n\ndef recursive(index, sum):\n global count\n if index == n:\n if sum == s:\n count += 1\n return\n recursive(index + 1, sum + value[index])\n recursive(index + 1, sum)\n\n\nrecursive(0, 0)\nif s == 0:\n count -= 1\nprint(count)\n", "step-4": "import sys\nsys.setrecursionlimit(10 ** 6)\nn, s = map(int, input().split())\nvalue = list(map(int, input().split()))\ncount = 0\n\n\ndef recursive(index, sum):\n global count\n if index == n:\n if sum == s:\n count += 1\n return\n recursive(index + 1, sum + value[index])\n recursive(index + 1, sum)\n\n\nrecursive(0, 0)\nif s == 0:\n count -= 1\nprint(count)\n", "step-5": null, "step-ids": [ 1, 2, 3, 4 ] }
[ 1, 2, 3, 4 ]
from setup import app, manager from Users.controller import user_controller from Test.controller import test_controller app.register_blueprint(test_controller, url_prefix="/test") #registeting test_controller blueprint with the main "app" and asking it to handle all url that begins with "/test". For eg: http://127.0.0.1/test/anythingcanbehere/orhere/orhere all such urls will go the test_conrtoller file. For now we just have to defined endpoints "test_get", "test_post". Anything else will result in 404 not fond error. app.register_blueprint(user_controller, url_prefix="/") if __name__ == "__main__": app.run(debug=True) #manager.run()
normal
{ "blob_id": "afa22db946f77e9b33a443657592c20fbea21eb1", "index": 6146, "step-1": "<mask token>\n", "step-2": "<mask token>\napp.register_blueprint(test_controller, url_prefix='/test')\napp.register_blueprint(user_controller, url_prefix='/')\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-3": "from setup import app, manager\nfrom Users.controller import user_controller\nfrom Test.controller import test_controller\napp.register_blueprint(test_controller, url_prefix='/test')\napp.register_blueprint(user_controller, url_prefix='/')\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-4": "from setup import app, manager\nfrom Users.controller import user_controller\nfrom Test.controller import test_controller\n\napp.register_blueprint(test_controller, url_prefix=\"/test\") #registeting test_controller blueprint with the main \"app\" and asking it to handle all url that begins with \"/test\". For eg: http://127.0.0.1/test/anythingcanbehere/orhere/orhere all such urls will go the test_conrtoller file. For now we just have to defined endpoints \"test_get\", \"test_post\". Anything else will result in 404 not fond error.\napp.register_blueprint(user_controller, url_prefix=\"/\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n #manager.run()", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# Copyright (c) 2017, Matt Layman import bisect import configparser import os import smartypants from werkzeug.contrib.atom import AtomFeed, FeedEntry from handroll import logger from handroll.exceptions import AbortError from handroll.extensions.base import Extension from handroll.i18n import _ class BlogPost(object): def __init__(self, **kwargs): self.date = kwargs['date'] self.source_file = kwargs['source_file'] self.summary = smartypants.smartypants(kwargs['summary']) self.title = smartypants.smartypants(kwargs['title']) self.route = kwargs['route'] self.url = kwargs['url'] # Having the posts enables a blog post to find its relationships. self._posts = kwargs['posts'] def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __lt__(self, other): return self.date < other.date def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return 'BlogPost({}, {})'.format(self.source_file, self.date) @property def next(self): """Get the next chronological blog post.""" posts_by_date = self.posts_by_date index = bisect.bisect_left(posts_by_date, self) if index + 1 == len(posts_by_date): return None return posts_by_date[index + 1] @property def previous(self): """Get the previous chronological blog post.""" posts_by_date = self.posts_by_date index = bisect.bisect_left(posts_by_date, self) if index == 0: return None return posts_by_date[index - 1] @property def posts_by_date(self): return sorted(self._posts.values(), key=lambda p: p.date) class BlogExtension(Extension): """Track files marked as blog entries and generate a feed.""" handle_frontmatter_loaded = True handle_pre_composition = True handle_post_composition = True required_metadata = { 'author': 'atom_author', 'id': 'atom_id', 'title': 'atom_title', 'url': 'atom_url', } def __init__(self, config): super(BlogExtension, self).__init__(config) self.posts = {} self.atom_metadata = {} self.atom_output = '' self.list_template = None self.list_output = None self._resolver = None self._should_generate = True def on_pre_composition(self, director): """Check that all the required configuration exists.""" if not self._config.parser.has_section('blog'): raise AbortError( _('A blog section is missing in the configuration file.')) # Collect atom feed configuration. for metadata, option in self.required_metadata.items(): self._add_atom_metadata(metadata, option) self.atom_output = self._get_option('atom_output') # Collect HTML listing configuration. if self._config.parser.has_option('blog', 'list_template'): self.list_template = self._get_option('list_template') self.list_output = self._get_option('list_output') # Grab the resolver from the director for determining URLs for posts. self._resolver = director.resolver def on_frontmatter_loaded(self, source_file, frontmatter): """Record any new blog posts.""" if not self._is_post(frontmatter): return self._validate_post(source_file, frontmatter) post = BlogPost( date=frontmatter['date'], source_file=source_file, summary=frontmatter.get('summary', ''), title=frontmatter['title'], route=self._resolver.as_route(source_file), url=self._resolver.as_url(source_file), posts=self.posts, ) frontmatter['post'] = post if post != self.posts.get(source_file): self.posts[source_file] = post self._should_generate = True def on_post_composition(self, director): """Generate blog output.""" if not self._should_generate: return blog_posts = sorted( self.posts.values(), key=lambda p: p.date, reverse=True) self._generate_atom_feed(director, blog_posts) if self.list_template is not None: self._generate_list_page(director, blog_posts) self._should_generate = False def _is_post(self, frontmatter): """Check if the front matter looks like a blog post.""" is_post = frontmatter.get('blog', False) if type(is_post) != bool: raise AbortError( _('Invalid blog frontmatter (expects True or False): ' '{blog_value}').format(blog_value=is_post)) return is_post def _validate_post(self, source_file, frontmatter): """Validate that the post contains all the required fields.""" required = set([ 'date', 'title', ]) fields = set(frontmatter.keys()) missing = required - fields if missing: raise AbortError(_( 'The blog post, {filename}, ' 'is missing required fields: {missing_fields}'.format( filename=source_file, missing_fields=', '.join(missing)))) def _generate_atom_feed(self, director, blog_posts): """Generate the atom feed.""" logger.info(_('Generating Atom XML feed ...')) builder = FeedBuilder(self.atom_metadata) builder.add(blog_posts) output_file = os.path.join(director.outdir, self.atom_output) builder.write_to(output_file) def _generate_list_page(self, director, blog_posts): """Generate the list page.""" logger.info(_('Generating blog list page ...')) template = director.catalog.get_template(self.list_template) builder = ListPageBuilder(template) builder.add(blog_posts) output_file = os.path.join(director.outdir, self.list_output) builder.write_to(output_file) def _add_atom_metadata(self, name, option): """Add atom metadata from the config parser.""" self.atom_metadata[name] = self._get_option(option) def _get_option(self, option): """Get an option out of the blog section.""" try: return self._config.parser.get('blog', option) except configparser.NoOptionError: raise AbortError( _('The blog extension requires the {option} option.').format( option=option)) class BlogBuilder(object): """A template pattern class for generating output related to a blog.""" def _generate_output(self): """Generate output that belongs in the destination file. Subclasses must implement this method. """ raise NotImplementedError() def write_to(self, filepath): """Write the output to the provided filepath.""" output = self._generate_output() with open(filepath, 'wb') as out: out.write(output.encode('utf-8')) out.write(b'<!-- handrolled for excellence -->\n') class FeedBuilder(BlogBuilder): """Transform blog metadata and posts into an Atom feed.""" def __init__(self, metadata): self.metadata = metadata self._feed = AtomFeed(**metadata) def add(self, posts): """Add blog posts to the feed.""" for post in posts: self._feed.add(FeedEntry( summary=post.summary, title=post.title, title_type='html', url=post.url, updated=post.date, )) def _generate_output(self): return self._feed.to_string() class ListPageBuilder(BlogBuilder): """Transform blog posts into a list page.""" def __init__(self, template): self._template = template self._blog_list = '' self._posts = None def add(self, posts): """Add the posts and generate a blog list.""" li_html = [] for post in posts: li_html.append( u'<li><a href="{route}">{title}</a></li>'.format( route=post.route, title=post.title)) self._blog_list = u'\n'.join(li_html) self._posts = posts def _generate_output(self): context = { 'blog_list': self._blog_list, 'posts': self._posts, } return self._template.render(context)
normal
{ "blob_id": "c3d9ad49b62c56dfbd9674cb1ac5c206e6401a27", "index": 830, "step-1": "<mask token>\n\n\nclass BlogBuilder(object):\n <mask token>\n\n def _generate_output(self):\n \"\"\"Generate output that belongs in the destination file.\n\n Subclasses must implement this method.\n \"\"\"\n raise NotImplementedError()\n\n def write_to(self, filepath):\n \"\"\"Write the output to the provided filepath.\"\"\"\n output = self._generate_output()\n with open(filepath, 'wb') as out:\n out.write(output.encode('utf-8'))\n out.write(b'<!-- handrolled for excellence -->\\n')\n\n\nclass FeedBuilder(BlogBuilder):\n \"\"\"Transform blog metadata and posts into an Atom feed.\"\"\"\n\n def __init__(self, metadata):\n self.metadata = metadata\n self._feed = AtomFeed(**metadata)\n\n def add(self, posts):\n \"\"\"Add blog posts to the feed.\"\"\"\n for post in posts:\n self._feed.add(FeedEntry(summary=post.summary, title=post.title,\n title_type='html', url=post.url, updated=post.date))\n\n def _generate_output(self):\n return self._feed.to_string()\n\n\nclass ListPageBuilder(BlogBuilder):\n \"\"\"Transform blog posts into a list page.\"\"\"\n\n def __init__(self, template):\n self._template = template\n self._blog_list = ''\n self._posts = None\n\n def add(self, posts):\n \"\"\"Add the posts and generate a blog list.\"\"\"\n li_html = []\n for post in posts:\n li_html.append(u'<li><a href=\"{route}\">{title}</a></li>'.format\n (route=post.route, title=post.title))\n self._blog_list = u'\\n'.join(li_html)\n self._posts = posts\n\n def _generate_output(self):\n context = {'blog_list': self._blog_list, 'posts': self._posts}\n return self._template.render(context)\n", "step-2": "<mask token>\n\n\nclass BlogExtension(Extension):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, config):\n super(BlogExtension, self).__init__(config)\n self.posts = {}\n self.atom_metadata = {}\n self.atom_output = ''\n self.list_template = None\n self.list_output = None\n self._resolver = None\n self._should_generate = True\n\n def on_pre_composition(self, director):\n \"\"\"Check that all the required configuration exists.\"\"\"\n if not self._config.parser.has_section('blog'):\n raise AbortError(_(\n 'A blog section is missing in the configuration file.'))\n for metadata, option in self.required_metadata.items():\n self._add_atom_metadata(metadata, option)\n self.atom_output = self._get_option('atom_output')\n if self._config.parser.has_option('blog', 'list_template'):\n self.list_template = self._get_option('list_template')\n self.list_output = self._get_option('list_output')\n self._resolver = director.resolver\n <mask token>\n\n def on_post_composition(self, director):\n \"\"\"Generate blog output.\"\"\"\n if not self._should_generate:\n return\n blog_posts = sorted(self.posts.values(), key=lambda p: p.date,\n reverse=True)\n self._generate_atom_feed(director, blog_posts)\n if self.list_template is not None:\n self._generate_list_page(director, blog_posts)\n self._should_generate = False\n\n def _is_post(self, frontmatter):\n \"\"\"Check if the front matter looks like a blog post.\"\"\"\n is_post = frontmatter.get('blog', False)\n if type(is_post) != bool:\n raise AbortError(_(\n 'Invalid blog frontmatter (expects True or False): {blog_value}'\n ).format(blog_value=is_post))\n return is_post\n\n def _validate_post(self, source_file, frontmatter):\n \"\"\"Validate that the post contains all the required fields.\"\"\"\n required = set(['date', 'title'])\n fields = set(frontmatter.keys())\n missing = required - fields\n if missing:\n raise AbortError(_(\n 'The blog post, {filename}, is missing required fields: {missing_fields}'\n .format(filename=source_file, missing_fields=', '.join(\n missing))))\n\n def _generate_atom_feed(self, director, blog_posts):\n \"\"\"Generate the atom feed.\"\"\"\n logger.info(_('Generating Atom XML feed ...'))\n builder = FeedBuilder(self.atom_metadata)\n builder.add(blog_posts)\n output_file = os.path.join(director.outdir, self.atom_output)\n builder.write_to(output_file)\n\n def _generate_list_page(self, director, blog_posts):\n \"\"\"Generate the list page.\"\"\"\n logger.info(_('Generating blog list page ...'))\n template = director.catalog.get_template(self.list_template)\n builder = ListPageBuilder(template)\n builder.add(blog_posts)\n output_file = os.path.join(director.outdir, self.list_output)\n builder.write_to(output_file)\n\n def _add_atom_metadata(self, name, option):\n \"\"\"Add atom metadata from the config parser.\"\"\"\n self.atom_metadata[name] = self._get_option(option)\n\n def _get_option(self, option):\n \"\"\"Get an option out of the blog section.\"\"\"\n try:\n return self._config.parser.get('blog', option)\n except configparser.NoOptionError:\n raise AbortError(_(\n 'The blog extension requires the {option} option.').format(\n option=option))\n\n\nclass BlogBuilder(object):\n \"\"\"A template pattern class for generating output related to a blog.\"\"\"\n\n def _generate_output(self):\n \"\"\"Generate output that belongs in the destination file.\n\n Subclasses must implement this method.\n \"\"\"\n raise NotImplementedError()\n\n def write_to(self, filepath):\n \"\"\"Write the output to the provided filepath.\"\"\"\n output = self._generate_output()\n with open(filepath, 'wb') as out:\n out.write(output.encode('utf-8'))\n out.write(b'<!-- handrolled for excellence -->\\n')\n\n\nclass FeedBuilder(BlogBuilder):\n \"\"\"Transform blog metadata and posts into an Atom feed.\"\"\"\n\n def __init__(self, metadata):\n self.metadata = metadata\n self._feed = AtomFeed(**metadata)\n\n def add(self, posts):\n \"\"\"Add blog posts to the feed.\"\"\"\n for post in posts:\n self._feed.add(FeedEntry(summary=post.summary, title=post.title,\n title_type='html', url=post.url, updated=post.date))\n\n def _generate_output(self):\n return self._feed.to_string()\n\n\nclass ListPageBuilder(BlogBuilder):\n \"\"\"Transform blog posts into a list page.\"\"\"\n\n def __init__(self, template):\n self._template = template\n self._blog_list = ''\n self._posts = None\n\n def add(self, posts):\n \"\"\"Add the posts and generate a blog list.\"\"\"\n li_html = []\n for post in posts:\n li_html.append(u'<li><a href=\"{route}\">{title}</a></li>'.format\n (route=post.route, title=post.title))\n self._blog_list = u'\\n'.join(li_html)\n self._posts = posts\n\n def _generate_output(self):\n context = {'blog_list': self._blog_list, 'posts': self._posts}\n return self._template.render(context)\n", "step-3": "<mask token>\n\n\nclass BlogPost(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass BlogExtension(Extension):\n \"\"\"Track files marked as blog entries and generate a feed.\"\"\"\n handle_frontmatter_loaded = True\n handle_pre_composition = True\n handle_post_composition = True\n required_metadata = {'author': 'atom_author', 'id': 'atom_id', 'title':\n 'atom_title', 'url': 'atom_url'}\n\n def __init__(self, config):\n super(BlogExtension, self).__init__(config)\n self.posts = {}\n self.atom_metadata = {}\n self.atom_output = ''\n self.list_template = None\n self.list_output = None\n self._resolver = None\n self._should_generate = True\n\n def on_pre_composition(self, director):\n \"\"\"Check that all the required configuration exists.\"\"\"\n if not self._config.parser.has_section('blog'):\n raise AbortError(_(\n 'A blog section is missing in the configuration file.'))\n for metadata, option in self.required_metadata.items():\n self._add_atom_metadata(metadata, option)\n self.atom_output = self._get_option('atom_output')\n if self._config.parser.has_option('blog', 'list_template'):\n self.list_template = self._get_option('list_template')\n self.list_output = self._get_option('list_output')\n self._resolver = director.resolver\n\n def on_frontmatter_loaded(self, source_file, frontmatter):\n \"\"\"Record any new blog posts.\"\"\"\n if not self._is_post(frontmatter):\n return\n self._validate_post(source_file, frontmatter)\n post = BlogPost(date=frontmatter['date'], source_file=source_file,\n summary=frontmatter.get('summary', ''), title=frontmatter[\n 'title'], route=self._resolver.as_route(source_file), url=self.\n _resolver.as_url(source_file), posts=self.posts)\n frontmatter['post'] = post\n if post != self.posts.get(source_file):\n self.posts[source_file] = post\n self._should_generate = True\n\n def on_post_composition(self, director):\n \"\"\"Generate blog output.\"\"\"\n if not self._should_generate:\n return\n blog_posts = sorted(self.posts.values(), key=lambda p: p.date,\n reverse=True)\n self._generate_atom_feed(director, blog_posts)\n if self.list_template is not None:\n self._generate_list_page(director, blog_posts)\n self._should_generate = False\n\n def _is_post(self, frontmatter):\n \"\"\"Check if the front matter looks like a blog post.\"\"\"\n is_post = frontmatter.get('blog', False)\n if type(is_post) != bool:\n raise AbortError(_(\n 'Invalid blog frontmatter (expects True or False): {blog_value}'\n ).format(blog_value=is_post))\n return is_post\n\n def _validate_post(self, source_file, frontmatter):\n \"\"\"Validate that the post contains all the required fields.\"\"\"\n required = set(['date', 'title'])\n fields = set(frontmatter.keys())\n missing = required - fields\n if missing:\n raise AbortError(_(\n 'The blog post, {filename}, is missing required fields: {missing_fields}'\n .format(filename=source_file, missing_fields=', '.join(\n missing))))\n\n def _generate_atom_feed(self, director, blog_posts):\n \"\"\"Generate the atom feed.\"\"\"\n logger.info(_('Generating Atom XML feed ...'))\n builder = FeedBuilder(self.atom_metadata)\n builder.add(blog_posts)\n output_file = os.path.join(director.outdir, self.atom_output)\n builder.write_to(output_file)\n\n def _generate_list_page(self, director, blog_posts):\n \"\"\"Generate the list page.\"\"\"\n logger.info(_('Generating blog list page ...'))\n template = director.catalog.get_template(self.list_template)\n builder = ListPageBuilder(template)\n builder.add(blog_posts)\n output_file = os.path.join(director.outdir, self.list_output)\n builder.write_to(output_file)\n\n def _add_atom_metadata(self, name, option):\n \"\"\"Add atom metadata from the config parser.\"\"\"\n self.atom_metadata[name] = self._get_option(option)\n\n def _get_option(self, option):\n \"\"\"Get an option out of the blog section.\"\"\"\n try:\n return self._config.parser.get('blog', option)\n except configparser.NoOptionError:\n raise AbortError(_(\n 'The blog extension requires the {option} option.').format(\n option=option))\n\n\nclass BlogBuilder(object):\n \"\"\"A template pattern class for generating output related to a blog.\"\"\"\n\n def _generate_output(self):\n \"\"\"Generate output that belongs in the destination file.\n\n Subclasses must implement this method.\n \"\"\"\n raise NotImplementedError()\n\n def write_to(self, filepath):\n \"\"\"Write the output to the provided filepath.\"\"\"\n output = self._generate_output()\n with open(filepath, 'wb') as out:\n out.write(output.encode('utf-8'))\n out.write(b'<!-- handrolled for excellence -->\\n')\n\n\nclass FeedBuilder(BlogBuilder):\n \"\"\"Transform blog metadata and posts into an Atom feed.\"\"\"\n\n def __init__(self, metadata):\n self.metadata = metadata\n self._feed = AtomFeed(**metadata)\n\n def add(self, posts):\n \"\"\"Add blog posts to the feed.\"\"\"\n for post in posts:\n self._feed.add(FeedEntry(summary=post.summary, title=post.title,\n title_type='html', url=post.url, updated=post.date))\n\n def _generate_output(self):\n return self._feed.to_string()\n\n\nclass ListPageBuilder(BlogBuilder):\n \"\"\"Transform blog posts into a list page.\"\"\"\n\n def __init__(self, template):\n self._template = template\n self._blog_list = ''\n self._posts = None\n\n def add(self, posts):\n \"\"\"Add the posts and generate a blog list.\"\"\"\n li_html = []\n for post in posts:\n li_html.append(u'<li><a href=\"{route}\">{title}</a></li>'.format\n (route=post.route, title=post.title))\n self._blog_list = u'\\n'.join(li_html)\n self._posts = posts\n\n def _generate_output(self):\n context = {'blog_list': self._blog_list, 'posts': self._posts}\n return self._template.render(context)\n", "step-4": "<mask token>\n\n\nclass BlogPost(object):\n\n def __init__(self, **kwargs):\n self.date = kwargs['date']\n self.source_file = kwargs['source_file']\n self.summary = smartypants.smartypants(kwargs['summary'])\n self.title = smartypants.smartypants(kwargs['title'])\n self.route = kwargs['route']\n self.url = kwargs['url']\n self._posts = kwargs['posts']\n <mask token>\n\n def __lt__(self, other):\n return self.date < other.date\n\n def __ne__(self, other):\n return not self.__eq__(other)\n <mask token>\n\n @property\n def next(self):\n \"\"\"Get the next chronological blog post.\"\"\"\n posts_by_date = self.posts_by_date\n index = bisect.bisect_left(posts_by_date, self)\n if index + 1 == len(posts_by_date):\n return None\n return posts_by_date[index + 1]\n <mask token>\n <mask token>\n\n\nclass BlogExtension(Extension):\n \"\"\"Track files marked as blog entries and generate a feed.\"\"\"\n handle_frontmatter_loaded = True\n handle_pre_composition = True\n handle_post_composition = True\n required_metadata = {'author': 'atom_author', 'id': 'atom_id', 'title':\n 'atom_title', 'url': 'atom_url'}\n\n def __init__(self, config):\n super(BlogExtension, self).__init__(config)\n self.posts = {}\n self.atom_metadata = {}\n self.atom_output = ''\n self.list_template = None\n self.list_output = None\n self._resolver = None\n self._should_generate = True\n\n def on_pre_composition(self, director):\n \"\"\"Check that all the required configuration exists.\"\"\"\n if not self._config.parser.has_section('blog'):\n raise AbortError(_(\n 'A blog section is missing in the configuration file.'))\n for metadata, option in self.required_metadata.items():\n self._add_atom_metadata(metadata, option)\n self.atom_output = self._get_option('atom_output')\n if self._config.parser.has_option('blog', 'list_template'):\n self.list_template = self._get_option('list_template')\n self.list_output = self._get_option('list_output')\n self._resolver = director.resolver\n\n def on_frontmatter_loaded(self, source_file, frontmatter):\n \"\"\"Record any new blog posts.\"\"\"\n if not self._is_post(frontmatter):\n return\n self._validate_post(source_file, frontmatter)\n post = BlogPost(date=frontmatter['date'], source_file=source_file,\n summary=frontmatter.get('summary', ''), title=frontmatter[\n 'title'], route=self._resolver.as_route(source_file), url=self.\n _resolver.as_url(source_file), posts=self.posts)\n frontmatter['post'] = post\n if post != self.posts.get(source_file):\n self.posts[source_file] = post\n self._should_generate = True\n\n def on_post_composition(self, director):\n \"\"\"Generate blog output.\"\"\"\n if not self._should_generate:\n return\n blog_posts = sorted(self.posts.values(), key=lambda p: p.date,\n reverse=True)\n self._generate_atom_feed(director, blog_posts)\n if self.list_template is not None:\n self._generate_list_page(director, blog_posts)\n self._should_generate = False\n\n def _is_post(self, frontmatter):\n \"\"\"Check if the front matter looks like a blog post.\"\"\"\n is_post = frontmatter.get('blog', False)\n if type(is_post) != bool:\n raise AbortError(_(\n 'Invalid blog frontmatter (expects True or False): {blog_value}'\n ).format(blog_value=is_post))\n return is_post\n\n def _validate_post(self, source_file, frontmatter):\n \"\"\"Validate that the post contains all the required fields.\"\"\"\n required = set(['date', 'title'])\n fields = set(frontmatter.keys())\n missing = required - fields\n if missing:\n raise AbortError(_(\n 'The blog post, {filename}, is missing required fields: {missing_fields}'\n .format(filename=source_file, missing_fields=', '.join(\n missing))))\n\n def _generate_atom_feed(self, director, blog_posts):\n \"\"\"Generate the atom feed.\"\"\"\n logger.info(_('Generating Atom XML feed ...'))\n builder = FeedBuilder(self.atom_metadata)\n builder.add(blog_posts)\n output_file = os.path.join(director.outdir, self.atom_output)\n builder.write_to(output_file)\n\n def _generate_list_page(self, director, blog_posts):\n \"\"\"Generate the list page.\"\"\"\n logger.info(_('Generating blog list page ...'))\n template = director.catalog.get_template(self.list_template)\n builder = ListPageBuilder(template)\n builder.add(blog_posts)\n output_file = os.path.join(director.outdir, self.list_output)\n builder.write_to(output_file)\n\n def _add_atom_metadata(self, name, option):\n \"\"\"Add atom metadata from the config parser.\"\"\"\n self.atom_metadata[name] = self._get_option(option)\n\n def _get_option(self, option):\n \"\"\"Get an option out of the blog section.\"\"\"\n try:\n return self._config.parser.get('blog', option)\n except configparser.NoOptionError:\n raise AbortError(_(\n 'The blog extension requires the {option} option.').format(\n option=option))\n\n\nclass BlogBuilder(object):\n \"\"\"A template pattern class for generating output related to a blog.\"\"\"\n\n def _generate_output(self):\n \"\"\"Generate output that belongs in the destination file.\n\n Subclasses must implement this method.\n \"\"\"\n raise NotImplementedError()\n\n def write_to(self, filepath):\n \"\"\"Write the output to the provided filepath.\"\"\"\n output = self._generate_output()\n with open(filepath, 'wb') as out:\n out.write(output.encode('utf-8'))\n out.write(b'<!-- handrolled for excellence -->\\n')\n\n\nclass FeedBuilder(BlogBuilder):\n \"\"\"Transform blog metadata and posts into an Atom feed.\"\"\"\n\n def __init__(self, metadata):\n self.metadata = metadata\n self._feed = AtomFeed(**metadata)\n\n def add(self, posts):\n \"\"\"Add blog posts to the feed.\"\"\"\n for post in posts:\n self._feed.add(FeedEntry(summary=post.summary, title=post.title,\n title_type='html', url=post.url, updated=post.date))\n\n def _generate_output(self):\n return self._feed.to_string()\n\n\nclass ListPageBuilder(BlogBuilder):\n \"\"\"Transform blog posts into a list page.\"\"\"\n\n def __init__(self, template):\n self._template = template\n self._blog_list = ''\n self._posts = None\n\n def add(self, posts):\n \"\"\"Add the posts and generate a blog list.\"\"\"\n li_html = []\n for post in posts:\n li_html.append(u'<li><a href=\"{route}\">{title}</a></li>'.format\n (route=post.route, title=post.title))\n self._blog_list = u'\\n'.join(li_html)\n self._posts = posts\n\n def _generate_output(self):\n context = {'blog_list': self._blog_list, 'posts': self._posts}\n return self._template.render(context)\n", "step-5": "# Copyright (c) 2017, Matt Layman\n\nimport bisect\nimport configparser\nimport os\n\nimport smartypants\nfrom werkzeug.contrib.atom import AtomFeed, FeedEntry\n\nfrom handroll import logger\nfrom handroll.exceptions import AbortError\nfrom handroll.extensions.base import Extension\nfrom handroll.i18n import _\n\n\nclass BlogPost(object):\n\n def __init__(self, **kwargs):\n self.date = kwargs['date']\n self.source_file = kwargs['source_file']\n self.summary = smartypants.smartypants(kwargs['summary'])\n self.title = smartypants.smartypants(kwargs['title'])\n self.route = kwargs['route']\n self.url = kwargs['url']\n # Having the posts enables a blog post to find its relationships.\n self._posts = kwargs['posts']\n\n def __eq__(self, other):\n if other is None:\n return False\n return self.__dict__ == other.__dict__\n\n def __lt__(self, other):\n return self.date < other.date\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __repr__(self):\n return 'BlogPost({}, {})'.format(self.source_file, self.date)\n\n @property\n def next(self):\n \"\"\"Get the next chronological blog post.\"\"\"\n posts_by_date = self.posts_by_date\n index = bisect.bisect_left(posts_by_date, self)\n if index + 1 == len(posts_by_date):\n return None\n return posts_by_date[index + 1]\n\n @property\n def previous(self):\n \"\"\"Get the previous chronological blog post.\"\"\"\n posts_by_date = self.posts_by_date\n index = bisect.bisect_left(posts_by_date, self)\n if index == 0:\n return None\n return posts_by_date[index - 1]\n\n @property\n def posts_by_date(self):\n return sorted(self._posts.values(), key=lambda p: p.date)\n\n\nclass BlogExtension(Extension):\n \"\"\"Track files marked as blog entries and generate a feed.\"\"\"\n\n handle_frontmatter_loaded = True\n handle_pre_composition = True\n handle_post_composition = True\n\n required_metadata = {\n 'author': 'atom_author',\n 'id': 'atom_id',\n 'title': 'atom_title',\n 'url': 'atom_url',\n }\n\n def __init__(self, config):\n super(BlogExtension, self).__init__(config)\n self.posts = {}\n self.atom_metadata = {}\n self.atom_output = ''\n self.list_template = None\n self.list_output = None\n self._resolver = None\n self._should_generate = True\n\n def on_pre_composition(self, director):\n \"\"\"Check that all the required configuration exists.\"\"\"\n if not self._config.parser.has_section('blog'):\n raise AbortError(\n _('A blog section is missing in the configuration file.'))\n\n # Collect atom feed configuration.\n for metadata, option in self.required_metadata.items():\n self._add_atom_metadata(metadata, option)\n self.atom_output = self._get_option('atom_output')\n\n # Collect HTML listing configuration.\n if self._config.parser.has_option('blog', 'list_template'):\n self.list_template = self._get_option('list_template')\n self.list_output = self._get_option('list_output')\n\n # Grab the resolver from the director for determining URLs for posts.\n self._resolver = director.resolver\n\n def on_frontmatter_loaded(self, source_file, frontmatter):\n \"\"\"Record any new blog posts.\"\"\"\n if not self._is_post(frontmatter):\n return\n self._validate_post(source_file, frontmatter)\n post = BlogPost(\n date=frontmatter['date'],\n source_file=source_file,\n summary=frontmatter.get('summary', ''),\n title=frontmatter['title'],\n route=self._resolver.as_route(source_file),\n url=self._resolver.as_url(source_file),\n posts=self.posts,\n )\n frontmatter['post'] = post\n if post != self.posts.get(source_file):\n self.posts[source_file] = post\n self._should_generate = True\n\n def on_post_composition(self, director):\n \"\"\"Generate blog output.\"\"\"\n if not self._should_generate:\n return\n blog_posts = sorted(\n self.posts.values(), key=lambda p: p.date, reverse=True)\n self._generate_atom_feed(director, blog_posts)\n if self.list_template is not None:\n self._generate_list_page(director, blog_posts)\n self._should_generate = False\n\n def _is_post(self, frontmatter):\n \"\"\"Check if the front matter looks like a blog post.\"\"\"\n is_post = frontmatter.get('blog', False)\n if type(is_post) != bool:\n raise AbortError(\n _('Invalid blog frontmatter (expects True or False): '\n '{blog_value}').format(blog_value=is_post))\n return is_post\n\n def _validate_post(self, source_file, frontmatter):\n \"\"\"Validate that the post contains all the required fields.\"\"\"\n required = set([\n 'date',\n 'title',\n ])\n fields = set(frontmatter.keys())\n missing = required - fields\n if missing:\n raise AbortError(_(\n 'The blog post, {filename}, '\n 'is missing required fields: {missing_fields}'.format(\n filename=source_file, missing_fields=', '.join(missing))))\n\n def _generate_atom_feed(self, director, blog_posts):\n \"\"\"Generate the atom feed.\"\"\"\n logger.info(_('Generating Atom XML feed ...'))\n builder = FeedBuilder(self.atom_metadata)\n builder.add(blog_posts)\n output_file = os.path.join(director.outdir, self.atom_output)\n builder.write_to(output_file)\n\n def _generate_list_page(self, director, blog_posts):\n \"\"\"Generate the list page.\"\"\"\n logger.info(_('Generating blog list page ...'))\n template = director.catalog.get_template(self.list_template)\n builder = ListPageBuilder(template)\n builder.add(blog_posts)\n output_file = os.path.join(director.outdir, self.list_output)\n builder.write_to(output_file)\n\n def _add_atom_metadata(self, name, option):\n \"\"\"Add atom metadata from the config parser.\"\"\"\n self.atom_metadata[name] = self._get_option(option)\n\n def _get_option(self, option):\n \"\"\"Get an option out of the blog section.\"\"\"\n try:\n return self._config.parser.get('blog', option)\n except configparser.NoOptionError:\n raise AbortError(\n _('The blog extension requires the {option} option.').format(\n option=option))\n\n\nclass BlogBuilder(object):\n \"\"\"A template pattern class for generating output related to a blog.\"\"\"\n\n def _generate_output(self):\n \"\"\"Generate output that belongs in the destination file.\n\n Subclasses must implement this method.\n \"\"\"\n raise NotImplementedError()\n\n def write_to(self, filepath):\n \"\"\"Write the output to the provided filepath.\"\"\"\n output = self._generate_output()\n with open(filepath, 'wb') as out:\n out.write(output.encode('utf-8'))\n out.write(b'<!-- handrolled for excellence -->\\n')\n\n\nclass FeedBuilder(BlogBuilder):\n \"\"\"Transform blog metadata and posts into an Atom feed.\"\"\"\n\n def __init__(self, metadata):\n self.metadata = metadata\n self._feed = AtomFeed(**metadata)\n\n def add(self, posts):\n \"\"\"Add blog posts to the feed.\"\"\"\n for post in posts:\n self._feed.add(FeedEntry(\n summary=post.summary,\n title=post.title,\n title_type='html',\n url=post.url,\n updated=post.date,\n ))\n\n def _generate_output(self):\n return self._feed.to_string()\n\n\nclass ListPageBuilder(BlogBuilder):\n \"\"\"Transform blog posts into a list page.\"\"\"\n\n def __init__(self, template):\n self._template = template\n self._blog_list = ''\n self._posts = None\n\n def add(self, posts):\n \"\"\"Add the posts and generate a blog list.\"\"\"\n li_html = []\n for post in posts:\n li_html.append(\n u'<li><a href=\"{route}\">{title}</a></li>'.format(\n route=post.route, title=post.title))\n self._blog_list = u'\\n'.join(li_html)\n self._posts = posts\n\n def _generate_output(self):\n context = {\n 'blog_list': self._blog_list,\n 'posts': self._posts,\n }\n return self._template.render(context)\n", "step-ids": [ 13, 24, 28, 32, 38 ] }
[ 13, 24, 28, 32, 38 ]
<|reserved_special_token_0|> class StudentListView(ListView): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def get_queryset(self): return Student.objects.filter(course='Python') <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class StudentListView(ListView): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def get_queryset(self): return Student.objects.filter(course='Python') def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['freshers'] = Student.objects.all().order_by('name') return context def get_template_names(self): if self.request.COOKIES['user'] == 'farzam': template_name = 'staff/farzam.html' else: template_name = self.template_name return template_name <|reserved_special_token_1|> <|reserved_special_token_0|> class StudentListView(ListView): model = Student template_name = 'staff/student_list.html' ordering = ['name'] def get_queryset(self): return Student.objects.filter(course='Python') def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['freshers'] = Student.objects.all().order_by('name') return context def get_template_names(self): if self.request.COOKIES['user'] == 'farzam': template_name = 'staff/farzam.html' else: template_name = self.template_name return template_name <|reserved_special_token_1|> from django.shortcuts import render from django.views.generic.list import ListView from .models import Student class StudentListView(ListView): model = Student template_name = 'staff/student_list.html' ordering = ['name'] def get_queryset(self): return Student.objects.filter(course='Python') def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['freshers'] = Student.objects.all().order_by('name') return context def get_template_names(self): if self.request.COOKIES['user'] == 'farzam': template_name = 'staff/farzam.html' else: template_name = self.template_name return template_name <|reserved_special_token_1|> from django.shortcuts import render from django.views.generic.list import ListView from .models import Student # Create your views here. class StudentListView(ListView): model = Student # Custom has a HIGH priority than default in any field template_name = 'staff/student_list.html' # template_name_suffix = '_list' ordering = ['name'] # context_object_name = 'students' def get_queryset(self): return Student.objects.filter(course='Python') def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['freshers'] = Student.objects.all().order_by('name') return context def get_template_names(self): # if self.request.user.is_superuser: # template_name = 'staff/admin.html' # elif self.request.user.is_staff: # template_name = 'staff/staff.html' # else: # template_name = self.template_name # return template_name if self.request.COOKIES['user'] == 'farzam': template_name = 'staff/farzam.html' else: template_name = self.template_name return template_name
flexible
{ "blob_id": "bcad9869e6bc9b17eee490897b4b706171381366", "index": 2093, "step-1": "<mask token>\n\n\nclass StudentListView(ListView):\n <mask token>\n <mask token>\n <mask token>\n\n def get_queryset(self):\n return Student.objects.filter(course='Python')\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass StudentListView(ListView):\n <mask token>\n <mask token>\n <mask token>\n\n def get_queryset(self):\n return Student.objects.filter(course='Python')\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n context['freshers'] = Student.objects.all().order_by('name')\n return context\n\n def get_template_names(self):\n if self.request.COOKIES['user'] == 'farzam':\n template_name = 'staff/farzam.html'\n else:\n template_name = self.template_name\n return template_name\n", "step-3": "<mask token>\n\n\nclass StudentListView(ListView):\n model = Student\n template_name = 'staff/student_list.html'\n ordering = ['name']\n\n def get_queryset(self):\n return Student.objects.filter(course='Python')\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n context['freshers'] = Student.objects.all().order_by('name')\n return context\n\n def get_template_names(self):\n if self.request.COOKIES['user'] == 'farzam':\n template_name = 'staff/farzam.html'\n else:\n template_name = self.template_name\n return template_name\n", "step-4": "from django.shortcuts import render\nfrom django.views.generic.list import ListView\nfrom .models import Student\n\n\nclass StudentListView(ListView):\n model = Student\n template_name = 'staff/student_list.html'\n ordering = ['name']\n\n def get_queryset(self):\n return Student.objects.filter(course='Python')\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n context['freshers'] = Student.objects.all().order_by('name')\n return context\n\n def get_template_names(self):\n if self.request.COOKIES['user'] == 'farzam':\n template_name = 'staff/farzam.html'\n else:\n template_name = self.template_name\n return template_name\n", "step-5": "from django.shortcuts import render\nfrom django.views.generic.list import ListView\nfrom .models import Student\n\n# Create your views here.\nclass StudentListView(ListView):\n model = Student\n\n # Custom has a HIGH priority than default in any field\n\n template_name = 'staff/student_list.html'\n # template_name_suffix = '_list'\n ordering = ['name']\n # context_object_name = 'students'\n\n def get_queryset(self):\n return Student.objects.filter(course='Python')\n\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n context['freshers'] = Student.objects.all().order_by('name')\n\n return context\n\n\n def get_template_names(self):\n # if self.request.user.is_superuser:\n # template_name = 'staff/admin.html'\n # elif self.request.user.is_staff:\n # template_name = 'staff/staff.html'\n # else:\n # template_name = self.template_name\n # return template_name\n\n\n if self.request.COOKIES['user'] == 'farzam':\n template_name = 'staff/farzam.html'\n else:\n template_name = self.template_name\n\n return template_name", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
from flask import Blueprint, request, make_response from untils import restful, cacheuntil from untils.captcha import Captcha from exts import smsapi from .forms import SMSCaptchaForm from io import BytesIO bp = Blueprint('common', __name__, url_prefix='/c') # @bp.route('/sms_captcha/', methods=['post']) # def sms_captcha(): # telephone = request.form.get('telephone') # if not telephone: # return restful.params_error(message='请传入手机号码!') # code = Captcha.gene_text(number=4) # TODO: 获取随机4位数字字符串 # resp = smsapi.send_sms(telephone=telephone, param=code) # if resp: # return restful.success(message='短信验证码发送成功!') # else: # return restful.params_error(message='短信验证码发送失败!') # TODO: 发送短信验证码 @bp.route('/sms_captcha/', methods=['post']) def sms_captcha(): form = SMSCaptchaForm(request.form) if form.validate(): telephone = form.telephone.data # TODO: 获取手机号 code = Captcha.gene_text(number=4) # TODO: 获取随机4位数字字符串 resp = smsapi.send_sms(telephone=telephone, param=code) if resp: cacheuntil.set(telephone, code) # TODO: redis存储短信验证码 return restful.success(message='短信验证码发送成功!') else: return restful.params_error(message='短信验证码发送失败!') else: return restful.params_error(message=form.get_random_error(), data=form.get_all_errors()) # TODO: 图形验证码视图 @bp.route('/captcha/') def CaptchaView(): text, image = Captcha.gene_graph_captcha() cacheuntil.set(text.lower(), text.lower()) # TODO: redis存储图片验证码 out = BytesIO() # TODO: 将图片保存到IO中格式png image.save(out, 'png') # TODO: 保存完毕后,移动指针到起始位置 out.seek(0) # TODO: 将IO读取出来转为image/png响应 resp = make_response(out.read()) resp.content_type = 'image/png' return resp
normal
{ "blob_id": "856beaf3b9dad333d5b48c1be3a8ad917f8d020c", "index": 3634, "step-1": "<mask token>\n\n\n@bp.route('/captcha/')\ndef CaptchaView():\n text, image = Captcha.gene_graph_captcha()\n cacheuntil.set(text.lower(), text.lower())\n out = BytesIO()\n image.save(out, 'png')\n out.seek(0)\n resp = make_response(out.read())\n resp.content_type = 'image/png'\n return resp\n", "step-2": "<mask token>\n\n\n@bp.route('/sms_captcha/', methods=['post'])\ndef sms_captcha():\n form = SMSCaptchaForm(request.form)\n if form.validate():\n telephone = form.telephone.data\n code = Captcha.gene_text(number=4)\n resp = smsapi.send_sms(telephone=telephone, param=code)\n if resp:\n cacheuntil.set(telephone, code)\n return restful.success(message='短信验证码发送成功!')\n else:\n return restful.params_error(message='短信验证码发送失败!')\n else:\n return restful.params_error(message=form.get_random_error(), data=\n form.get_all_errors())\n\n\n@bp.route('/captcha/')\ndef CaptchaView():\n text, image = Captcha.gene_graph_captcha()\n cacheuntil.set(text.lower(), text.lower())\n out = BytesIO()\n image.save(out, 'png')\n out.seek(0)\n resp = make_response(out.read())\n resp.content_type = 'image/png'\n return resp\n", "step-3": "<mask token>\nbp = Blueprint('common', __name__, url_prefix='/c')\n\n\n@bp.route('/sms_captcha/', methods=['post'])\ndef sms_captcha():\n form = SMSCaptchaForm(request.form)\n if form.validate():\n telephone = form.telephone.data\n code = Captcha.gene_text(number=4)\n resp = smsapi.send_sms(telephone=telephone, param=code)\n if resp:\n cacheuntil.set(telephone, code)\n return restful.success(message='短信验证码发送成功!')\n else:\n return restful.params_error(message='短信验证码发送失败!')\n else:\n return restful.params_error(message=form.get_random_error(), data=\n form.get_all_errors())\n\n\n@bp.route('/captcha/')\ndef CaptchaView():\n text, image = Captcha.gene_graph_captcha()\n cacheuntil.set(text.lower(), text.lower())\n out = BytesIO()\n image.save(out, 'png')\n out.seek(0)\n resp = make_response(out.read())\n resp.content_type = 'image/png'\n return resp\n", "step-4": "from flask import Blueprint, request, make_response\nfrom untils import restful, cacheuntil\nfrom untils.captcha import Captcha\nfrom exts import smsapi\nfrom .forms import SMSCaptchaForm\nfrom io import BytesIO\nbp = Blueprint('common', __name__, url_prefix='/c')\n\n\n@bp.route('/sms_captcha/', methods=['post'])\ndef sms_captcha():\n form = SMSCaptchaForm(request.form)\n if form.validate():\n telephone = form.telephone.data\n code = Captcha.gene_text(number=4)\n resp = smsapi.send_sms(telephone=telephone, param=code)\n if resp:\n cacheuntil.set(telephone, code)\n return restful.success(message='短信验证码发送成功!')\n else:\n return restful.params_error(message='短信验证码发送失败!')\n else:\n return restful.params_error(message=form.get_random_error(), data=\n form.get_all_errors())\n\n\n@bp.route('/captcha/')\ndef CaptchaView():\n text, image = Captcha.gene_graph_captcha()\n cacheuntil.set(text.lower(), text.lower())\n out = BytesIO()\n image.save(out, 'png')\n out.seek(0)\n resp = make_response(out.read())\n resp.content_type = 'image/png'\n return resp\n", "step-5": "from flask import Blueprint, request, make_response\nfrom untils import restful, cacheuntil\nfrom untils.captcha import Captcha\nfrom exts import smsapi\nfrom .forms import SMSCaptchaForm\nfrom io import BytesIO\n\nbp = Blueprint('common', __name__, url_prefix='/c')\n\n\n# @bp.route('/sms_captcha/', methods=['post'])\n# def sms_captcha():\n# telephone = request.form.get('telephone')\n# if not telephone:\n# return restful.params_error(message='请传入手机号码!')\n# code = Captcha.gene_text(number=4) # TODO: 获取随机4位数字字符串\n# resp = smsapi.send_sms(telephone=telephone, param=code)\n# if resp:\n# return restful.success(message='短信验证码发送成功!')\n# else:\n# return restful.params_error(message='短信验证码发送失败!')\n\n\n# TODO: 发送短信验证码\n@bp.route('/sms_captcha/', methods=['post'])\ndef sms_captcha():\n form = SMSCaptchaForm(request.form)\n if form.validate():\n telephone = form.telephone.data # TODO: 获取手机号\n code = Captcha.gene_text(number=4) # TODO: 获取随机4位数字字符串\n resp = smsapi.send_sms(telephone=telephone, param=code)\n if resp:\n cacheuntil.set(telephone, code) # TODO: redis存储短信验证码\n return restful.success(message='短信验证码发送成功!')\n else:\n return restful.params_error(message='短信验证码发送失败!')\n else:\n return restful.params_error(message=form.get_random_error(), data=form.get_all_errors())\n\n\n# TODO: 图形验证码视图\n@bp.route('/captcha/')\ndef CaptchaView():\n text, image = Captcha.gene_graph_captcha()\n cacheuntil.set(text.lower(), text.lower()) # TODO: redis存储图片验证码\n out = BytesIO()\n # TODO: 将图片保存到IO中格式png\n image.save(out, 'png')\n # TODO: 保存完毕后,移动指针到起始位置\n out.seek(0)\n # TODO: 将IO读取出来转为image/png响应\n resp = make_response(out.read())\n resp.content_type = 'image/png'\n return resp\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
from typing import Sized import pygame import time from pygame.locals import * import random SIZE = 20 BACKGROUND = (45, 34, 44) W = 800 H = 400 SCREEN = (W, H) class Snake: def __init__(self, parent_screen, length): self.parent_screen = parent_screen self.length = length self.snake = pygame.image.load( "resources/snake.png").convert() # inserting snake image self.snake_x = [W//2]*length # list with 'length' number of elements self.snake_y = [H//2]*length self.direction = "left" # default direction LEFT def increase_length(self): self.length += 1 # adds another block to snake # appends a random value to the list...cause it will change immidiately in 'move()' method self.snake_x.append(0) self.snake_y.append(0) def draw(self): # self.parent_screen.fill(BACKGROUND) for i in range(self.length): self.parent_screen.blit( self.snake, (self.snake_x[i], self.snake_y[i])) # drawing snake pygame.display.flip() def move(self): # Logic gor moving the TAIL snakes [like 2nd snake will come to 1st pos, 3rd will move to 2nd pos.] for i in range(self.length-1, 0, -1): # reverse for loop self.snake_x[i] = self.snake_x[i-1] self.snake_y[i] = self.snake_y[i-1] # Logic for moving the head snakes if self.direction == 'up': self.snake_y[0] -= SIZE if self.direction == 'down': self.snake_y[0] += SIZE if self.direction == 'right': self.snake_x[0] += SIZE if self.direction == 'left': self.snake_x[0] -= SIZE self.draw() def move_up(self): self.direction = 'up' def move_down(self): self.direction = 'down' def move_right(self): self.direction = 'right' def move_left(self): self.direction = 'left' # Apple class class Food: def __init__(self, parent_screen): self.parent_screen = parent_screen self.food1 = pygame.image.load( "resources/food.png").convert() # inserting food image self.food2 = pygame.image.load( "resources/snake1.png").convert() self.food_x = SIZE*3 self.food_y = SIZE*2 def draw(self): seq = [self.food1, self.food2] self.parent_screen.blit(random.choice(seq), (self.food_x, self.food_y)) # drawing snake pygame.display.flip() def move(self): self.food_x = random.randint(0, W//SIZE - 1) * SIZE self.food_y = random.randint(0, H//SIZE - 1) * SIZE class Game: def __init__(self): pygame.init() pygame.display.set_caption("Snake Game") self.surface = pygame.display.set_mode( SCREEN) # crating game window 1000x720 self.surface.fill(BACKGROUND) # rgb color combination # snake object (surface, size_of_snake) self.snake = Snake(self.surface, 3) self.snake.draw() self.food = Food(self.surface) # Food object(Surface) self.food.draw() pygame.mixer.init() # pygame class mixer...for sound # start playing background b_music self.background_music() def is_collision(self, x1, y1, x2, y2): if x1 >= x2 and x1 < x2 + SIZE: if y1 >= y2 and y1 < y2 + SIZE: return True else: return False def play_sound(self, sound_location): sound = pygame.mixer.Sound(sound_location) # sound is for short time pygame.mixer.Sound.play(sound) def background_music(self): pygame.mixer.music.load("resources/b_music1.mp3") pygame.mixer.music.play(-1) #plays music infinitely def render_background(self): bg = pygame.image.load("resources/background.jpg") self.surface.blit(bg, (0, 0)) def play(self): self.render_background() # render the background self.snake.move() self.food.draw() self.display_score() self.screen_msgs() pygame.display.flip() # Snake colloding with apple if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[0], self.food.food_x, self.food.food_y): self.food.move() # moves apple to random position self.snake.increase_length() # play sound when eating the food self.play_sound("resources/ding.mp3") # passing the music location # to play the sound # Snake colliding with itself Game Over logic for i in range(2, self.snake.length): if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[0], self.snake.snake_x[i], self.snake.snake_y[i]): # play sound when game Over self.play_sound("resources/fail_buzz.mp3") raise "Game Over" # raising exeption self.touch_border_action() def pause_msg(self): font = pygame.font.SysFont('arial', 20) font1 = pygame.font.SysFont('Rockwell', 80) line1 = font1.render( f"<Paused>", True, (200, 200, 200)) line2 = font.render( f"Press <UP, DOWN, LEFT, RIGHT> To Resume", True, (255,255, 0)) self.surface.blit(line1, (W//4 + 20, H//3)) self.surface.blit(line2, (W//4 + 30, H//3 + 100)) pygame.display.flip() def show_game_over(self): # self.surface.fill(BACKGROUND) self.render_background() font = pygame.font.SysFont('Cooper Black', 30) font1 = pygame.font.SysFont('Cooper Black', 60) line1 = font1.render( f"GAME OVER !!", True, (200, 0, 0)) line1B = font.render( f"<<Score : {self.snake.length - 3}>>", True, (10, 255, 10)) line2 = font.render( f"Press <UP, DOWN, LEFT, RIGHT> To Play Again", True, (200, 200, 200)) line3 = font.render( f"Press ESC to EXIT!", True, (255, 200, 0)) self.surface.blit(line1, (W//4 - 25, H//3-45)) self.surface.blit(line1B, (W//4 + 100, H//3 + 60)) self.surface.blit(line2, (45, H//3 + 110)) self.surface.blit(line3, (W//4+50, H//3 + 160)) pygame.display.flip() # pause the background_music when game over pygame.mixer.music.rewind() pygame.mixer.music.pause() def touch_border_action(self): if self.snake.snake_x[0] == W: self.snake.snake_x[0] = 0 elif self.snake.snake_x[0] < 0: self.snake.snake_x[0] = W if self.snake.snake_y[0] == H: self.snake.snake_y[0] = 0 elif self.snake.snake_y[0] < 0: self.snake.snake_y[0] = H def reset_game(self): self.snake = Snake(self.surface, 3) self.food = Food(self.surface) # Food object(Surface) def display_score(self): font = pygame.font.SysFont('Algerian', 30) score = font.render( f"[Score : {self.snake.length - 3}]", True, (0, 255, 255)) self.surface.blit(score, (W //2 - 70 , 5)) def screen_msgs(self): font = pygame.font.SysFont('aharoni',16) msgs1 = font.render("[SPACE] to Pause", True, (200, 204, 255)) msgs2 = font.render("[ESC] to EXIT", True, (200, 204, 255)) self.surface.blit(msgs1, (W - 100, H - 20)) self.surface.blit(msgs2, (10, H - 20)) def run(self): clock = pygame.time.Clock() running = True pause_game = False while running: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: # PRESS esc to escape the screen running = False if event.key == K_SPACE: # to pause the game pygame.mixer.music.pause() self.pause_msg() pause_game = True if event.key == K_UP: self.snake.move_up() pause_game = False pygame.mixer.music.unpause() if event.key == K_DOWN: self.snake.move_down() pause_game = False pygame.mixer.music.unpause() if event.key == K_LEFT: self.snake.move_left() pause_game = False pygame.mixer.music.unpause() if event.key == K_RIGHT: self.snake.move_right() pause_game = False pygame.mixer.music.unpause() elif event.type == QUIT: running = False if not pause_game: try: self.play() except Exception as e: self.show_game_over() pause_game = True self.reset_game() clock.tick(60) if __name__ == "__main__": game = Game() # Game class object game.run() # auto-py-to-exe.exe # run this commande to convert to exe
normal
{ "blob_id": "935853a4afdb50a4652e14913d0cdb251a84ea14", "index": 6427, "step-1": "<mask token>\n\n\nclass Food:\n <mask token>\n\n def draw(self):\n seq = [self.food1, self.food2]\n self.parent_screen.blit(random.choice(seq), (self.food_x, self.food_y))\n pygame.display.flip()\n\n def move(self):\n self.food_x = random.randint(0, W // SIZE - 1) * SIZE\n self.food_y = random.randint(0, H // SIZE - 1) * SIZE\n\n\nclass Game:\n\n def __init__(self):\n pygame.init()\n pygame.display.set_caption('Snake Game')\n self.surface = pygame.display.set_mode(SCREEN)\n self.surface.fill(BACKGROUND)\n self.snake = Snake(self.surface, 3)\n self.snake.draw()\n self.food = Food(self.surface)\n self.food.draw()\n pygame.mixer.init()\n self.background_music()\n\n def is_collision(self, x1, y1, x2, y2):\n if x1 >= x2 and x1 < x2 + SIZE:\n if y1 >= y2 and y1 < y2 + SIZE:\n return True\n else:\n return False\n\n def play_sound(self, sound_location):\n sound = pygame.mixer.Sound(sound_location)\n pygame.mixer.Sound.play(sound)\n\n def background_music(self):\n pygame.mixer.music.load('resources/b_music1.mp3')\n pygame.mixer.music.play(-1)\n\n def render_background(self):\n bg = pygame.image.load('resources/background.jpg')\n self.surface.blit(bg, (0, 0))\n\n def play(self):\n self.render_background()\n self.snake.move()\n self.food.draw()\n self.display_score()\n self.screen_msgs()\n pygame.display.flip()\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[0],\n self.food.food_x, self.food.food_y):\n self.food.move()\n self.snake.increase_length()\n self.play_sound('resources/ding.mp3')\n for i in range(2, self.snake.length):\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[\n 0], self.snake.snake_x[i], self.snake.snake_y[i]):\n self.play_sound('resources/fail_buzz.mp3')\n raise 'Game Over'\n self.touch_border_action()\n\n def pause_msg(self):\n font = pygame.font.SysFont('arial', 20)\n font1 = pygame.font.SysFont('Rockwell', 80)\n line1 = font1.render(f'<Paused>', True, (200, 200, 200))\n line2 = font.render(f'Press <UP, DOWN, LEFT, RIGHT> To Resume', \n True, (255, 255, 0))\n self.surface.blit(line1, (W // 4 + 20, H // 3))\n self.surface.blit(line2, (W // 4 + 30, H // 3 + 100))\n pygame.display.flip()\n\n def show_game_over(self):\n self.render_background()\n font = pygame.font.SysFont('Cooper Black', 30)\n font1 = pygame.font.SysFont('Cooper Black', 60)\n line1 = font1.render(f'GAME OVER !!', True, (200, 0, 0))\n line1B = font.render(f'<<Score : {self.snake.length - 3}>>', True,\n (10, 255, 10))\n line2 = font.render(f'Press <UP, DOWN, LEFT, RIGHT> To Play Again',\n True, (200, 200, 200))\n line3 = font.render(f'Press ESC to EXIT!', True, (255, 200, 0))\n self.surface.blit(line1, (W // 4 - 25, H // 3 - 45))\n self.surface.blit(line1B, (W // 4 + 100, H // 3 + 60))\n self.surface.blit(line2, (45, H // 3 + 110))\n self.surface.blit(line3, (W // 4 + 50, H // 3 + 160))\n pygame.display.flip()\n pygame.mixer.music.rewind()\n pygame.mixer.music.pause()\n\n def touch_border_action(self):\n if self.snake.snake_x[0] == W:\n self.snake.snake_x[0] = 0\n elif self.snake.snake_x[0] < 0:\n self.snake.snake_x[0] = W\n if self.snake.snake_y[0] == H:\n self.snake.snake_y[0] = 0\n elif self.snake.snake_y[0] < 0:\n self.snake.snake_y[0] = H\n\n def reset_game(self):\n self.snake = Snake(self.surface, 3)\n self.food = Food(self.surface)\n\n def display_score(self):\n font = pygame.font.SysFont('Algerian', 30)\n score = font.render(f'[Score : {self.snake.length - 3}]', True, (0,\n 255, 255))\n self.surface.blit(score, (W // 2 - 70, 5))\n\n def screen_msgs(self):\n font = pygame.font.SysFont('aharoni', 16)\n msgs1 = font.render('[SPACE] to Pause', True, (200, 204, 255))\n msgs2 = font.render('[ESC] to EXIT', True, (200, 204, 255))\n self.surface.blit(msgs1, (W - 100, H - 20))\n self.surface.blit(msgs2, (10, H - 20))\n\n def run(self):\n clock = pygame.time.Clock()\n running = True\n pause_game = False\n while running:\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n if event.key == K_SPACE:\n pygame.mixer.music.pause()\n self.pause_msg()\n pause_game = True\n if event.key == K_UP:\n self.snake.move_up()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_DOWN:\n self.snake.move_down()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_LEFT:\n self.snake.move_left()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_RIGHT:\n self.snake.move_right()\n pause_game = False\n pygame.mixer.music.unpause()\n elif event.type == QUIT:\n running = False\n if not pause_game:\n try:\n self.play()\n except Exception as e:\n self.show_game_over()\n pause_game = True\n self.reset_game()\n clock.tick(60)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Snake:\n\n def __init__(self, parent_screen, length):\n self.parent_screen = parent_screen\n self.length = length\n self.snake = pygame.image.load('resources/snake.png').convert()\n self.snake_x = [W // 2] * length\n self.snake_y = [H // 2] * length\n self.direction = 'left'\n <mask token>\n\n def draw(self):\n for i in range(self.length):\n self.parent_screen.blit(self.snake, (self.snake_x[i], self.\n snake_y[i]))\n pygame.display.flip()\n\n def move(self):\n for i in range(self.length - 1, 0, -1):\n self.snake_x[i] = self.snake_x[i - 1]\n self.snake_y[i] = self.snake_y[i - 1]\n if self.direction == 'up':\n self.snake_y[0] -= SIZE\n if self.direction == 'down':\n self.snake_y[0] += SIZE\n if self.direction == 'right':\n self.snake_x[0] += SIZE\n if self.direction == 'left':\n self.snake_x[0] -= SIZE\n self.draw()\n\n def move_up(self):\n self.direction = 'up'\n\n def move_down(self):\n self.direction = 'down'\n\n def move_right(self):\n self.direction = 'right'\n\n def move_left(self):\n self.direction = 'left'\n\n\nclass Food:\n\n def __init__(self, parent_screen):\n self.parent_screen = parent_screen\n self.food1 = pygame.image.load('resources/food.png').convert()\n self.food2 = pygame.image.load('resources/snake1.png').convert()\n self.food_x = SIZE * 3\n self.food_y = SIZE * 2\n\n def draw(self):\n seq = [self.food1, self.food2]\n self.parent_screen.blit(random.choice(seq), (self.food_x, self.food_y))\n pygame.display.flip()\n\n def move(self):\n self.food_x = random.randint(0, W // SIZE - 1) * SIZE\n self.food_y = random.randint(0, H // SIZE - 1) * SIZE\n\n\nclass Game:\n\n def __init__(self):\n pygame.init()\n pygame.display.set_caption('Snake Game')\n self.surface = pygame.display.set_mode(SCREEN)\n self.surface.fill(BACKGROUND)\n self.snake = Snake(self.surface, 3)\n self.snake.draw()\n self.food = Food(self.surface)\n self.food.draw()\n pygame.mixer.init()\n self.background_music()\n\n def is_collision(self, x1, y1, x2, y2):\n if x1 >= x2 and x1 < x2 + SIZE:\n if y1 >= y2 and y1 < y2 + SIZE:\n return True\n else:\n return False\n\n def play_sound(self, sound_location):\n sound = pygame.mixer.Sound(sound_location)\n pygame.mixer.Sound.play(sound)\n\n def background_music(self):\n pygame.mixer.music.load('resources/b_music1.mp3')\n pygame.mixer.music.play(-1)\n\n def render_background(self):\n bg = pygame.image.load('resources/background.jpg')\n self.surface.blit(bg, (0, 0))\n\n def play(self):\n self.render_background()\n self.snake.move()\n self.food.draw()\n self.display_score()\n self.screen_msgs()\n pygame.display.flip()\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[0],\n self.food.food_x, self.food.food_y):\n self.food.move()\n self.snake.increase_length()\n self.play_sound('resources/ding.mp3')\n for i in range(2, self.snake.length):\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[\n 0], self.snake.snake_x[i], self.snake.snake_y[i]):\n self.play_sound('resources/fail_buzz.mp3')\n raise 'Game Over'\n self.touch_border_action()\n\n def pause_msg(self):\n font = pygame.font.SysFont('arial', 20)\n font1 = pygame.font.SysFont('Rockwell', 80)\n line1 = font1.render(f'<Paused>', True, (200, 200, 200))\n line2 = font.render(f'Press <UP, DOWN, LEFT, RIGHT> To Resume', \n True, (255, 255, 0))\n self.surface.blit(line1, (W // 4 + 20, H // 3))\n self.surface.blit(line2, (W // 4 + 30, H // 3 + 100))\n pygame.display.flip()\n\n def show_game_over(self):\n self.render_background()\n font = pygame.font.SysFont('Cooper Black', 30)\n font1 = pygame.font.SysFont('Cooper Black', 60)\n line1 = font1.render(f'GAME OVER !!', True, (200, 0, 0))\n line1B = font.render(f'<<Score : {self.snake.length - 3}>>', True,\n (10, 255, 10))\n line2 = font.render(f'Press <UP, DOWN, LEFT, RIGHT> To Play Again',\n True, (200, 200, 200))\n line3 = font.render(f'Press ESC to EXIT!', True, (255, 200, 0))\n self.surface.blit(line1, (W // 4 - 25, H // 3 - 45))\n self.surface.blit(line1B, (W // 4 + 100, H // 3 + 60))\n self.surface.blit(line2, (45, H // 3 + 110))\n self.surface.blit(line3, (W // 4 + 50, H // 3 + 160))\n pygame.display.flip()\n pygame.mixer.music.rewind()\n pygame.mixer.music.pause()\n\n def touch_border_action(self):\n if self.snake.snake_x[0] == W:\n self.snake.snake_x[0] = 0\n elif self.snake.snake_x[0] < 0:\n self.snake.snake_x[0] = W\n if self.snake.snake_y[0] == H:\n self.snake.snake_y[0] = 0\n elif self.snake.snake_y[0] < 0:\n self.snake.snake_y[0] = H\n\n def reset_game(self):\n self.snake = Snake(self.surface, 3)\n self.food = Food(self.surface)\n\n def display_score(self):\n font = pygame.font.SysFont('Algerian', 30)\n score = font.render(f'[Score : {self.snake.length - 3}]', True, (0,\n 255, 255))\n self.surface.blit(score, (W // 2 - 70, 5))\n\n def screen_msgs(self):\n font = pygame.font.SysFont('aharoni', 16)\n msgs1 = font.render('[SPACE] to Pause', True, (200, 204, 255))\n msgs2 = font.render('[ESC] to EXIT', True, (200, 204, 255))\n self.surface.blit(msgs1, (W - 100, H - 20))\n self.surface.blit(msgs2, (10, H - 20))\n\n def run(self):\n clock = pygame.time.Clock()\n running = True\n pause_game = False\n while running:\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n if event.key == K_SPACE:\n pygame.mixer.music.pause()\n self.pause_msg()\n pause_game = True\n if event.key == K_UP:\n self.snake.move_up()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_DOWN:\n self.snake.move_down()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_LEFT:\n self.snake.move_left()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_RIGHT:\n self.snake.move_right()\n pause_game = False\n pygame.mixer.music.unpause()\n elif event.type == QUIT:\n running = False\n if not pause_game:\n try:\n self.play()\n except Exception as e:\n self.show_game_over()\n pause_game = True\n self.reset_game()\n clock.tick(60)\n\n\n<mask token>\n", "step-3": "<mask token>\nSIZE = 20\nBACKGROUND = 45, 34, 44\nW = 800\nH = 400\nSCREEN = W, H\n\n\nclass Snake:\n\n def __init__(self, parent_screen, length):\n self.parent_screen = parent_screen\n self.length = length\n self.snake = pygame.image.load('resources/snake.png').convert()\n self.snake_x = [W // 2] * length\n self.snake_y = [H // 2] * length\n self.direction = 'left'\n\n def increase_length(self):\n self.length += 1\n self.snake_x.append(0)\n self.snake_y.append(0)\n\n def draw(self):\n for i in range(self.length):\n self.parent_screen.blit(self.snake, (self.snake_x[i], self.\n snake_y[i]))\n pygame.display.flip()\n\n def move(self):\n for i in range(self.length - 1, 0, -1):\n self.snake_x[i] = self.snake_x[i - 1]\n self.snake_y[i] = self.snake_y[i - 1]\n if self.direction == 'up':\n self.snake_y[0] -= SIZE\n if self.direction == 'down':\n self.snake_y[0] += SIZE\n if self.direction == 'right':\n self.snake_x[0] += SIZE\n if self.direction == 'left':\n self.snake_x[0] -= SIZE\n self.draw()\n\n def move_up(self):\n self.direction = 'up'\n\n def move_down(self):\n self.direction = 'down'\n\n def move_right(self):\n self.direction = 'right'\n\n def move_left(self):\n self.direction = 'left'\n\n\nclass Food:\n\n def __init__(self, parent_screen):\n self.parent_screen = parent_screen\n self.food1 = pygame.image.load('resources/food.png').convert()\n self.food2 = pygame.image.load('resources/snake1.png').convert()\n self.food_x = SIZE * 3\n self.food_y = SIZE * 2\n\n def draw(self):\n seq = [self.food1, self.food2]\n self.parent_screen.blit(random.choice(seq), (self.food_x, self.food_y))\n pygame.display.flip()\n\n def move(self):\n self.food_x = random.randint(0, W // SIZE - 1) * SIZE\n self.food_y = random.randint(0, H // SIZE - 1) * SIZE\n\n\nclass Game:\n\n def __init__(self):\n pygame.init()\n pygame.display.set_caption('Snake Game')\n self.surface = pygame.display.set_mode(SCREEN)\n self.surface.fill(BACKGROUND)\n self.snake = Snake(self.surface, 3)\n self.snake.draw()\n self.food = Food(self.surface)\n self.food.draw()\n pygame.mixer.init()\n self.background_music()\n\n def is_collision(self, x1, y1, x2, y2):\n if x1 >= x2 and x1 < x2 + SIZE:\n if y1 >= y2 and y1 < y2 + SIZE:\n return True\n else:\n return False\n\n def play_sound(self, sound_location):\n sound = pygame.mixer.Sound(sound_location)\n pygame.mixer.Sound.play(sound)\n\n def background_music(self):\n pygame.mixer.music.load('resources/b_music1.mp3')\n pygame.mixer.music.play(-1)\n\n def render_background(self):\n bg = pygame.image.load('resources/background.jpg')\n self.surface.blit(bg, (0, 0))\n\n def play(self):\n self.render_background()\n self.snake.move()\n self.food.draw()\n self.display_score()\n self.screen_msgs()\n pygame.display.flip()\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[0],\n self.food.food_x, self.food.food_y):\n self.food.move()\n self.snake.increase_length()\n self.play_sound('resources/ding.mp3')\n for i in range(2, self.snake.length):\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[\n 0], self.snake.snake_x[i], self.snake.snake_y[i]):\n self.play_sound('resources/fail_buzz.mp3')\n raise 'Game Over'\n self.touch_border_action()\n\n def pause_msg(self):\n font = pygame.font.SysFont('arial', 20)\n font1 = pygame.font.SysFont('Rockwell', 80)\n line1 = font1.render(f'<Paused>', True, (200, 200, 200))\n line2 = font.render(f'Press <UP, DOWN, LEFT, RIGHT> To Resume', \n True, (255, 255, 0))\n self.surface.blit(line1, (W // 4 + 20, H // 3))\n self.surface.blit(line2, (W // 4 + 30, H // 3 + 100))\n pygame.display.flip()\n\n def show_game_over(self):\n self.render_background()\n font = pygame.font.SysFont('Cooper Black', 30)\n font1 = pygame.font.SysFont('Cooper Black', 60)\n line1 = font1.render(f'GAME OVER !!', True, (200, 0, 0))\n line1B = font.render(f'<<Score : {self.snake.length - 3}>>', True,\n (10, 255, 10))\n line2 = font.render(f'Press <UP, DOWN, LEFT, RIGHT> To Play Again',\n True, (200, 200, 200))\n line3 = font.render(f'Press ESC to EXIT!', True, (255, 200, 0))\n self.surface.blit(line1, (W // 4 - 25, H // 3 - 45))\n self.surface.blit(line1B, (W // 4 + 100, H // 3 + 60))\n self.surface.blit(line2, (45, H // 3 + 110))\n self.surface.blit(line3, (W // 4 + 50, H // 3 + 160))\n pygame.display.flip()\n pygame.mixer.music.rewind()\n pygame.mixer.music.pause()\n\n def touch_border_action(self):\n if self.snake.snake_x[0] == W:\n self.snake.snake_x[0] = 0\n elif self.snake.snake_x[0] < 0:\n self.snake.snake_x[0] = W\n if self.snake.snake_y[0] == H:\n self.snake.snake_y[0] = 0\n elif self.snake.snake_y[0] < 0:\n self.snake.snake_y[0] = H\n\n def reset_game(self):\n self.snake = Snake(self.surface, 3)\n self.food = Food(self.surface)\n\n def display_score(self):\n font = pygame.font.SysFont('Algerian', 30)\n score = font.render(f'[Score : {self.snake.length - 3}]', True, (0,\n 255, 255))\n self.surface.blit(score, (W // 2 - 70, 5))\n\n def screen_msgs(self):\n font = pygame.font.SysFont('aharoni', 16)\n msgs1 = font.render('[SPACE] to Pause', True, (200, 204, 255))\n msgs2 = font.render('[ESC] to EXIT', True, (200, 204, 255))\n self.surface.blit(msgs1, (W - 100, H - 20))\n self.surface.blit(msgs2, (10, H - 20))\n\n def run(self):\n clock = pygame.time.Clock()\n running = True\n pause_game = False\n while running:\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n if event.key == K_SPACE:\n pygame.mixer.music.pause()\n self.pause_msg()\n pause_game = True\n if event.key == K_UP:\n self.snake.move_up()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_DOWN:\n self.snake.move_down()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_LEFT:\n self.snake.move_left()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_RIGHT:\n self.snake.move_right()\n pause_game = False\n pygame.mixer.music.unpause()\n elif event.type == QUIT:\n running = False\n if not pause_game:\n try:\n self.play()\n except Exception as e:\n self.show_game_over()\n pause_game = True\n self.reset_game()\n clock.tick(60)\n\n\nif __name__ == '__main__':\n game = Game()\n game.run()\n", "step-4": "from typing import Sized\nimport pygame\nimport time\nfrom pygame.locals import *\nimport random\nSIZE = 20\nBACKGROUND = 45, 34, 44\nW = 800\nH = 400\nSCREEN = W, H\n\n\nclass Snake:\n\n def __init__(self, parent_screen, length):\n self.parent_screen = parent_screen\n self.length = length\n self.snake = pygame.image.load('resources/snake.png').convert()\n self.snake_x = [W // 2] * length\n self.snake_y = [H // 2] * length\n self.direction = 'left'\n\n def increase_length(self):\n self.length += 1\n self.snake_x.append(0)\n self.snake_y.append(0)\n\n def draw(self):\n for i in range(self.length):\n self.parent_screen.blit(self.snake, (self.snake_x[i], self.\n snake_y[i]))\n pygame.display.flip()\n\n def move(self):\n for i in range(self.length - 1, 0, -1):\n self.snake_x[i] = self.snake_x[i - 1]\n self.snake_y[i] = self.snake_y[i - 1]\n if self.direction == 'up':\n self.snake_y[0] -= SIZE\n if self.direction == 'down':\n self.snake_y[0] += SIZE\n if self.direction == 'right':\n self.snake_x[0] += SIZE\n if self.direction == 'left':\n self.snake_x[0] -= SIZE\n self.draw()\n\n def move_up(self):\n self.direction = 'up'\n\n def move_down(self):\n self.direction = 'down'\n\n def move_right(self):\n self.direction = 'right'\n\n def move_left(self):\n self.direction = 'left'\n\n\nclass Food:\n\n def __init__(self, parent_screen):\n self.parent_screen = parent_screen\n self.food1 = pygame.image.load('resources/food.png').convert()\n self.food2 = pygame.image.load('resources/snake1.png').convert()\n self.food_x = SIZE * 3\n self.food_y = SIZE * 2\n\n def draw(self):\n seq = [self.food1, self.food2]\n self.parent_screen.blit(random.choice(seq), (self.food_x, self.food_y))\n pygame.display.flip()\n\n def move(self):\n self.food_x = random.randint(0, W // SIZE - 1) * SIZE\n self.food_y = random.randint(0, H // SIZE - 1) * SIZE\n\n\nclass Game:\n\n def __init__(self):\n pygame.init()\n pygame.display.set_caption('Snake Game')\n self.surface = pygame.display.set_mode(SCREEN)\n self.surface.fill(BACKGROUND)\n self.snake = Snake(self.surface, 3)\n self.snake.draw()\n self.food = Food(self.surface)\n self.food.draw()\n pygame.mixer.init()\n self.background_music()\n\n def is_collision(self, x1, y1, x2, y2):\n if x1 >= x2 and x1 < x2 + SIZE:\n if y1 >= y2 and y1 < y2 + SIZE:\n return True\n else:\n return False\n\n def play_sound(self, sound_location):\n sound = pygame.mixer.Sound(sound_location)\n pygame.mixer.Sound.play(sound)\n\n def background_music(self):\n pygame.mixer.music.load('resources/b_music1.mp3')\n pygame.mixer.music.play(-1)\n\n def render_background(self):\n bg = pygame.image.load('resources/background.jpg')\n self.surface.blit(bg, (0, 0))\n\n def play(self):\n self.render_background()\n self.snake.move()\n self.food.draw()\n self.display_score()\n self.screen_msgs()\n pygame.display.flip()\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[0],\n self.food.food_x, self.food.food_y):\n self.food.move()\n self.snake.increase_length()\n self.play_sound('resources/ding.mp3')\n for i in range(2, self.snake.length):\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[\n 0], self.snake.snake_x[i], self.snake.snake_y[i]):\n self.play_sound('resources/fail_buzz.mp3')\n raise 'Game Over'\n self.touch_border_action()\n\n def pause_msg(self):\n font = pygame.font.SysFont('arial', 20)\n font1 = pygame.font.SysFont('Rockwell', 80)\n line1 = font1.render(f'<Paused>', True, (200, 200, 200))\n line2 = font.render(f'Press <UP, DOWN, LEFT, RIGHT> To Resume', \n True, (255, 255, 0))\n self.surface.blit(line1, (W // 4 + 20, H // 3))\n self.surface.blit(line2, (W // 4 + 30, H // 3 + 100))\n pygame.display.flip()\n\n def show_game_over(self):\n self.render_background()\n font = pygame.font.SysFont('Cooper Black', 30)\n font1 = pygame.font.SysFont('Cooper Black', 60)\n line1 = font1.render(f'GAME OVER !!', True, (200, 0, 0))\n line1B = font.render(f'<<Score : {self.snake.length - 3}>>', True,\n (10, 255, 10))\n line2 = font.render(f'Press <UP, DOWN, LEFT, RIGHT> To Play Again',\n True, (200, 200, 200))\n line3 = font.render(f'Press ESC to EXIT!', True, (255, 200, 0))\n self.surface.blit(line1, (W // 4 - 25, H // 3 - 45))\n self.surface.blit(line1B, (W // 4 + 100, H // 3 + 60))\n self.surface.blit(line2, (45, H // 3 + 110))\n self.surface.blit(line3, (W // 4 + 50, H // 3 + 160))\n pygame.display.flip()\n pygame.mixer.music.rewind()\n pygame.mixer.music.pause()\n\n def touch_border_action(self):\n if self.snake.snake_x[0] == W:\n self.snake.snake_x[0] = 0\n elif self.snake.snake_x[0] < 0:\n self.snake.snake_x[0] = W\n if self.snake.snake_y[0] == H:\n self.snake.snake_y[0] = 0\n elif self.snake.snake_y[0] < 0:\n self.snake.snake_y[0] = H\n\n def reset_game(self):\n self.snake = Snake(self.surface, 3)\n self.food = Food(self.surface)\n\n def display_score(self):\n font = pygame.font.SysFont('Algerian', 30)\n score = font.render(f'[Score : {self.snake.length - 3}]', True, (0,\n 255, 255))\n self.surface.blit(score, (W // 2 - 70, 5))\n\n def screen_msgs(self):\n font = pygame.font.SysFont('aharoni', 16)\n msgs1 = font.render('[SPACE] to Pause', True, (200, 204, 255))\n msgs2 = font.render('[ESC] to EXIT', True, (200, 204, 255))\n self.surface.blit(msgs1, (W - 100, H - 20))\n self.surface.blit(msgs2, (10, H - 20))\n\n def run(self):\n clock = pygame.time.Clock()\n running = True\n pause_game = False\n while running:\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n if event.key == K_SPACE:\n pygame.mixer.music.pause()\n self.pause_msg()\n pause_game = True\n if event.key == K_UP:\n self.snake.move_up()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_DOWN:\n self.snake.move_down()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_LEFT:\n self.snake.move_left()\n pause_game = False\n pygame.mixer.music.unpause()\n if event.key == K_RIGHT:\n self.snake.move_right()\n pause_game = False\n pygame.mixer.music.unpause()\n elif event.type == QUIT:\n running = False\n if not pause_game:\n try:\n self.play()\n except Exception as e:\n self.show_game_over()\n pause_game = True\n self.reset_game()\n clock.tick(60)\n\n\nif __name__ == '__main__':\n game = Game()\n game.run()\n", "step-5": "from typing import Sized\nimport pygame\nimport time\nfrom pygame.locals import *\nimport random\n\nSIZE = 20\nBACKGROUND = (45, 34, 44)\nW = 800\nH = 400\nSCREEN = (W, H)\n\n\nclass Snake:\n def __init__(self, parent_screen, length):\n self.parent_screen = parent_screen\n self.length = length\n self.snake = pygame.image.load(\n \"resources/snake.png\").convert() # inserting snake image\n\n self.snake_x = [W//2]*length # list with 'length' number of elements\n self.snake_y = [H//2]*length\n\n self.direction = \"left\" # default direction LEFT\n\n def increase_length(self):\n self.length += 1\n\n # adds another block to snake\n # appends a random value to the list...cause it will change immidiately in 'move()' method\n self.snake_x.append(0)\n self.snake_y.append(0)\n\n def draw(self):\n # self.parent_screen.fill(BACKGROUND)\n for i in range(self.length):\n self.parent_screen.blit(\n self.snake, (self.snake_x[i], self.snake_y[i])) # drawing snake\n pygame.display.flip()\n\n def move(self):\n # Logic gor moving the TAIL snakes [like 2nd snake will come to 1st pos, 3rd will move to 2nd pos.]\n\n for i in range(self.length-1, 0, -1): # reverse for loop\n self.snake_x[i] = self.snake_x[i-1]\n self.snake_y[i] = self.snake_y[i-1]\n\n # Logic for moving the head snakes\n\n if self.direction == 'up':\n self.snake_y[0] -= SIZE\n if self.direction == 'down':\n self.snake_y[0] += SIZE\n if self.direction == 'right':\n self.snake_x[0] += SIZE\n if self.direction == 'left':\n self.snake_x[0] -= SIZE\n\n self.draw()\n\n def move_up(self):\n self.direction = 'up'\n\n def move_down(self):\n self.direction = 'down'\n\n def move_right(self):\n self.direction = 'right'\n\n def move_left(self):\n self.direction = 'left'\n\n# Apple class\n\n\nclass Food:\n def __init__(self, parent_screen):\n self.parent_screen = parent_screen\n self.food1 = pygame.image.load(\n \"resources/food.png\").convert() # inserting food image\n self.food2 = pygame.image.load(\n \"resources/snake1.png\").convert() \n\n self.food_x = SIZE*3\n self.food_y = SIZE*2\n\n def draw(self):\n seq = [self.food1, self.food2]\n self.parent_screen.blit(random.choice(seq), (self.food_x, self.food_y)) # drawing snake\n pygame.display.flip()\n\n def move(self):\n self.food_x = random.randint(0, W//SIZE - 1) * SIZE\n self.food_y = random.randint(0, H//SIZE - 1) * SIZE\n\n\nclass Game:\n\n def __init__(self):\n pygame.init()\n pygame.display.set_caption(\"Snake Game\")\n\n self.surface = pygame.display.set_mode(\n SCREEN) # crating game window 1000x720\n self.surface.fill(BACKGROUND) # rgb color combination\n\n # snake object (surface, size_of_snake)\n self.snake = Snake(self.surface, 3)\n self.snake.draw()\n\n self.food = Food(self.surface) # Food object(Surface)\n self.food.draw()\n\n pygame.mixer.init() # pygame class mixer...for sound\n\n # start playing background b_music\n self.background_music()\n\n def is_collision(self, x1, y1, x2, y2):\n if x1 >= x2 and x1 < x2 + SIZE:\n if y1 >= y2 and y1 < y2 + SIZE:\n return True\n\n else:\n return False\n\n def play_sound(self, sound_location):\n sound = pygame.mixer.Sound(sound_location) # sound is for short time\n pygame.mixer.Sound.play(sound)\n\n def background_music(self):\n pygame.mixer.music.load(\"resources/b_music1.mp3\")\n pygame.mixer.music.play(-1) #plays music infinitely\n\n def render_background(self):\n bg = pygame.image.load(\"resources/background.jpg\")\n self.surface.blit(bg, (0, 0))\n\n def play(self):\n\n self.render_background() # render the background\n self.snake.move()\n self.food.draw()\n self.display_score()\n self.screen_msgs()\n pygame.display.flip()\n\n # Snake colloding with apple\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[0], self.food.food_x, self.food.food_y):\n self.food.move() # moves apple to random position\n self.snake.increase_length()\n # play sound when eating the food\n self.play_sound(\"resources/ding.mp3\") # passing the music location\n # to play the sound\n\n # Snake colliding with itself Game Over logic\n for i in range(2, self.snake.length):\n if self.is_collision(self.snake.snake_x[0], self.snake.snake_y[0], self.snake.snake_x[i], self.snake.snake_y[i]):\n # play sound when game Over\n self.play_sound(\"resources/fail_buzz.mp3\")\n\n raise \"Game Over\" # raising exeption\n \n self.touch_border_action()\n \n def pause_msg(self):\n font = pygame.font.SysFont('arial', 20)\n font1 = pygame.font.SysFont('Rockwell', 80)\n line1 = font1.render(\n f\"<Paused>\", True, (200, 200, 200))\n line2 = font.render(\n f\"Press <UP, DOWN, LEFT, RIGHT> To Resume\", True, (255,255, 0))\n self.surface.blit(line1, (W//4 + 20, H//3))\n self.surface.blit(line2, (W//4 + 30, H//3 + 100))\n\n pygame.display.flip()\n\n def show_game_over(self):\n # self.surface.fill(BACKGROUND)\n self.render_background()\n\n font = pygame.font.SysFont('Cooper Black', 30)\n font1 = pygame.font.SysFont('Cooper Black', 60)\n line1 = font1.render(\n f\"GAME OVER !!\", True, (200, 0, 0))\n line1B = font.render(\n f\"<<Score : {self.snake.length - 3}>>\", True, (10, 255, 10))\n\n line2 = font.render(\n f\"Press <UP, DOWN, LEFT, RIGHT> To Play Again\", True, (200, 200, 200))\n line3 = font.render(\n f\"Press ESC to EXIT!\", True, (255, 200, 0))\n\n self.surface.blit(line1, (W//4 - 25, H//3-45))\n self.surface.blit(line1B, (W//4 + 100, H//3 + 60))\n self.surface.blit(line2, (45, H//3 + 110))\n self.surface.blit(line3, (W//4+50, H//3 + 160))\n\n pygame.display.flip()\n # pause the background_music when game over\n pygame.mixer.music.rewind()\n pygame.mixer.music.pause()\n \n def touch_border_action(self):\n if self.snake.snake_x[0] == W:\n self.snake.snake_x[0] = 0\n elif self.snake.snake_x[0] < 0:\n self.snake.snake_x[0] = W \n \n if self.snake.snake_y[0] == H:\n self.snake.snake_y[0] = 0\n elif self.snake.snake_y[0] < 0:\n self.snake.snake_y[0] = H\n\n def reset_game(self):\n self.snake = Snake(self.surface, 3)\n\n self.food = Food(self.surface) # Food object(Surface)\n\n def display_score(self):\n font = pygame.font.SysFont('Algerian', 30)\n score = font.render(\n f\"[Score : {self.snake.length - 3}]\", True, (0, 255, 255))\n self.surface.blit(score, (W //2 - 70 , 5))\n\n def screen_msgs(self):\n font = pygame.font.SysFont('aharoni',16)\n msgs1 = font.render(\"[SPACE] to Pause\", True, (200, 204, 255))\n msgs2 = font.render(\"[ESC] to EXIT\", True, (200, 204, 255))\n self.surface.blit(msgs1, (W - 100, H - 20))\n self.surface.blit(msgs2, (10, H - 20))\n\n def run(self):\n clock = pygame.time.Clock()\n running = True\n pause_game = False\n while running:\n\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE: # PRESS esc to escape the screen\n running = False\n if event.key == K_SPACE: # to pause the game\n pygame.mixer.music.pause()\n self.pause_msg()\n pause_game = True\n\n if event.key == K_UP:\n self.snake.move_up()\n pause_game = False\n pygame.mixer.music.unpause()\n\n if event.key == K_DOWN:\n self.snake.move_down()\n pause_game = False\n pygame.mixer.music.unpause()\n\n if event.key == K_LEFT:\n self.snake.move_left()\n pause_game = False\n pygame.mixer.music.unpause()\n\n if event.key == K_RIGHT:\n self.snake.move_right()\n pause_game = False\n pygame.mixer.music.unpause()\n\n elif event.type == QUIT:\n running = False\n\n if not pause_game:\n try:\n self.play()\n except Exception as e:\n self.show_game_over()\n pause_game = True\n self.reset_game()\n\n clock.tick(60)\n\n\nif __name__ == \"__main__\":\n\n game = Game() # Game class object\n game.run()\n\n # auto-py-to-exe.exe # run this commande to convert to exe\n", "step-ids": [ 17, 26, 29, 30, 31 ] }
[ 17, 26, 29, 30, 31 ]
TOTAL = 1306336 ONE = { '0': 1473, '1': 5936, '2': 3681, '3': 2996, '4': 2480, '5': 2494, '6': 1324, '7': 1474, '8': 1754, '9': 1740, 'a': 79714, 'b': 83472, 'c': 78015, 'd': 61702, 'e': 42190, 'f': 68530, 'g': 48942, 'h': 63661, 'i': 34947, 'j': 24312, 'k': 26724, 'l': 66351, 'm': 77245, 'n': 36942, 'o': 40744, 'p': 68978, 'q': 6750, 'r': 49135, 's': 116034, 't': 87440, 'u': 19423, 'v': 22356, 'w': 50718, 'x': 6079, 'y': 13089, 'z': 7491, } TWO = { '0-': 19, '00': 145, '01': 143, '02': 212, '03': 90, '04': 61, '05': 241, '06': 31, '07': 151, '08': 104, '09': 99, '0a': 8, '0b': 8, '0c': 16, '0d': 18, '0e': 8, '0f': 7, '0g': 5, '0h': 4, '0i': 9, '0j': 1, '0k': 4, '0l': 2, '0m': 8, '0n': 10, '0o': 6, '0p': 10, '0r': 10, '0s': 10, '0t': 6, '0u': 5, '0v': 5, '0w': 5, '0x': 4, '0y': 3, '0z': 5, '1-': 177, '10': 983, '11': 537, '12': 767, '13': 327, '14': 270, '15': 257, '16': 276, '17': 318, '18': 505, '19': 280, '1a': 61, '1b': 58, '1c': 84, '1d': 52, '1e': 33, '1f': 32, '1g': 38, '1h': 44, '1i': 25, '1j': 13, '1k': 32, '1l': 33, '1m': 59, '1n': 39, '1o': 37, '1p': 68, '1q': 7, '1r': 21, '1s': 336, '1t': 54, '1u': 15, '1v': 14, '1w': 53, '1x': 7, '1y': 14, '1z': 10, '2-': 30, '20': 889, '21': 406, '22': 228, '23': 172, '24': 480, '25': 177, '26': 126, '27': 96, '28': 108, '29': 73, '2a': 50, '2b': 94, '2c': 59, '2d': 61, '2e': 29, '2f': 29, '2g': 47, '2h': 24, '2i': 22, '2j': 13, '2k': 27, '2l': 35, '2m': 62, '2n': 53, '2o': 22, '2p': 48, '2q': 7, '2r': 14, '2s': 53, '2t': 43, '2u': 20, '2v': 7, '2w': 43, '2x': 21, '2y': 7, '2z': 6, '3-': 53, '30': 292, '31': 224, '32': 188, '33': 179, '34': 91, '35': 153, '36': 367, '37': 101, '38': 122, '39': 118, '3a': 50, '3b': 45, '3c': 37, '3d': 350, '3e': 17, '3f': 26, '3g': 125, '3h': 27, '3i': 11, '3j': 9, '3k': 19, '3l': 25, '3m': 45, '3n': 17, '3o': 15, '3p': 32, '3q': 12, '3r': 72, '3s': 53, '3t': 28, '3u': 3, '3v': 13, '3w': 36, '3x': 17, '3y': 14, '3z': 10, '4-': 76, '40': 357, '41': 259, '42': 170, '43': 88, '44': 126, '45': 102, '46': 67, '47': 56, '48': 97, '49': 62, '4a': 41, '4b': 49, '4c': 55, '4d': 53, '4e': 51, '4f': 43, '4g': 52, '4h': 44, '4i': 19, '4j': 13, '4k': 22, '4l': 48, '4m': 62, '4n': 22, '4o': 21, '4p': 60, '4q': 11, '4r': 26, '4s': 94, '4t': 44, '4u': 40, '4v': 17, '4w': 45, '4x': 58, '4y': 24, '4z': 6, '5-': 30, '50': 323, '51': 574, '52': 361, '53': 79, '54': 155, '55': 141, '56': 109, '57': 66, '58': 85, '59': 87, '5a': 32, '5b': 17, '5c': 21, '5d': 39, '5e': 7, '5f': 17, '5g': 21, '5h': 10, '5i': 54, '5j': 4, '5k': 16, '5l': 19, '5m': 22, '5n': 8, '5o': 12, '5p': 27, '5q': 4, '5r': 9, '5s': 55, '5t': 38, '5u': 17, '5v': 5, '5w': 5, '5x': 9, '5y': 10, '5z': 6, '6-': 42, '60': 173, '61': 182, '62': 63, '63': 56, '64': 51, '65': 125, '66': 134, '67': 62, '68': 58, '69': 105, '6a': 12, '6b': 7, '6c': 11, '6d': 61, '6e': 6, '6f': 15, '6g': 7, '6h': 11, '6i': 6, '6j': 1, '6k': 7, '6l': 8, '6m': 16, '6n': 1, '6o': 5, '6p': 12, '6q': 6, '6r': 15, '6s': 28, '6t': 12, '6u': 2, '6v': 2, '6w': 8, '6x': 5, '6y': 9, '7-': 34, '70': 200, '71': 205, '72': 81, '73': 58, '74': 53, '75': 59, '76': 69, '77': 191, '78': 92, '79': 48, '7a': 33, '7b': 18, '7c': 28, '7d': 31, '7e': 13, '7f': 15, '7g': 11, '7h': 15, '7i': 7, '7j': 8, '7k': 16, '7l': 19, '7m': 15, '7n': 5, '7o': 13, '7p': 10, '7q': 2, '7r': 4, '7s': 33, '7t': 37, '7u': 2, '7v': 3, '7w': 13, '7x': 13, '7y': 12, '7z': 8, '8-': 61, '80': 336, '81': 180, '82': 61, '83': 62, '84': 99, '85': 85, '86': 138, '87': 85, '88': 339, '89': 78, '8a': 11, '8b': 16, '8c': 9, '8d': 10, '8e': 6, '8f': 10, '8g': 18, '8h': 7, '8i': 12, '8j': 4, '8k': 6, '8l': 6, '8m': 11, '8n': 2, '8o': 8, '8p': 15, '8q': 7, '8r': 10, '8s': 18, '8t': 24, '8u': 3, '8v': 2, '8w': 4, '8x': 1, '8y': 6, '8z': 4, '9-': 45, '90': 173, '91': 275, '92': 149, '93': 59, '94': 76, '95': 82, '96': 76, '97': 123, '98': 74, '99': 270, '9a': 19, '9b': 9, '9c': 22, '9d': 17, '9e': 10, '9f': 5, '9g': 16, '9h': 6, '9i': 20, '9j': 10, '9k': 9, '9l': 13, '9m': 19, '9n': 8, '9o': 8, '9p': 29, '9q': 3, '9r': 11, '9s': 22, '9t': 26, '9u': 3, '9v': 8, '9w': 11, '9x': 21, '9y': 8, '9z': 5, 'a-': 307, 'a0': 6, 'a1': 172, 'a2': 58, 'a3': 25, 'a4': 16, 'a5': 9, 'a6': 8, 'a7': 20, 'a8': 12, 'a9': 15, 'aa': 778, 'ab': 3124, 'ac': 4416, 'ad': 5316, 'ae': 537, 'af': 1343, 'ag': 4563, 'ah': 760, 'ai': 5617, 'aj': 331, 'ak': 715, 'al': 9102, 'am': 4388, 'an': 8462, 'ao': 351, 'ap': 2155, 'aq': 426, 'ar': 9178, 'as': 6419, 'at': 4007, 'au': 2485, 'av': 1218, 'aw': 1869, 'ax': 403, 'ay': 457, 'az': 646, 'b-': 148, 'b0': 7, 'b1': 19, 'b2': 94, 'b3': 12, 'b4': 24, 'b5': 9, 'b6': 4, 'b7': 5, 'b8': 2, 'b9': 6, 'ba': 15356, 'bb': 477, 'bc': 323, 'bd': 266, 'be': 14064, 'bf': 200, 'bg': 189, 'bh': 311, 'bi': 11911, 'bj': 604, 'bk': 178, 'bl': 5297, 'bm': 306, 'bn': 218, 'bo': 11986, 'bp': 229, 'bq': 103, 'br': 5001, 'bs': 317, 'bt': 266, 'bu': 12643, 'bv': 126, 'bw': 147, 'bx': 91, 'by': 2394, 'bz': 139, 'c-': 120, 'c0': 13, 'c1': 21, 'c2': 78, 'c3': 34, 'c4': 30, 'c5': 6, 'c6': 4, 'c7': 10, 'c8': 4, 'c9': 8, 'ca': 18400, 'cb': 368, 'cc': 678, 'cd': 484, 'ce': 3579, 'cf': 300, 'cg': 253, 'ch': 11318, 'ci': 2463, 'cj': 218, 'ck': 165, 'cl': 5881, 'cm': 371, 'cn': 895, 'co': 15790, 'cp': 497, 'cq': 239, 'cr': 5502, 'cs': 1710, 'ct': 364, 'cu': 6370, 'cv': 200, 'cw': 201, 'cx': 142, 'cy': 1053, 'cz': 246, 'd-': 147, 'd0': 7, 'd1': 14, 'd2': 37, 'd3': 29, 'd4': 10, 'd5': 5, 'd6': 4, 'd7': 8, 'd8': 6, 'd9': 7, 'da': 9910, 'db': 288, 'dc': 410, 'dd': 303, 'de': 11362, 'df': 288, 'dg': 307, 'dh': 280, 'di': 10934, 'dj': 682, 'dk': 157, 'dl': 393, 'dm': 361, 'dn': 476, 'do': 10944, 'dp': 211, 'dq': 106, 'dr': 6965, 'ds': 393, 'dt': 262, 'du': 4853, 'dv': 376, 'dw': 211, 'dx': 157, 'dy': 630, 'dz': 169, 'e-': 1066, 'e0': 9, 'e1': 12, 'e2': 26, 'e3': 27, 'e4': 11, 'e5': 2, 'e6': 6, 'e7': 6, 'e8': 37, 'e9': 5, 'ea': 6784, 'eb': 771, 'ec': 1530, 'ed': 2674, 'ee': 257, 'ef': 482, 'eg': 508, 'eh': 276, 'ei': 552, 'ej': 151, 'ek': 329, 'el': 3657, 'em': 1785, 'en': 4879, 'eo': 205, 'ep': 613, 'eq': 553, 'er': 2767, 'es': 1797, 'et': 766, 'eu': 1095, 'ev': 2975, 'ew': 218, 'ex': 2521, 'ey': 2066, 'ez': 772, 'f-': 75, 'f0': 6, 'f1': 54, 'f2': 25, 'f3': 5, 'f4': 9, 'f5': 12, 'f6': 2, 'f7': 4, 'f8': 10, 'f9': 2, 'fa': 12917, 'fb': 165, 'fc': 272, 'fd': 154, 'fe': 8514, 'ff': 195, 'fg': 107, 'fh': 175, 'fi': 14464, 'fj': 192, 'fk': 90, 'fl': 7482, 'fm': 210, 'fn': 114, 'fo': 8864, 'fp': 132, 'fq': 77, 'fr': 7566, 'fs': 413, 'ft': 252, 'fu': 5259, 'fv': 88, 'fw': 129, 'fx': 197, 'fy': 155, 'fz': 143, 'g-': 138, 'g0': 21, 'g1': 38, 'g2': 26, 'g3': 34, 'g4': 26, 'g5': 11, 'g6': 5, 'g7': 5, 'g8': 15, 'g9': 5, 'ga': 8708, 'gb': 232, 'gc': 262, 'gd': 339, 'ge': 5489, 'gf': 176, 'gg': 245, 'gh': 399, 'gi': 3752, 'gj': 108, 'gk': 138, 'gl': 2606, 'gm': 387, 'gn': 217, 'go': 9782, 'gp': 455, 'gq': 78, 'gr': 8101, 'gs': 381, 'gt': 252, 'gu': 5335, 'gv': 138, 'gw': 202, 'gx': 176, 'gy': 265, 'gz': 395, 'h-': 120, 'h0': 6, 'h1': 14, 'h2': 149, 'h3': 15, 'h4': 28, 'h5': 6, 'h6': 3, 'h7': 2, 'h8': 8, 'h9': 2, 'ha': 16216, 'hb': 351, 'hc': 228, 'hd': 442, 'he': 12087, 'hf': 180, 'hg': 158, 'hh': 243, 'hi': 10582, 'hj': 147, 'hk': 331, 'hl': 215, 'hm': 214, 'hn': 317, 'ho': 14380, 'hp': 207, 'hq': 147, 'hr': 318, 'hs': 380, 'ht': 314, 'hu': 4226, 'hv': 119, 'hw': 147, 'hx': 150, 'hy': 943, 'hz': 266, 'i-': 527, 'i0': 9, 'i1': 8, 'i2': 34, 'i3': 14, 'i4': 17, 'i5': 4, 'i6': 6, 'i7': 12, 'i8': 8, 'i9': 11, 'ia': 606, 'ib': 659, 'ic': 2175, 'id': 1981, 'ie': 282, 'if': 1514, 'ig': 488, 'ih': 370, 'ii': 226, 'ij': 122, 'ik': 351, 'il': 2287, 'im': 2155, 'in': 10117, 'io': 344, 'ip': 818, 'iq': 154, 'ir': 1037, 'is': 2803, 'it': 4514, 'iu': 135, 'iv': 328, 'iw': 391, 'ix': 87, 'iy': 123, 'iz': 230, 'j-': 143, 'j0': 7, 'j1': 2, 'j2': 20, 'j3': 8, 'j4': 10, 'j5': 1, 'j6': 1, 'j7': 2, 'j8': 3, 'j9': 2, 'ja': 3167, 'jb': 251, 'jc': 336, 'jd': 290, 'je': 2239, 'jf': 152, 'jg': 136, 'jh': 228, 'ji': 1541, 'jj': 266, 'jk': 191, 'jl': 249, 'jm': 340, 'jn': 230, 'jo': 7930, 'jp': 278, 'jq': 82, 'jr': 261, 'js': 448, 'jt': 174, 'ju': 4460, 'jv': 125, 'jw': 191, 'jx': 200, 'jy': 202, 'jz': 146, 'k-': 110, 'k0': 7, 'k1': 29, 'k2': 30, 'k3': 14, 'k4': 5, 'k5': 7, 'k6': 5, 'k7': 7, 'k8': 4, 'k9': 32, 'ka': 3724, 'kb': 212, 'kc': 275, 'kd': 182, 'ke': 6054, 'kf': 130, 'kg': 137, 'kh': 420, 'ki': 6316, 'kj': 144, 'kk': 167, 'kl': 487, 'km': 248, 'kn': 2612, 'ko': 1868, 'kp': 181, 'kq': 59, 'kr': 785, 'ks': 300, 'kt': 192, 'ku': 1013, 'kv': 116, 'kw': 230, 'kx': 88, 'ky': 444, 'kz': 90, 'l-': 45, 'l0': 12, 'l1': 8, 'l2': 60, 'l3': 18, 'l4': 6, 'l5': 2, 'l6': 2, 'l7': 14, 'l8': 5, 'l9': 3, 'la': 14155, 'lb': 350, 'lc': 258, 'ld': 192, 'le': 13390, 'lf': 172, 'lg': 196, 'lh': 179, 'li': 13775, 'lj': 185, 'lk': 82, 'll': 276, 'lm': 185, 'ln': 163, 'lo': 17441, 'lp': 192, 'lq': 75, 'lr': 137, 'ls': 265, 'lt': 197, 'lu': 2947, 'lv': 210, 'lw': 133, 'lx': 124, 'ly': 761, 'lz': 136, 'm-': 162, 'm0': 11, 'm1': 26, 'm2': 47, 'm3': 32, 'm4': 31, 'm5': 8, 'm6': 7, 'm7': 6, 'm8': 11, 'm9': 4, 'ma': 21517, 'mb': 321, 'mc': 856, 'md': 322, 'me': 12983, 'mf': 160, 'mg': 199, 'mh': 180, 'mi': 10847, 'mj': 190, 'mk': 192, 'ml': 403, 'mm': 572, 'mn': 242, 'mo': 11994, 'mp': 473, 'mq': 80, 'mr': 773, 'ms': 631, 'mt': 424, 'mu': 3947, 'mv': 212, 'mw': 145, 'mx': 138, 'my': 8975, 'mz': 124, 'n-': 85, 'n0': 16, 'n1': 16, 'n2': 209, 'n3': 6, 'n4': 10, 'n5': 3, 'n6': 4, 'n7': 6, 'n8': 14, 'n9': 2, 'na': 5028, 'nb': 379, 'nc': 347, 'nd': 186, 'ne': 10656, 'nf': 213, 'ng': 232, 'nh': 270, 'ni': 3672, 'nj': 370, 'nk': 136, 'nl': 174, 'nm': 214, 'nn': 176, 'no': 10377, 'np': 174, 'nq': 65, 'nr': 161, 'ns': 248, 'nt': 270, 'nu': 1902, 'nv': 175, 'nw': 247, 'nx': 119, 'ny': 630, 'nz': 150, 'o-': 95, 'o0': 2, 'o1': 5, 'o2': 28, 'o3': 13, 'o4': 2, 'o5': 5, 'o6': 2, 'o7': 2, 'o8': 4, 'o9': 1, 'oa': 322, 'ob': 1267, 'oc': 959, 'od': 2152, 'oe': 162, 'of': 3428, 'og': 208, 'oh': 1587, 'oi': 1494, 'oj': 147, 'ok': 724, 'ol': 2309, 'om': 1532, 'on': 7256, 'oo': 234, 'op': 1673, 'oq': 58, 'or': 3282, 'os': 555, 'ot': 634, 'ou': 4435, 'ov': 944, 'ow': 4377, 'ox': 218, 'oy': 187, 'oz': 441, 'p-': 86, 'p0': 12, 'p1': 19, 'p2': 43, 'p3': 24, 'p4': 15, 'p5': 8, 'p6': 2, 'p7': 2, 'p8': 5, 'p9': 5, 'pa': 15758, 'pb': 196, 'pc': 606, 'pd': 263, 'pe': 6763, 'pf': 189, 'pg': 207, 'ph': 2496, 'pi': 7203, 'pj': 148, 'pk': 162, 'pl': 7080, 'pm': 258, 'pn': 171, 'po': 11038, 'pp': 369, 'pq': 91, 'pr': 7474, 'ps': 686, 'pt': 286, 'pu': 6557, 'pv': 156, 'pw': 142, 'px': 98, 'py': 246, 'pz': 114, 'q-': 38, 'q0': 3, 'q1': 8, 'q2': 8, 'q3': 6, 'q4': 4, 'q5': 3, 'q6': 3, 'q8': 44, 'q9': 4, 'qa': 220, 'qb': 92, 'qc': 118, 'qd': 194, 'qe': 117, 'qf': 81, 'qg': 84, 'qh': 109, 'qi': 391, 'qj': 79, 'qk': 73, 'ql': 125, 'qm': 82, 'qn': 92, 'qo': 114, 'qp': 102, 'qq': 248, 'qr': 83, 'qs': 131, 'qt': 89, 'qu': 3434, 'qv': 65, 'qw': 148, 'qx': 97, 'qy': 109, 'qz': 152, 'r-': 89, 'r0': 7, 'r1': 10, 'r2': 26, 'r3': 20, 'r4': 17, 'r5': 2, 'r6': 2, 'r7': 10, 'r8': 1, 'r9': 4, 'ra': 9842, 'rb': 211, 'rc': 334, 'rd': 204, 're': 13653, 'rf': 215, 'rg': 139, 'rh': 365, 'ri': 7079, 'rj': 156, 'rk': 119, 'rl': 150, 'rm': 254, 'rn': 173, 'ro': 9275, 'rp': 216, 'rq': 46, 'rr': 143, 'rs': 333, 'rt': 270, 'ru': 4797, 'rv': 182, 'rw': 142, 'rx': 199, 'ry': 348, 'rz': 102, 's-': 122, 's0': 6, 's1': 26, 's2': 33, 's3': 27, 's4': 19, 's5': 10, 's6': 12, 's7': 19, 's8': 12, 's9': 6, 'sa': 17038, 'sb': 328, 'sc': 3980, 'sd': 603, 'se': 18133, 'sf': 356, 'sg': 309, 'sh': 12388, 'si': 10761, 'sj': 286, 'sk': 1551, 'sl': 2639, 'sm': 2210, 'sn': 818, 'so': 11313, 'sp': 6560, 'sq': 323, 'sr': 385, 'ss': 497, 'st': 11992, 'su': 9496, 'sv': 251, 'sw': 1490, 'sx': 289, 'sy': 1044, 'sz': 702, 't-': 149, 't0': 4, 't1': 14, 't2': 16, 't3': 20, 't4': 8, 't5': 8, 't6': 6, 't7': 9, 't8': 34, 't9': 12, 'ta': 10163, 'tb': 227, 'tc': 353, 'td': 239, 'te': 12576, 'tf': 165, 'tg': 186, 'th': 20347, 'ti': 8367, 'tj': 321, 'tk': 178, 'tl': 273, 'tm': 289, 'tn': 269, 'to': 11512, 'tp': 227, 'tq': 90, 'tr': 12301, 'ts': 469, 'tt': 280, 'tu': 3572, 'tv': 534, 'tw': 2193, 'tx': 266, 'ty': 1588, 'tz': 175, 'u-': 119, 'u0': 3, 'u1': 15, 'u2': 21, 'u3': 9, 'u4': 3, 'u5': 3, 'u6': 3, 'u7': 2, 'u8': 11, 'u9': 5, 'ua': 258, 'ub': 352, 'uc': 350, 'ud': 179, 'ue': 138, 'uf': 188, 'ug': 891, 'uh': 194, 'ui': 127, 'uj': 66, 'uk': 422, 'ul': 536, 'um': 326, 'un': 3354, 'uo': 106, 'up': 2718, 'uq': 59, 'ur': 923, 'us': 6826, 'ut': 474, 'uu': 108, 'uv': 172, 'uw': 165, 'ux': 93, 'uy': 107, 'uz': 97, 'v-': 87, 'v0': 3, 'v1': 8, 'v2': 11, 'v3': 20, 'v4': 8, 'v5': 4, 'v6': 14, 'v7': 2, 'v8': 9, 'v9': 2, 'va': 5048, 'vb': 168, 'vc': 200, 'vd': 140, 've': 2797, 'vf': 111, 'vg': 120, 'vh': 121, 'vi': 8878, 'vj': 91, 'vk': 117, 'vl': 172, 'vm': 152, 'vn': 149, 'vo': 2303, 'vp': 172, 'vq': 76, 'vr': 232, 'vs': 192, 'vt': 174, 'vu': 214, 'vv': 139, 'vw': 105, 'vx': 101, 'vy': 119, 'vz': 97, 'w-': 49, 'w0': 9, 'w1': 15, 'w2': 10, 'w3': 49, 'w4': 11, 'w5': 5, 'w6': 2, 'w7': 5, 'w8': 16, 'w9': 7, 'wa': 13399, 'wb': 160, 'wc': 178, 'wd': 138, 'we': 10270, 'wf': 145, 'wg': 135, 'wh': 7676, 'wi': 8165, 'wj': 154, 'wk': 103, 'wl': 169, 'wm': 219, 'wn': 137, 'wo': 4635, 'wp': 199, 'wq': 78, 'wr': 578, 'ws': 246, 'wt': 170, 'wu': 306, 'wv': 136, 'ww': 2494, 'wx': 193, 'wy': 274, 'wz': 183, 'x-': 157, 'x0': 8, 'x1': 15, 'x2': 61, 'x3': 15, 'x4': 2, 'x5': 8, 'x6': 12, 'x7': 3, 'x8': 5, 'x9': 3, 'xa': 329, 'xb': 191, 'xc': 220, 'xd': 145, 'xe': 282, 'xf': 158, 'xg': 136, 'xh': 144, 'xi': 794, 'xj': 208, 'xk': 79, 'xl': 180, 'xm': 285, 'xn': 107, 'xo': 163, 'xp': 292, 'xq': 82, 'xr': 126, 'xs': 195, 'xt': 344, 'xu': 208, 'xv': 78, 'xw': 84, 'xx': 552, 'xy': 237, 'xz': 171, 'y-': 45, 'y0': 5, 'y1': 6, 'y2': 13, 'y3': 2, 'y5': 5, 'y6': 4, 'y7': 4, 'y8': 3, 'y9': 4, 'ya': 1485, 'yb': 102, 'yc': 195, 'yd': 137, 'ye': 2320, 'yf': 106, 'yg': 116, 'yh': 159, 'yi': 568, 'yj': 136, 'yk': 131, 'yl': 168, 'ym': 174, 'yn': 217, 'yo': 4580, 'yp': 214, 'yq': 89, 'yr': 98, 'ys': 233, 'yt': 248, 'yu': 779, 'yv': 101, 'yw': 155, 'yx': 142, 'yy': 176, 'yz': 169, 'z-': 40, 'z0': 4, 'z1': 6, 'z2': 6, 'z3': 5, 'z4': 1, 'z5': 4, 'z7': 2, 'z8': 1, 'z9': 3, 'za': 920, 'zb': 144, 'zc': 129, 'zd': 141, 'ze': 1083, 'zf': 95, 'zg': 277, 'zh': 651, 'zi': 676, 'zj': 315, 'zk': 102, 'zl': 176, 'zm': 120, 'zn': 117, 'zo': 741, 'zp': 107, 'zq': 131, 'zr': 148, 'zs': 167, 'zt': 102, 'zu': 336, 'zv': 70, 'zw': 126, 'zx': 108, 'zy': 171, 'zz': 266, }
normal
{ "blob_id": "f254f93193a7cb7ed2e55e4481ed85821cafcd7b", "index": 4339, "step-1": "<mask token>\n", "step-2": "TOTAL = 1306336\nONE = {'0': 1473, '1': 5936, '2': 3681, '3': 2996, '4': 2480, '5': 2494,\n '6': 1324, '7': 1474, '8': 1754, '9': 1740, 'a': 79714, 'b': 83472, 'c':\n 78015, 'd': 61702, 'e': 42190, 'f': 68530, 'g': 48942, 'h': 63661, 'i':\n 34947, 'j': 24312, 'k': 26724, 'l': 66351, 'm': 77245, 'n': 36942, 'o':\n 40744, 'p': 68978, 'q': 6750, 'r': 49135, 's': 116034, 't': 87440, 'u':\n 19423, 'v': 22356, 'w': 50718, 'x': 6079, 'y': 13089, 'z': 7491}\nTWO = {'0-': 19, '00': 145, '01': 143, '02': 212, '03': 90, '04': 61, '05':\n 241, '06': 31, '07': 151, '08': 104, '09': 99, '0a': 8, '0b': 8, '0c': \n 16, '0d': 18, '0e': 8, '0f': 7, '0g': 5, '0h': 4, '0i': 9, '0j': 1,\n '0k': 4, '0l': 2, '0m': 8, '0n': 10, '0o': 6, '0p': 10, '0r': 10, '0s':\n 10, '0t': 6, '0u': 5, '0v': 5, '0w': 5, '0x': 4, '0y': 3, '0z': 5, '1-':\n 177, '10': 983, '11': 537, '12': 767, '13': 327, '14': 270, '15': 257,\n '16': 276, '17': 318, '18': 505, '19': 280, '1a': 61, '1b': 58, '1c': \n 84, '1d': 52, '1e': 33, '1f': 32, '1g': 38, '1h': 44, '1i': 25, '1j': \n 13, '1k': 32, '1l': 33, '1m': 59, '1n': 39, '1o': 37, '1p': 68, '1q': 7,\n '1r': 21, '1s': 336, '1t': 54, '1u': 15, '1v': 14, '1w': 53, '1x': 7,\n '1y': 14, '1z': 10, '2-': 30, '20': 889, '21': 406, '22': 228, '23': \n 172, '24': 480, '25': 177, '26': 126, '27': 96, '28': 108, '29': 73,\n '2a': 50, '2b': 94, '2c': 59, '2d': 61, '2e': 29, '2f': 29, '2g': 47,\n '2h': 24, '2i': 22, '2j': 13, '2k': 27, '2l': 35, '2m': 62, '2n': 53,\n '2o': 22, '2p': 48, '2q': 7, '2r': 14, '2s': 53, '2t': 43, '2u': 20,\n '2v': 7, '2w': 43, '2x': 21, '2y': 7, '2z': 6, '3-': 53, '30': 292,\n '31': 224, '32': 188, '33': 179, '34': 91, '35': 153, '36': 367, '37': \n 101, '38': 122, '39': 118, '3a': 50, '3b': 45, '3c': 37, '3d': 350,\n '3e': 17, '3f': 26, '3g': 125, '3h': 27, '3i': 11, '3j': 9, '3k': 19,\n '3l': 25, '3m': 45, '3n': 17, '3o': 15, '3p': 32, '3q': 12, '3r': 72,\n '3s': 53, '3t': 28, '3u': 3, '3v': 13, '3w': 36, '3x': 17, '3y': 14,\n '3z': 10, '4-': 76, '40': 357, '41': 259, '42': 170, '43': 88, '44': \n 126, '45': 102, '46': 67, '47': 56, '48': 97, '49': 62, '4a': 41, '4b':\n 49, '4c': 55, '4d': 53, '4e': 51, '4f': 43, '4g': 52, '4h': 44, '4i': \n 19, '4j': 13, '4k': 22, '4l': 48, '4m': 62, '4n': 22, '4o': 21, '4p': \n 60, '4q': 11, '4r': 26, '4s': 94, '4t': 44, '4u': 40, '4v': 17, '4w': \n 45, '4x': 58, '4y': 24, '4z': 6, '5-': 30, '50': 323, '51': 574, '52': \n 361, '53': 79, '54': 155, '55': 141, '56': 109, '57': 66, '58': 85,\n '59': 87, '5a': 32, '5b': 17, '5c': 21, '5d': 39, '5e': 7, '5f': 17,\n '5g': 21, '5h': 10, '5i': 54, '5j': 4, '5k': 16, '5l': 19, '5m': 22,\n '5n': 8, '5o': 12, '5p': 27, '5q': 4, '5r': 9, '5s': 55, '5t': 38, '5u':\n 17, '5v': 5, '5w': 5, '5x': 9, '5y': 10, '5z': 6, '6-': 42, '60': 173,\n '61': 182, '62': 63, '63': 56, '64': 51, '65': 125, '66': 134, '67': 62,\n '68': 58, '69': 105, '6a': 12, '6b': 7, '6c': 11, '6d': 61, '6e': 6,\n '6f': 15, '6g': 7, '6h': 11, '6i': 6, '6j': 1, '6k': 7, '6l': 8, '6m': \n 16, '6n': 1, '6o': 5, '6p': 12, '6q': 6, '6r': 15, '6s': 28, '6t': 12,\n '6u': 2, '6v': 2, '6w': 8, '6x': 5, '6y': 9, '7-': 34, '70': 200, '71':\n 205, '72': 81, '73': 58, '74': 53, '75': 59, '76': 69, '77': 191, '78':\n 92, '79': 48, '7a': 33, '7b': 18, '7c': 28, '7d': 31, '7e': 13, '7f': \n 15, '7g': 11, '7h': 15, '7i': 7, '7j': 8, '7k': 16, '7l': 19, '7m': 15,\n '7n': 5, '7o': 13, '7p': 10, '7q': 2, '7r': 4, '7s': 33, '7t': 37, '7u':\n 2, '7v': 3, '7w': 13, '7x': 13, '7y': 12, '7z': 8, '8-': 61, '80': 336,\n '81': 180, '82': 61, '83': 62, '84': 99, '85': 85, '86': 138, '87': 85,\n '88': 339, '89': 78, '8a': 11, '8b': 16, '8c': 9, '8d': 10, '8e': 6,\n '8f': 10, '8g': 18, '8h': 7, '8i': 12, '8j': 4, '8k': 6, '8l': 6, '8m':\n 11, '8n': 2, '8o': 8, '8p': 15, '8q': 7, '8r': 10, '8s': 18, '8t': 24,\n '8u': 3, '8v': 2, '8w': 4, '8x': 1, '8y': 6, '8z': 4, '9-': 45, '90': \n 173, '91': 275, '92': 149, '93': 59, '94': 76, '95': 82, '96': 76, '97':\n 123, '98': 74, '99': 270, '9a': 19, '9b': 9, '9c': 22, '9d': 17, '9e': \n 10, '9f': 5, '9g': 16, '9h': 6, '9i': 20, '9j': 10, '9k': 9, '9l': 13,\n '9m': 19, '9n': 8, '9o': 8, '9p': 29, '9q': 3, '9r': 11, '9s': 22, '9t':\n 26, '9u': 3, '9v': 8, '9w': 11, '9x': 21, '9y': 8, '9z': 5, 'a-': 307,\n 'a0': 6, 'a1': 172, 'a2': 58, 'a3': 25, 'a4': 16, 'a5': 9, 'a6': 8,\n 'a7': 20, 'a8': 12, 'a9': 15, 'aa': 778, 'ab': 3124, 'ac': 4416, 'ad': \n 5316, 'ae': 537, 'af': 1343, 'ag': 4563, 'ah': 760, 'ai': 5617, 'aj': \n 331, 'ak': 715, 'al': 9102, 'am': 4388, 'an': 8462, 'ao': 351, 'ap': \n 2155, 'aq': 426, 'ar': 9178, 'as': 6419, 'at': 4007, 'au': 2485, 'av': \n 1218, 'aw': 1869, 'ax': 403, 'ay': 457, 'az': 646, 'b-': 148, 'b0': 7,\n 'b1': 19, 'b2': 94, 'b3': 12, 'b4': 24, 'b5': 9, 'b6': 4, 'b7': 5, 'b8':\n 2, 'b9': 6, 'ba': 15356, 'bb': 477, 'bc': 323, 'bd': 266, 'be': 14064,\n 'bf': 200, 'bg': 189, 'bh': 311, 'bi': 11911, 'bj': 604, 'bk': 178,\n 'bl': 5297, 'bm': 306, 'bn': 218, 'bo': 11986, 'bp': 229, 'bq': 103,\n 'br': 5001, 'bs': 317, 'bt': 266, 'bu': 12643, 'bv': 126, 'bw': 147,\n 'bx': 91, 'by': 2394, 'bz': 139, 'c-': 120, 'c0': 13, 'c1': 21, 'c2': \n 78, 'c3': 34, 'c4': 30, 'c5': 6, 'c6': 4, 'c7': 10, 'c8': 4, 'c9': 8,\n 'ca': 18400, 'cb': 368, 'cc': 678, 'cd': 484, 'ce': 3579, 'cf': 300,\n 'cg': 253, 'ch': 11318, 'ci': 2463, 'cj': 218, 'ck': 165, 'cl': 5881,\n 'cm': 371, 'cn': 895, 'co': 15790, 'cp': 497, 'cq': 239, 'cr': 5502,\n 'cs': 1710, 'ct': 364, 'cu': 6370, 'cv': 200, 'cw': 201, 'cx': 142,\n 'cy': 1053, 'cz': 246, 'd-': 147, 'd0': 7, 'd1': 14, 'd2': 37, 'd3': 29,\n 'd4': 10, 'd5': 5, 'd6': 4, 'd7': 8, 'd8': 6, 'd9': 7, 'da': 9910, 'db':\n 288, 'dc': 410, 'dd': 303, 'de': 11362, 'df': 288, 'dg': 307, 'dh': 280,\n 'di': 10934, 'dj': 682, 'dk': 157, 'dl': 393, 'dm': 361, 'dn': 476,\n 'do': 10944, 'dp': 211, 'dq': 106, 'dr': 6965, 'ds': 393, 'dt': 262,\n 'du': 4853, 'dv': 376, 'dw': 211, 'dx': 157, 'dy': 630, 'dz': 169, 'e-':\n 1066, 'e0': 9, 'e1': 12, 'e2': 26, 'e3': 27, 'e4': 11, 'e5': 2, 'e6': 6,\n 'e7': 6, 'e8': 37, 'e9': 5, 'ea': 6784, 'eb': 771, 'ec': 1530, 'ed': \n 2674, 'ee': 257, 'ef': 482, 'eg': 508, 'eh': 276, 'ei': 552, 'ej': 151,\n 'ek': 329, 'el': 3657, 'em': 1785, 'en': 4879, 'eo': 205, 'ep': 613,\n 'eq': 553, 'er': 2767, 'es': 1797, 'et': 766, 'eu': 1095, 'ev': 2975,\n 'ew': 218, 'ex': 2521, 'ey': 2066, 'ez': 772, 'f-': 75, 'f0': 6, 'f1': \n 54, 'f2': 25, 'f3': 5, 'f4': 9, 'f5': 12, 'f6': 2, 'f7': 4, 'f8': 10,\n 'f9': 2, 'fa': 12917, 'fb': 165, 'fc': 272, 'fd': 154, 'fe': 8514, 'ff':\n 195, 'fg': 107, 'fh': 175, 'fi': 14464, 'fj': 192, 'fk': 90, 'fl': 7482,\n 'fm': 210, 'fn': 114, 'fo': 8864, 'fp': 132, 'fq': 77, 'fr': 7566, 'fs':\n 413, 'ft': 252, 'fu': 5259, 'fv': 88, 'fw': 129, 'fx': 197, 'fy': 155,\n 'fz': 143, 'g-': 138, 'g0': 21, 'g1': 38, 'g2': 26, 'g3': 34, 'g4': 26,\n 'g5': 11, 'g6': 5, 'g7': 5, 'g8': 15, 'g9': 5, 'ga': 8708, 'gb': 232,\n 'gc': 262, 'gd': 339, 'ge': 5489, 'gf': 176, 'gg': 245, 'gh': 399, 'gi':\n 3752, 'gj': 108, 'gk': 138, 'gl': 2606, 'gm': 387, 'gn': 217, 'go': \n 9782, 'gp': 455, 'gq': 78, 'gr': 8101, 'gs': 381, 'gt': 252, 'gu': 5335,\n 'gv': 138, 'gw': 202, 'gx': 176, 'gy': 265, 'gz': 395, 'h-': 120, 'h0':\n 6, 'h1': 14, 'h2': 149, 'h3': 15, 'h4': 28, 'h5': 6, 'h6': 3, 'h7': 2,\n 'h8': 8, 'h9': 2, 'ha': 16216, 'hb': 351, 'hc': 228, 'hd': 442, 'he': \n 12087, 'hf': 180, 'hg': 158, 'hh': 243, 'hi': 10582, 'hj': 147, 'hk': \n 331, 'hl': 215, 'hm': 214, 'hn': 317, 'ho': 14380, 'hp': 207, 'hq': 147,\n 'hr': 318, 'hs': 380, 'ht': 314, 'hu': 4226, 'hv': 119, 'hw': 147, 'hx':\n 150, 'hy': 943, 'hz': 266, 'i-': 527, 'i0': 9, 'i1': 8, 'i2': 34, 'i3':\n 14, 'i4': 17, 'i5': 4, 'i6': 6, 'i7': 12, 'i8': 8, 'i9': 11, 'ia': 606,\n 'ib': 659, 'ic': 2175, 'id': 1981, 'ie': 282, 'if': 1514, 'ig': 488,\n 'ih': 370, 'ii': 226, 'ij': 122, 'ik': 351, 'il': 2287, 'im': 2155,\n 'in': 10117, 'io': 344, 'ip': 818, 'iq': 154, 'ir': 1037, 'is': 2803,\n 'it': 4514, 'iu': 135, 'iv': 328, 'iw': 391, 'ix': 87, 'iy': 123, 'iz':\n 230, 'j-': 143, 'j0': 7, 'j1': 2, 'j2': 20, 'j3': 8, 'j4': 10, 'j5': 1,\n 'j6': 1, 'j7': 2, 'j8': 3, 'j9': 2, 'ja': 3167, 'jb': 251, 'jc': 336,\n 'jd': 290, 'je': 2239, 'jf': 152, 'jg': 136, 'jh': 228, 'ji': 1541,\n 'jj': 266, 'jk': 191, 'jl': 249, 'jm': 340, 'jn': 230, 'jo': 7930, 'jp':\n 278, 'jq': 82, 'jr': 261, 'js': 448, 'jt': 174, 'ju': 4460, 'jv': 125,\n 'jw': 191, 'jx': 200, 'jy': 202, 'jz': 146, 'k-': 110, 'k0': 7, 'k1': \n 29, 'k2': 30, 'k3': 14, 'k4': 5, 'k5': 7, 'k6': 5, 'k7': 7, 'k8': 4,\n 'k9': 32, 'ka': 3724, 'kb': 212, 'kc': 275, 'kd': 182, 'ke': 6054, 'kf':\n 130, 'kg': 137, 'kh': 420, 'ki': 6316, 'kj': 144, 'kk': 167, 'kl': 487,\n 'km': 248, 'kn': 2612, 'ko': 1868, 'kp': 181, 'kq': 59, 'kr': 785, 'ks':\n 300, 'kt': 192, 'ku': 1013, 'kv': 116, 'kw': 230, 'kx': 88, 'ky': 444,\n 'kz': 90, 'l-': 45, 'l0': 12, 'l1': 8, 'l2': 60, 'l3': 18, 'l4': 6,\n 'l5': 2, 'l6': 2, 'l7': 14, 'l8': 5, 'l9': 3, 'la': 14155, 'lb': 350,\n 'lc': 258, 'ld': 192, 'le': 13390, 'lf': 172, 'lg': 196, 'lh': 179,\n 'li': 13775, 'lj': 185, 'lk': 82, 'll': 276, 'lm': 185, 'ln': 163, 'lo':\n 17441, 'lp': 192, 'lq': 75, 'lr': 137, 'ls': 265, 'lt': 197, 'lu': 2947,\n 'lv': 210, 'lw': 133, 'lx': 124, 'ly': 761, 'lz': 136, 'm-': 162, 'm0':\n 11, 'm1': 26, 'm2': 47, 'm3': 32, 'm4': 31, 'm5': 8, 'm6': 7, 'm7': 6,\n 'm8': 11, 'm9': 4, 'ma': 21517, 'mb': 321, 'mc': 856, 'md': 322, 'me': \n 12983, 'mf': 160, 'mg': 199, 'mh': 180, 'mi': 10847, 'mj': 190, 'mk': \n 192, 'ml': 403, 'mm': 572, 'mn': 242, 'mo': 11994, 'mp': 473, 'mq': 80,\n 'mr': 773, 'ms': 631, 'mt': 424, 'mu': 3947, 'mv': 212, 'mw': 145, 'mx':\n 138, 'my': 8975, 'mz': 124, 'n-': 85, 'n0': 16, 'n1': 16, 'n2': 209,\n 'n3': 6, 'n4': 10, 'n5': 3, 'n6': 4, 'n7': 6, 'n8': 14, 'n9': 2, 'na': \n 5028, 'nb': 379, 'nc': 347, 'nd': 186, 'ne': 10656, 'nf': 213, 'ng': \n 232, 'nh': 270, 'ni': 3672, 'nj': 370, 'nk': 136, 'nl': 174, 'nm': 214,\n 'nn': 176, 'no': 10377, 'np': 174, 'nq': 65, 'nr': 161, 'ns': 248, 'nt':\n 270, 'nu': 1902, 'nv': 175, 'nw': 247, 'nx': 119, 'ny': 630, 'nz': 150,\n 'o-': 95, 'o0': 2, 'o1': 5, 'o2': 28, 'o3': 13, 'o4': 2, 'o5': 5, 'o6':\n 2, 'o7': 2, 'o8': 4, 'o9': 1, 'oa': 322, 'ob': 1267, 'oc': 959, 'od': \n 2152, 'oe': 162, 'of': 3428, 'og': 208, 'oh': 1587, 'oi': 1494, 'oj': \n 147, 'ok': 724, 'ol': 2309, 'om': 1532, 'on': 7256, 'oo': 234, 'op': \n 1673, 'oq': 58, 'or': 3282, 'os': 555, 'ot': 634, 'ou': 4435, 'ov': 944,\n 'ow': 4377, 'ox': 218, 'oy': 187, 'oz': 441, 'p-': 86, 'p0': 12, 'p1': \n 19, 'p2': 43, 'p3': 24, 'p4': 15, 'p5': 8, 'p6': 2, 'p7': 2, 'p8': 5,\n 'p9': 5, 'pa': 15758, 'pb': 196, 'pc': 606, 'pd': 263, 'pe': 6763, 'pf':\n 189, 'pg': 207, 'ph': 2496, 'pi': 7203, 'pj': 148, 'pk': 162, 'pl': \n 7080, 'pm': 258, 'pn': 171, 'po': 11038, 'pp': 369, 'pq': 91, 'pr': \n 7474, 'ps': 686, 'pt': 286, 'pu': 6557, 'pv': 156, 'pw': 142, 'px': 98,\n 'py': 246, 'pz': 114, 'q-': 38, 'q0': 3, 'q1': 8, 'q2': 8, 'q3': 6,\n 'q4': 4, 'q5': 3, 'q6': 3, 'q8': 44, 'q9': 4, 'qa': 220, 'qb': 92, 'qc':\n 118, 'qd': 194, 'qe': 117, 'qf': 81, 'qg': 84, 'qh': 109, 'qi': 391,\n 'qj': 79, 'qk': 73, 'ql': 125, 'qm': 82, 'qn': 92, 'qo': 114, 'qp': 102,\n 'qq': 248, 'qr': 83, 'qs': 131, 'qt': 89, 'qu': 3434, 'qv': 65, 'qw': \n 148, 'qx': 97, 'qy': 109, 'qz': 152, 'r-': 89, 'r0': 7, 'r1': 10, 'r2':\n 26, 'r3': 20, 'r4': 17, 'r5': 2, 'r6': 2, 'r7': 10, 'r8': 1, 'r9': 4,\n 'ra': 9842, 'rb': 211, 'rc': 334, 'rd': 204, 're': 13653, 'rf': 215,\n 'rg': 139, 'rh': 365, 'ri': 7079, 'rj': 156, 'rk': 119, 'rl': 150, 'rm':\n 254, 'rn': 173, 'ro': 9275, 'rp': 216, 'rq': 46, 'rr': 143, 'rs': 333,\n 'rt': 270, 'ru': 4797, 'rv': 182, 'rw': 142, 'rx': 199, 'ry': 348, 'rz':\n 102, 's-': 122, 's0': 6, 's1': 26, 's2': 33, 's3': 27, 's4': 19, 's5': \n 10, 's6': 12, 's7': 19, 's8': 12, 's9': 6, 'sa': 17038, 'sb': 328, 'sc':\n 3980, 'sd': 603, 'se': 18133, 'sf': 356, 'sg': 309, 'sh': 12388, 'si': \n 10761, 'sj': 286, 'sk': 1551, 'sl': 2639, 'sm': 2210, 'sn': 818, 'so': \n 11313, 'sp': 6560, 'sq': 323, 'sr': 385, 'ss': 497, 'st': 11992, 'su': \n 9496, 'sv': 251, 'sw': 1490, 'sx': 289, 'sy': 1044, 'sz': 702, 't-': \n 149, 't0': 4, 't1': 14, 't2': 16, 't3': 20, 't4': 8, 't5': 8, 't6': 6,\n 't7': 9, 't8': 34, 't9': 12, 'ta': 10163, 'tb': 227, 'tc': 353, 'td': \n 239, 'te': 12576, 'tf': 165, 'tg': 186, 'th': 20347, 'ti': 8367, 'tj': \n 321, 'tk': 178, 'tl': 273, 'tm': 289, 'tn': 269, 'to': 11512, 'tp': 227,\n 'tq': 90, 'tr': 12301, 'ts': 469, 'tt': 280, 'tu': 3572, 'tv': 534,\n 'tw': 2193, 'tx': 266, 'ty': 1588, 'tz': 175, 'u-': 119, 'u0': 3, 'u1':\n 15, 'u2': 21, 'u3': 9, 'u4': 3, 'u5': 3, 'u6': 3, 'u7': 2, 'u8': 11,\n 'u9': 5, 'ua': 258, 'ub': 352, 'uc': 350, 'ud': 179, 'ue': 138, 'uf': \n 188, 'ug': 891, 'uh': 194, 'ui': 127, 'uj': 66, 'uk': 422, 'ul': 536,\n 'um': 326, 'un': 3354, 'uo': 106, 'up': 2718, 'uq': 59, 'ur': 923, 'us':\n 6826, 'ut': 474, 'uu': 108, 'uv': 172, 'uw': 165, 'ux': 93, 'uy': 107,\n 'uz': 97, 'v-': 87, 'v0': 3, 'v1': 8, 'v2': 11, 'v3': 20, 'v4': 8, 'v5':\n 4, 'v6': 14, 'v7': 2, 'v8': 9, 'v9': 2, 'va': 5048, 'vb': 168, 'vc': \n 200, 'vd': 140, 've': 2797, 'vf': 111, 'vg': 120, 'vh': 121, 'vi': 8878,\n 'vj': 91, 'vk': 117, 'vl': 172, 'vm': 152, 'vn': 149, 'vo': 2303, 'vp':\n 172, 'vq': 76, 'vr': 232, 'vs': 192, 'vt': 174, 'vu': 214, 'vv': 139,\n 'vw': 105, 'vx': 101, 'vy': 119, 'vz': 97, 'w-': 49, 'w0': 9, 'w1': 15,\n 'w2': 10, 'w3': 49, 'w4': 11, 'w5': 5, 'w6': 2, 'w7': 5, 'w8': 16, 'w9':\n 7, 'wa': 13399, 'wb': 160, 'wc': 178, 'wd': 138, 'we': 10270, 'wf': 145,\n 'wg': 135, 'wh': 7676, 'wi': 8165, 'wj': 154, 'wk': 103, 'wl': 169,\n 'wm': 219, 'wn': 137, 'wo': 4635, 'wp': 199, 'wq': 78, 'wr': 578, 'ws':\n 246, 'wt': 170, 'wu': 306, 'wv': 136, 'ww': 2494, 'wx': 193, 'wy': 274,\n 'wz': 183, 'x-': 157, 'x0': 8, 'x1': 15, 'x2': 61, 'x3': 15, 'x4': 2,\n 'x5': 8, 'x6': 12, 'x7': 3, 'x8': 5, 'x9': 3, 'xa': 329, 'xb': 191,\n 'xc': 220, 'xd': 145, 'xe': 282, 'xf': 158, 'xg': 136, 'xh': 144, 'xi':\n 794, 'xj': 208, 'xk': 79, 'xl': 180, 'xm': 285, 'xn': 107, 'xo': 163,\n 'xp': 292, 'xq': 82, 'xr': 126, 'xs': 195, 'xt': 344, 'xu': 208, 'xv': \n 78, 'xw': 84, 'xx': 552, 'xy': 237, 'xz': 171, 'y-': 45, 'y0': 5, 'y1':\n 6, 'y2': 13, 'y3': 2, 'y5': 5, 'y6': 4, 'y7': 4, 'y8': 3, 'y9': 4, 'ya':\n 1485, 'yb': 102, 'yc': 195, 'yd': 137, 'ye': 2320, 'yf': 106, 'yg': 116,\n 'yh': 159, 'yi': 568, 'yj': 136, 'yk': 131, 'yl': 168, 'ym': 174, 'yn':\n 217, 'yo': 4580, 'yp': 214, 'yq': 89, 'yr': 98, 'ys': 233, 'yt': 248,\n 'yu': 779, 'yv': 101, 'yw': 155, 'yx': 142, 'yy': 176, 'yz': 169, 'z-':\n 40, 'z0': 4, 'z1': 6, 'z2': 6, 'z3': 5, 'z4': 1, 'z5': 4, 'z7': 2, 'z8':\n 1, 'z9': 3, 'za': 920, 'zb': 144, 'zc': 129, 'zd': 141, 'ze': 1083,\n 'zf': 95, 'zg': 277, 'zh': 651, 'zi': 676, 'zj': 315, 'zk': 102, 'zl': \n 176, 'zm': 120, 'zn': 117, 'zo': 741, 'zp': 107, 'zq': 131, 'zr': 148,\n 'zs': 167, 'zt': 102, 'zu': 336, 'zv': 70, 'zw': 126, 'zx': 108, 'zy': \n 171, 'zz': 266}\n", "step-3": "TOTAL = 1306336\n\nONE = {\n'0': 1473,\n'1': 5936,\n'2': 3681,\n'3': 2996,\n'4': 2480,\n'5': 2494,\n'6': 1324,\n'7': 1474,\n'8': 1754,\n'9': 1740,\n'a': 79714,\n'b': 83472,\n'c': 78015,\n'd': 61702,\n'e': 42190,\n'f': 68530,\n'g': 48942,\n'h': 63661,\n'i': 34947,\n'j': 24312,\n'k': 26724,\n'l': 66351,\n'm': 77245,\n'n': 36942,\n'o': 40744,\n'p': 68978,\n'q': 6750,\n'r': 49135,\n's': 116034,\n't': 87440,\n'u': 19423,\n'v': 22356,\n'w': 50718,\n'x': 6079,\n'y': 13089,\n'z': 7491,\n}\n\nTWO = {\n'0-': 19,\n'00': 145,\n'01': 143,\n'02': 212,\n'03': 90,\n'04': 61,\n'05': 241,\n'06': 31,\n'07': 151,\n'08': 104,\n'09': 99,\n'0a': 8,\n'0b': 8,\n'0c': 16,\n'0d': 18,\n'0e': 8,\n'0f': 7,\n'0g': 5,\n'0h': 4,\n'0i': 9,\n'0j': 1,\n'0k': 4,\n'0l': 2,\n'0m': 8,\n'0n': 10,\n'0o': 6,\n'0p': 10,\n'0r': 10,\n'0s': 10,\n'0t': 6,\n'0u': 5,\n'0v': 5,\n'0w': 5,\n'0x': 4,\n'0y': 3,\n'0z': 5,\n'1-': 177,\n'10': 983,\n'11': 537,\n'12': 767,\n'13': 327,\n'14': 270,\n'15': 257,\n'16': 276,\n'17': 318,\n'18': 505,\n'19': 280,\n'1a': 61,\n'1b': 58,\n'1c': 84,\n'1d': 52,\n'1e': 33,\n'1f': 32,\n'1g': 38,\n'1h': 44,\n'1i': 25,\n'1j': 13,\n'1k': 32,\n'1l': 33,\n'1m': 59,\n'1n': 39,\n'1o': 37,\n'1p': 68,\n'1q': 7,\n'1r': 21,\n'1s': 336,\n'1t': 54,\n'1u': 15,\n'1v': 14,\n'1w': 53,\n'1x': 7,\n'1y': 14,\n'1z': 10,\n'2-': 30,\n'20': 889,\n'21': 406,\n'22': 228,\n'23': 172,\n'24': 480,\n'25': 177,\n'26': 126,\n'27': 96,\n'28': 108,\n'29': 73,\n'2a': 50,\n'2b': 94,\n'2c': 59,\n'2d': 61,\n'2e': 29,\n'2f': 29,\n'2g': 47,\n'2h': 24,\n'2i': 22,\n'2j': 13,\n'2k': 27,\n'2l': 35,\n'2m': 62,\n'2n': 53,\n'2o': 22,\n'2p': 48,\n'2q': 7,\n'2r': 14,\n'2s': 53,\n'2t': 43,\n'2u': 20,\n'2v': 7,\n'2w': 43,\n'2x': 21,\n'2y': 7,\n'2z': 6,\n'3-': 53,\n'30': 292,\n'31': 224,\n'32': 188,\n'33': 179,\n'34': 91,\n'35': 153,\n'36': 367,\n'37': 101,\n'38': 122,\n'39': 118,\n'3a': 50,\n'3b': 45,\n'3c': 37,\n'3d': 350,\n'3e': 17,\n'3f': 26,\n'3g': 125,\n'3h': 27,\n'3i': 11,\n'3j': 9,\n'3k': 19,\n'3l': 25,\n'3m': 45,\n'3n': 17,\n'3o': 15,\n'3p': 32,\n'3q': 12,\n'3r': 72,\n'3s': 53,\n'3t': 28,\n'3u': 3,\n'3v': 13,\n'3w': 36,\n'3x': 17,\n'3y': 14,\n'3z': 10,\n'4-': 76,\n'40': 357,\n'41': 259,\n'42': 170,\n'43': 88,\n'44': 126,\n'45': 102,\n'46': 67,\n'47': 56,\n'48': 97,\n'49': 62,\n'4a': 41,\n'4b': 49,\n'4c': 55,\n'4d': 53,\n'4e': 51,\n'4f': 43,\n'4g': 52,\n'4h': 44,\n'4i': 19,\n'4j': 13,\n'4k': 22,\n'4l': 48,\n'4m': 62,\n'4n': 22,\n'4o': 21,\n'4p': 60,\n'4q': 11,\n'4r': 26,\n'4s': 94,\n'4t': 44,\n'4u': 40,\n'4v': 17,\n'4w': 45,\n'4x': 58,\n'4y': 24,\n'4z': 6,\n'5-': 30,\n'50': 323,\n'51': 574,\n'52': 361,\n'53': 79,\n'54': 155,\n'55': 141,\n'56': 109,\n'57': 66,\n'58': 85,\n'59': 87,\n'5a': 32,\n'5b': 17,\n'5c': 21,\n'5d': 39,\n'5e': 7,\n'5f': 17,\n'5g': 21,\n'5h': 10,\n'5i': 54,\n'5j': 4,\n'5k': 16,\n'5l': 19,\n'5m': 22,\n'5n': 8,\n'5o': 12,\n'5p': 27,\n'5q': 4,\n'5r': 9,\n'5s': 55,\n'5t': 38,\n'5u': 17,\n'5v': 5,\n'5w': 5,\n'5x': 9,\n'5y': 10,\n'5z': 6,\n'6-': 42,\n'60': 173,\n'61': 182,\n'62': 63,\n'63': 56,\n'64': 51,\n'65': 125,\n'66': 134,\n'67': 62,\n'68': 58,\n'69': 105,\n'6a': 12,\n'6b': 7,\n'6c': 11,\n'6d': 61,\n'6e': 6,\n'6f': 15,\n'6g': 7,\n'6h': 11,\n'6i': 6,\n'6j': 1,\n'6k': 7,\n'6l': 8,\n'6m': 16,\n'6n': 1,\n'6o': 5,\n'6p': 12,\n'6q': 6,\n'6r': 15,\n'6s': 28,\n'6t': 12,\n'6u': 2,\n'6v': 2,\n'6w': 8,\n'6x': 5,\n'6y': 9,\n'7-': 34,\n'70': 200,\n'71': 205,\n'72': 81,\n'73': 58,\n'74': 53,\n'75': 59,\n'76': 69,\n'77': 191,\n'78': 92,\n'79': 48,\n'7a': 33,\n'7b': 18,\n'7c': 28,\n'7d': 31,\n'7e': 13,\n'7f': 15,\n'7g': 11,\n'7h': 15,\n'7i': 7,\n'7j': 8,\n'7k': 16,\n'7l': 19,\n'7m': 15,\n'7n': 5,\n'7o': 13,\n'7p': 10,\n'7q': 2,\n'7r': 4,\n'7s': 33,\n'7t': 37,\n'7u': 2,\n'7v': 3,\n'7w': 13,\n'7x': 13,\n'7y': 12,\n'7z': 8,\n'8-': 61,\n'80': 336,\n'81': 180,\n'82': 61,\n'83': 62,\n'84': 99,\n'85': 85,\n'86': 138,\n'87': 85,\n'88': 339,\n'89': 78,\n'8a': 11,\n'8b': 16,\n'8c': 9,\n'8d': 10,\n'8e': 6,\n'8f': 10,\n'8g': 18,\n'8h': 7,\n'8i': 12,\n'8j': 4,\n'8k': 6,\n'8l': 6,\n'8m': 11,\n'8n': 2,\n'8o': 8,\n'8p': 15,\n'8q': 7,\n'8r': 10,\n'8s': 18,\n'8t': 24,\n'8u': 3,\n'8v': 2,\n'8w': 4,\n'8x': 1,\n'8y': 6,\n'8z': 4,\n'9-': 45,\n'90': 173,\n'91': 275,\n'92': 149,\n'93': 59,\n'94': 76,\n'95': 82,\n'96': 76,\n'97': 123,\n'98': 74,\n'99': 270,\n'9a': 19,\n'9b': 9,\n'9c': 22,\n'9d': 17,\n'9e': 10,\n'9f': 5,\n'9g': 16,\n'9h': 6,\n'9i': 20,\n'9j': 10,\n'9k': 9,\n'9l': 13,\n'9m': 19,\n'9n': 8,\n'9o': 8,\n'9p': 29,\n'9q': 3,\n'9r': 11,\n'9s': 22,\n'9t': 26,\n'9u': 3,\n'9v': 8,\n'9w': 11,\n'9x': 21,\n'9y': 8,\n'9z': 5,\n'a-': 307,\n'a0': 6,\n'a1': 172,\n'a2': 58,\n'a3': 25,\n'a4': 16,\n'a5': 9,\n'a6': 8,\n'a7': 20,\n'a8': 12,\n'a9': 15,\n'aa': 778,\n'ab': 3124,\n'ac': 4416,\n'ad': 5316,\n'ae': 537,\n'af': 1343,\n'ag': 4563,\n'ah': 760,\n'ai': 5617,\n'aj': 331,\n'ak': 715,\n'al': 9102,\n'am': 4388,\n'an': 8462,\n'ao': 351,\n'ap': 2155,\n'aq': 426,\n'ar': 9178,\n'as': 6419,\n'at': 4007,\n'au': 2485,\n'av': 1218,\n'aw': 1869,\n'ax': 403,\n'ay': 457,\n'az': 646,\n'b-': 148,\n'b0': 7,\n'b1': 19,\n'b2': 94,\n'b3': 12,\n'b4': 24,\n'b5': 9,\n'b6': 4,\n'b7': 5,\n'b8': 2,\n'b9': 6,\n'ba': 15356,\n'bb': 477,\n'bc': 323,\n'bd': 266,\n'be': 14064,\n'bf': 200,\n'bg': 189,\n'bh': 311,\n'bi': 11911,\n'bj': 604,\n'bk': 178,\n'bl': 5297,\n'bm': 306,\n'bn': 218,\n'bo': 11986,\n'bp': 229,\n'bq': 103,\n'br': 5001,\n'bs': 317,\n'bt': 266,\n'bu': 12643,\n'bv': 126,\n'bw': 147,\n'bx': 91,\n'by': 2394,\n'bz': 139,\n'c-': 120,\n'c0': 13,\n'c1': 21,\n'c2': 78,\n'c3': 34,\n'c4': 30,\n'c5': 6,\n'c6': 4,\n'c7': 10,\n'c8': 4,\n'c9': 8,\n'ca': 18400,\n'cb': 368,\n'cc': 678,\n'cd': 484,\n'ce': 3579,\n'cf': 300,\n'cg': 253,\n'ch': 11318,\n'ci': 2463,\n'cj': 218,\n'ck': 165,\n'cl': 5881,\n'cm': 371,\n'cn': 895,\n'co': 15790,\n'cp': 497,\n'cq': 239,\n'cr': 5502,\n'cs': 1710,\n'ct': 364,\n'cu': 6370,\n'cv': 200,\n'cw': 201,\n'cx': 142,\n'cy': 1053,\n'cz': 246,\n'd-': 147,\n'd0': 7,\n'd1': 14,\n'd2': 37,\n'd3': 29,\n'd4': 10,\n'd5': 5,\n'd6': 4,\n'd7': 8,\n'd8': 6,\n'd9': 7,\n'da': 9910,\n'db': 288,\n'dc': 410,\n'dd': 303,\n'de': 11362,\n'df': 288,\n'dg': 307,\n'dh': 280,\n'di': 10934,\n'dj': 682,\n'dk': 157,\n'dl': 393,\n'dm': 361,\n'dn': 476,\n'do': 10944,\n'dp': 211,\n'dq': 106,\n'dr': 6965,\n'ds': 393,\n'dt': 262,\n'du': 4853,\n'dv': 376,\n'dw': 211,\n'dx': 157,\n'dy': 630,\n'dz': 169,\n'e-': 1066,\n'e0': 9,\n'e1': 12,\n'e2': 26,\n'e3': 27,\n'e4': 11,\n'e5': 2,\n'e6': 6,\n'e7': 6,\n'e8': 37,\n'e9': 5,\n'ea': 6784,\n'eb': 771,\n'ec': 1530,\n'ed': 2674,\n'ee': 257,\n'ef': 482,\n'eg': 508,\n'eh': 276,\n'ei': 552,\n'ej': 151,\n'ek': 329,\n'el': 3657,\n'em': 1785,\n'en': 4879,\n'eo': 205,\n'ep': 613,\n'eq': 553,\n'er': 2767,\n'es': 1797,\n'et': 766,\n'eu': 1095,\n'ev': 2975,\n'ew': 218,\n'ex': 2521,\n'ey': 2066,\n'ez': 772,\n'f-': 75,\n'f0': 6,\n'f1': 54,\n'f2': 25,\n'f3': 5,\n'f4': 9,\n'f5': 12,\n'f6': 2,\n'f7': 4,\n'f8': 10,\n'f9': 2,\n'fa': 12917,\n'fb': 165,\n'fc': 272,\n'fd': 154,\n'fe': 8514,\n'ff': 195,\n'fg': 107,\n'fh': 175,\n'fi': 14464,\n'fj': 192,\n'fk': 90,\n'fl': 7482,\n'fm': 210,\n'fn': 114,\n'fo': 8864,\n'fp': 132,\n'fq': 77,\n'fr': 7566,\n'fs': 413,\n'ft': 252,\n'fu': 5259,\n'fv': 88,\n'fw': 129,\n'fx': 197,\n'fy': 155,\n'fz': 143,\n'g-': 138,\n'g0': 21,\n'g1': 38,\n'g2': 26,\n'g3': 34,\n'g4': 26,\n'g5': 11,\n'g6': 5,\n'g7': 5,\n'g8': 15,\n'g9': 5,\n'ga': 8708,\n'gb': 232,\n'gc': 262,\n'gd': 339,\n'ge': 5489,\n'gf': 176,\n'gg': 245,\n'gh': 399,\n'gi': 3752,\n'gj': 108,\n'gk': 138,\n'gl': 2606,\n'gm': 387,\n'gn': 217,\n'go': 9782,\n'gp': 455,\n'gq': 78,\n'gr': 8101,\n'gs': 381,\n'gt': 252,\n'gu': 5335,\n'gv': 138,\n'gw': 202,\n'gx': 176,\n'gy': 265,\n'gz': 395,\n'h-': 120,\n'h0': 6,\n'h1': 14,\n'h2': 149,\n'h3': 15,\n'h4': 28,\n'h5': 6,\n'h6': 3,\n'h7': 2,\n'h8': 8,\n'h9': 2,\n'ha': 16216,\n'hb': 351,\n'hc': 228,\n'hd': 442,\n'he': 12087,\n'hf': 180,\n'hg': 158,\n'hh': 243,\n'hi': 10582,\n'hj': 147,\n'hk': 331,\n'hl': 215,\n'hm': 214,\n'hn': 317,\n'ho': 14380,\n'hp': 207,\n'hq': 147,\n'hr': 318,\n'hs': 380,\n'ht': 314,\n'hu': 4226,\n'hv': 119,\n'hw': 147,\n'hx': 150,\n'hy': 943,\n'hz': 266,\n'i-': 527,\n'i0': 9,\n'i1': 8,\n'i2': 34,\n'i3': 14,\n'i4': 17,\n'i5': 4,\n'i6': 6,\n'i7': 12,\n'i8': 8,\n'i9': 11,\n'ia': 606,\n'ib': 659,\n'ic': 2175,\n'id': 1981,\n'ie': 282,\n'if': 1514,\n'ig': 488,\n'ih': 370,\n'ii': 226,\n'ij': 122,\n'ik': 351,\n'il': 2287,\n'im': 2155,\n'in': 10117,\n'io': 344,\n'ip': 818,\n'iq': 154,\n'ir': 1037,\n'is': 2803,\n'it': 4514,\n'iu': 135,\n'iv': 328,\n'iw': 391,\n'ix': 87,\n'iy': 123,\n'iz': 230,\n'j-': 143,\n'j0': 7,\n'j1': 2,\n'j2': 20,\n'j3': 8,\n'j4': 10,\n'j5': 1,\n'j6': 1,\n'j7': 2,\n'j8': 3,\n'j9': 2,\n'ja': 3167,\n'jb': 251,\n'jc': 336,\n'jd': 290,\n'je': 2239,\n'jf': 152,\n'jg': 136,\n'jh': 228,\n'ji': 1541,\n'jj': 266,\n'jk': 191,\n'jl': 249,\n'jm': 340,\n'jn': 230,\n'jo': 7930,\n'jp': 278,\n'jq': 82,\n'jr': 261,\n'js': 448,\n'jt': 174,\n'ju': 4460,\n'jv': 125,\n'jw': 191,\n'jx': 200,\n'jy': 202,\n'jz': 146,\n'k-': 110,\n'k0': 7,\n'k1': 29,\n'k2': 30,\n'k3': 14,\n'k4': 5,\n'k5': 7,\n'k6': 5,\n'k7': 7,\n'k8': 4,\n'k9': 32,\n'ka': 3724,\n'kb': 212,\n'kc': 275,\n'kd': 182,\n'ke': 6054,\n'kf': 130,\n'kg': 137,\n'kh': 420,\n'ki': 6316,\n'kj': 144,\n'kk': 167,\n'kl': 487,\n'km': 248,\n'kn': 2612,\n'ko': 1868,\n'kp': 181,\n'kq': 59,\n'kr': 785,\n'ks': 300,\n'kt': 192,\n'ku': 1013,\n'kv': 116,\n'kw': 230,\n'kx': 88,\n'ky': 444,\n'kz': 90,\n'l-': 45,\n'l0': 12,\n'l1': 8,\n'l2': 60,\n'l3': 18,\n'l4': 6,\n'l5': 2,\n'l6': 2,\n'l7': 14,\n'l8': 5,\n'l9': 3,\n'la': 14155,\n'lb': 350,\n'lc': 258,\n'ld': 192,\n'le': 13390,\n'lf': 172,\n'lg': 196,\n'lh': 179,\n'li': 13775,\n'lj': 185,\n'lk': 82,\n'll': 276,\n'lm': 185,\n'ln': 163,\n'lo': 17441,\n'lp': 192,\n'lq': 75,\n'lr': 137,\n'ls': 265,\n'lt': 197,\n'lu': 2947,\n'lv': 210,\n'lw': 133,\n'lx': 124,\n'ly': 761,\n'lz': 136,\n'm-': 162,\n'm0': 11,\n'm1': 26,\n'm2': 47,\n'm3': 32,\n'm4': 31,\n'm5': 8,\n'm6': 7,\n'm7': 6,\n'm8': 11,\n'm9': 4,\n'ma': 21517,\n'mb': 321,\n'mc': 856,\n'md': 322,\n'me': 12983,\n'mf': 160,\n'mg': 199,\n'mh': 180,\n'mi': 10847,\n'mj': 190,\n'mk': 192,\n'ml': 403,\n'mm': 572,\n'mn': 242,\n'mo': 11994,\n'mp': 473,\n'mq': 80,\n'mr': 773,\n'ms': 631,\n'mt': 424,\n'mu': 3947,\n'mv': 212,\n'mw': 145,\n'mx': 138,\n'my': 8975,\n'mz': 124,\n'n-': 85,\n'n0': 16,\n'n1': 16,\n'n2': 209,\n'n3': 6,\n'n4': 10,\n'n5': 3,\n'n6': 4,\n'n7': 6,\n'n8': 14,\n'n9': 2,\n'na': 5028,\n'nb': 379,\n'nc': 347,\n'nd': 186,\n'ne': 10656,\n'nf': 213,\n'ng': 232,\n'nh': 270,\n'ni': 3672,\n'nj': 370,\n'nk': 136,\n'nl': 174,\n'nm': 214,\n'nn': 176,\n'no': 10377,\n'np': 174,\n'nq': 65,\n'nr': 161,\n'ns': 248,\n'nt': 270,\n'nu': 1902,\n'nv': 175,\n'nw': 247,\n'nx': 119,\n'ny': 630,\n'nz': 150,\n'o-': 95,\n'o0': 2,\n'o1': 5,\n'o2': 28,\n'o3': 13,\n'o4': 2,\n'o5': 5,\n'o6': 2,\n'o7': 2,\n'o8': 4,\n'o9': 1,\n'oa': 322,\n'ob': 1267,\n'oc': 959,\n'od': 2152,\n'oe': 162,\n'of': 3428,\n'og': 208,\n'oh': 1587,\n'oi': 1494,\n'oj': 147,\n'ok': 724,\n'ol': 2309,\n'om': 1532,\n'on': 7256,\n'oo': 234,\n'op': 1673,\n'oq': 58,\n'or': 3282,\n'os': 555,\n'ot': 634,\n'ou': 4435,\n'ov': 944,\n'ow': 4377,\n'ox': 218,\n'oy': 187,\n'oz': 441,\n'p-': 86,\n'p0': 12,\n'p1': 19,\n'p2': 43,\n'p3': 24,\n'p4': 15,\n'p5': 8,\n'p6': 2,\n'p7': 2,\n'p8': 5,\n'p9': 5,\n'pa': 15758,\n'pb': 196,\n'pc': 606,\n'pd': 263,\n'pe': 6763,\n'pf': 189,\n'pg': 207,\n'ph': 2496,\n'pi': 7203,\n'pj': 148,\n'pk': 162,\n'pl': 7080,\n'pm': 258,\n'pn': 171,\n'po': 11038,\n'pp': 369,\n'pq': 91,\n'pr': 7474,\n'ps': 686,\n'pt': 286,\n'pu': 6557,\n'pv': 156,\n'pw': 142,\n'px': 98,\n'py': 246,\n'pz': 114,\n'q-': 38,\n'q0': 3,\n'q1': 8,\n'q2': 8,\n'q3': 6,\n'q4': 4,\n'q5': 3,\n'q6': 3,\n'q8': 44,\n'q9': 4,\n'qa': 220,\n'qb': 92,\n'qc': 118,\n'qd': 194,\n'qe': 117,\n'qf': 81,\n'qg': 84,\n'qh': 109,\n'qi': 391,\n'qj': 79,\n'qk': 73,\n'ql': 125,\n'qm': 82,\n'qn': 92,\n'qo': 114,\n'qp': 102,\n'qq': 248,\n'qr': 83,\n'qs': 131,\n'qt': 89,\n'qu': 3434,\n'qv': 65,\n'qw': 148,\n'qx': 97,\n'qy': 109,\n'qz': 152,\n'r-': 89,\n'r0': 7,\n'r1': 10,\n'r2': 26,\n'r3': 20,\n'r4': 17,\n'r5': 2,\n'r6': 2,\n'r7': 10,\n'r8': 1,\n'r9': 4,\n'ra': 9842,\n'rb': 211,\n'rc': 334,\n'rd': 204,\n're': 13653,\n'rf': 215,\n'rg': 139,\n'rh': 365,\n'ri': 7079,\n'rj': 156,\n'rk': 119,\n'rl': 150,\n'rm': 254,\n'rn': 173,\n'ro': 9275,\n'rp': 216,\n'rq': 46,\n'rr': 143,\n'rs': 333,\n'rt': 270,\n'ru': 4797,\n'rv': 182,\n'rw': 142,\n'rx': 199,\n'ry': 348,\n'rz': 102,\n's-': 122,\n's0': 6,\n's1': 26,\n's2': 33,\n's3': 27,\n's4': 19,\n's5': 10,\n's6': 12,\n's7': 19,\n's8': 12,\n's9': 6,\n'sa': 17038,\n'sb': 328,\n'sc': 3980,\n'sd': 603,\n'se': 18133,\n'sf': 356,\n'sg': 309,\n'sh': 12388,\n'si': 10761,\n'sj': 286,\n'sk': 1551,\n'sl': 2639,\n'sm': 2210,\n'sn': 818,\n'so': 11313,\n'sp': 6560,\n'sq': 323,\n'sr': 385,\n'ss': 497,\n'st': 11992,\n'su': 9496,\n'sv': 251,\n'sw': 1490,\n'sx': 289,\n'sy': 1044,\n'sz': 702,\n't-': 149,\n't0': 4,\n't1': 14,\n't2': 16,\n't3': 20,\n't4': 8,\n't5': 8,\n't6': 6,\n't7': 9,\n't8': 34,\n't9': 12,\n'ta': 10163,\n'tb': 227,\n'tc': 353,\n'td': 239,\n'te': 12576,\n'tf': 165,\n'tg': 186,\n'th': 20347,\n'ti': 8367,\n'tj': 321,\n'tk': 178,\n'tl': 273,\n'tm': 289,\n'tn': 269,\n'to': 11512,\n'tp': 227,\n'tq': 90,\n'tr': 12301,\n'ts': 469,\n'tt': 280,\n'tu': 3572,\n'tv': 534,\n'tw': 2193,\n'tx': 266,\n'ty': 1588,\n'tz': 175,\n'u-': 119,\n'u0': 3,\n'u1': 15,\n'u2': 21,\n'u3': 9,\n'u4': 3,\n'u5': 3,\n'u6': 3,\n'u7': 2,\n'u8': 11,\n'u9': 5,\n'ua': 258,\n'ub': 352,\n'uc': 350,\n'ud': 179,\n'ue': 138,\n'uf': 188,\n'ug': 891,\n'uh': 194,\n'ui': 127,\n'uj': 66,\n'uk': 422,\n'ul': 536,\n'um': 326,\n'un': 3354,\n'uo': 106,\n'up': 2718,\n'uq': 59,\n'ur': 923,\n'us': 6826,\n'ut': 474,\n'uu': 108,\n'uv': 172,\n'uw': 165,\n'ux': 93,\n'uy': 107,\n'uz': 97,\n'v-': 87,\n'v0': 3,\n'v1': 8,\n'v2': 11,\n'v3': 20,\n'v4': 8,\n'v5': 4,\n'v6': 14,\n'v7': 2,\n'v8': 9,\n'v9': 2,\n'va': 5048,\n'vb': 168,\n'vc': 200,\n'vd': 140,\n've': 2797,\n'vf': 111,\n'vg': 120,\n'vh': 121,\n'vi': 8878,\n'vj': 91,\n'vk': 117,\n'vl': 172,\n'vm': 152,\n'vn': 149,\n'vo': 2303,\n'vp': 172,\n'vq': 76,\n'vr': 232,\n'vs': 192,\n'vt': 174,\n'vu': 214,\n'vv': 139,\n'vw': 105,\n'vx': 101,\n'vy': 119,\n'vz': 97,\n'w-': 49,\n'w0': 9,\n'w1': 15,\n'w2': 10,\n'w3': 49,\n'w4': 11,\n'w5': 5,\n'w6': 2,\n'w7': 5,\n'w8': 16,\n'w9': 7,\n'wa': 13399,\n'wb': 160,\n'wc': 178,\n'wd': 138,\n'we': 10270,\n'wf': 145,\n'wg': 135,\n'wh': 7676,\n'wi': 8165,\n'wj': 154,\n'wk': 103,\n'wl': 169,\n'wm': 219,\n'wn': 137,\n'wo': 4635,\n'wp': 199,\n'wq': 78,\n'wr': 578,\n'ws': 246,\n'wt': 170,\n'wu': 306,\n'wv': 136,\n'ww': 2494,\n'wx': 193,\n'wy': 274,\n'wz': 183,\n'x-': 157,\n'x0': 8,\n'x1': 15,\n'x2': 61,\n'x3': 15,\n'x4': 2,\n'x5': 8,\n'x6': 12,\n'x7': 3,\n'x8': 5,\n'x9': 3,\n'xa': 329,\n'xb': 191,\n'xc': 220,\n'xd': 145,\n'xe': 282,\n'xf': 158,\n'xg': 136,\n'xh': 144,\n'xi': 794,\n'xj': 208,\n'xk': 79,\n'xl': 180,\n'xm': 285,\n'xn': 107,\n'xo': 163,\n'xp': 292,\n'xq': 82,\n'xr': 126,\n'xs': 195,\n'xt': 344,\n'xu': 208,\n'xv': 78,\n'xw': 84,\n'xx': 552,\n'xy': 237,\n'xz': 171,\n'y-': 45,\n'y0': 5,\n'y1': 6,\n'y2': 13,\n'y3': 2,\n'y5': 5,\n'y6': 4,\n'y7': 4,\n'y8': 3,\n'y9': 4,\n'ya': 1485,\n'yb': 102,\n'yc': 195,\n'yd': 137,\n'ye': 2320,\n'yf': 106,\n'yg': 116,\n'yh': 159,\n'yi': 568,\n'yj': 136,\n'yk': 131,\n'yl': 168,\n'ym': 174,\n'yn': 217,\n'yo': 4580,\n'yp': 214,\n'yq': 89,\n'yr': 98,\n'ys': 233,\n'yt': 248,\n'yu': 779,\n'yv': 101,\n'yw': 155,\n'yx': 142,\n'yy': 176,\n'yz': 169,\n'z-': 40,\n'z0': 4,\n'z1': 6,\n'z2': 6,\n'z3': 5,\n'z4': 1,\n'z5': 4,\n'z7': 2,\n'z8': 1,\n'z9': 3,\n'za': 920,\n'zb': 144,\n'zc': 129,\n'zd': 141,\n'ze': 1083,\n'zf': 95,\n'zg': 277,\n'zh': 651,\n'zi': 676,\n'zj': 315,\n'zk': 102,\n'zl': 176,\n'zm': 120,\n'zn': 117,\n'zo': 741,\n'zp': 107,\n'zq': 131,\n'zr': 148,\n'zs': 167,\n'zt': 102,\n'zu': 336,\n'zv': 70,\n'zw': 126,\n'zx': 108,\n'zy': 171,\n'zz': 266,\n}\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import signal import time import sdnotify n = sdnotify.SystemdNotifier() if __name__ == '__main__': n.notify("READY=1") time.sleep(2)
normal
{ "blob_id": "78dc2193c05ddb4cd4c80b1c0322890eca7fcf19", "index": 789, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n n.notify('READY=1')\n time.sleep(2)\n", "step-3": "<mask token>\nn = sdnotify.SystemdNotifier()\nif __name__ == '__main__':\n n.notify('READY=1')\n time.sleep(2)\n", "step-4": "import signal\nimport time\nimport sdnotify\nn = sdnotify.SystemdNotifier()\nif __name__ == '__main__':\n n.notify('READY=1')\n time.sleep(2)\n", "step-5": "import signal\nimport time\n\nimport sdnotify\n\nn = sdnotify.SystemdNotifier()\n\nif __name__ == '__main__':\n\n n.notify(\"READY=1\")\n time.sleep(2)\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class KaliteUI(object): def __init__(self, kaliteApp): dropdown = DropDown() dropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y= None, size=(150, 40), font_size=18, color=(0.06, 0.6, 0.2, 1), bold=True, background_color=(1, 1, 1, 0.2)) dropdown_btn.bind(on_release=dropdown.open) self.root_layout = GridLayout(cols=1) logo_holder = _BoxLayout(orientation='horizontal') logo_img = Image(source='horizontal-logo.png', size_hint_x=None, width=360) logo_holder.padding = [10, 10, 10, 10] logo_holder.add_widget(logo_img) self.content_reload_btn = Button(text='Reload Content', size_hint_x =None, size_hint_y=None, size=(150, 40), font_size=18, color=(1, 1, 1, 1), bold=True) self.content_reload_btn.bind(on_press=kaliteApp.reload_content) space_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': 0.8} ) logo_holder.add_widget(space_holder) buttons_holder = AnchorLayout(anchor_x='center', anchor_y='center') dropdown.add_widget(self.content_reload_btn) logo_holder.add_widget(dropdown_btn) logo_holder.spacing = [300, 0] self.root_layout.add_widget(logo_holder) self.img_holder = BoxLayout(orientation='vertical', size=(200, 200), size_hint=(1, None)) self.img_holder.padding = [0, 80, 0, 10] self.root_layout.add_widget(self.img_holder) self.progress_bar = ProgressBar() self.messages = BoxLayout(orientation='vertical') self.root_layout.add_widget(self.messages) self.root_layout.add_widget(buttons_holder) self.root_layout.add_widget(self.progress_bar) def disable_reload_bnt(self): self.content_reload_btn.disabled = True def get_root_Layout(self): return self.root_layout def add_messages(self, message): self.messages.add_widget(message) def remove_messages(self, message): self.messages.remove_widget(message) def add_loading_gif(self): self.gif_img = Image(source='loading.zip', anim_delay=0.15) self.img_holder.add_widget(self.gif_img) def remove_loading_gif(self): self.img_holder.remove_widget(self.gif_img) def start_progress_bar(self, anim_value): self.anim = Animation(value=anim_value, duration=3) self.anim.start(self.progress_bar) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class _BoxLayout(BoxLayout): <|reserved_special_token_0|> <|reserved_special_token_0|> class KaliteUI(object): def __init__(self, kaliteApp): dropdown = DropDown() dropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y= None, size=(150, 40), font_size=18, color=(0.06, 0.6, 0.2, 1), bold=True, background_color=(1, 1, 1, 0.2)) dropdown_btn.bind(on_release=dropdown.open) self.root_layout = GridLayout(cols=1) logo_holder = _BoxLayout(orientation='horizontal') logo_img = Image(source='horizontal-logo.png', size_hint_x=None, width=360) logo_holder.padding = [10, 10, 10, 10] logo_holder.add_widget(logo_img) self.content_reload_btn = Button(text='Reload Content', size_hint_x =None, size_hint_y=None, size=(150, 40), font_size=18, color=(1, 1, 1, 1), bold=True) self.content_reload_btn.bind(on_press=kaliteApp.reload_content) space_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': 0.8} ) logo_holder.add_widget(space_holder) buttons_holder = AnchorLayout(anchor_x='center', anchor_y='center') dropdown.add_widget(self.content_reload_btn) logo_holder.add_widget(dropdown_btn) logo_holder.spacing = [300, 0] self.root_layout.add_widget(logo_holder) self.img_holder = BoxLayout(orientation='vertical', size=(200, 200), size_hint=(1, None)) self.img_holder.padding = [0, 80, 0, 10] self.root_layout.add_widget(self.img_holder) self.progress_bar = ProgressBar() self.messages = BoxLayout(orientation='vertical') self.root_layout.add_widget(self.messages) self.root_layout.add_widget(buttons_holder) self.root_layout.add_widget(self.progress_bar) def disable_reload_bnt(self): self.content_reload_btn.disabled = True def get_root_Layout(self): return self.root_layout def add_messages(self, message): self.messages.add_widget(message) def remove_messages(self, message): self.messages.remove_widget(message) def add_loading_gif(self): self.gif_img = Image(source='loading.zip', anim_delay=0.15) self.img_holder.add_widget(self.gif_img) def remove_loading_gif(self): self.img_holder.remove_widget(self.gif_img) def start_progress_bar(self, anim_value): self.anim = Animation(value=anim_value, duration=3) self.anim.start(self.progress_bar) def animation_bind(self, bindFunction): self.anim.bind(on_complete=bindFunction) <|reserved_special_token_1|> <|reserved_special_token_0|> Window.clearcolor = 1, 1, 1, 1 class _BoxLayout(BoxLayout): def __init__(self, **kwargs): super(_BoxLayout, self).__init__(**kwargs) with self.canvas.before: Color(0.878, 0.941, 0.784) self.rect = Rectangle(size=self.size, pos=self.pos) self.bind(size=self._update_rect, pos=self._update_rect) def _update_rect(self, instance, value): self.rect.pos = instance.pos self.rect.size = instance.size class KaliteUI(object): def __init__(self, kaliteApp): dropdown = DropDown() dropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y= None, size=(150, 40), font_size=18, color=(0.06, 0.6, 0.2, 1), bold=True, background_color=(1, 1, 1, 0.2)) dropdown_btn.bind(on_release=dropdown.open) self.root_layout = GridLayout(cols=1) logo_holder = _BoxLayout(orientation='horizontal') logo_img = Image(source='horizontal-logo.png', size_hint_x=None, width=360) logo_holder.padding = [10, 10, 10, 10] logo_holder.add_widget(logo_img) self.content_reload_btn = Button(text='Reload Content', size_hint_x =None, size_hint_y=None, size=(150, 40), font_size=18, color=(1, 1, 1, 1), bold=True) self.content_reload_btn.bind(on_press=kaliteApp.reload_content) space_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': 0.8} ) logo_holder.add_widget(space_holder) buttons_holder = AnchorLayout(anchor_x='center', anchor_y='center') dropdown.add_widget(self.content_reload_btn) logo_holder.add_widget(dropdown_btn) logo_holder.spacing = [300, 0] self.root_layout.add_widget(logo_holder) self.img_holder = BoxLayout(orientation='vertical', size=(200, 200), size_hint=(1, None)) self.img_holder.padding = [0, 80, 0, 10] self.root_layout.add_widget(self.img_holder) self.progress_bar = ProgressBar() self.messages = BoxLayout(orientation='vertical') self.root_layout.add_widget(self.messages) self.root_layout.add_widget(buttons_holder) self.root_layout.add_widget(self.progress_bar) def disable_reload_bnt(self): self.content_reload_btn.disabled = True def get_root_Layout(self): return self.root_layout def add_messages(self, message): self.messages.add_widget(message) def remove_messages(self, message): self.messages.remove_widget(message) def add_loading_gif(self): self.gif_img = Image(source='loading.zip', anim_delay=0.15) self.img_holder.add_widget(self.gif_img) def remove_loading_gif(self): self.img_holder.remove_widget(self.gif_img) def start_progress_bar(self, anim_value): self.anim = Animation(value=anim_value, duration=3) self.anim.start(self.progress_bar) def animation_bind(self, bindFunction): self.anim.bind(on_complete=bindFunction) <|reserved_special_token_1|> from kivy.uix.progressbar import ProgressBar from kivy.animation import Animation from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.image import Image from kivy.graphics import Color, Rectangle from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.gridlayout import GridLayout from kivy.core.window import Window from kivy.uix.dropdown import DropDown Window.clearcolor = 1, 1, 1, 1 class _BoxLayout(BoxLayout): def __init__(self, **kwargs): super(_BoxLayout, self).__init__(**kwargs) with self.canvas.before: Color(0.878, 0.941, 0.784) self.rect = Rectangle(size=self.size, pos=self.pos) self.bind(size=self._update_rect, pos=self._update_rect) def _update_rect(self, instance, value): self.rect.pos = instance.pos self.rect.size = instance.size class KaliteUI(object): def __init__(self, kaliteApp): dropdown = DropDown() dropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y= None, size=(150, 40), font_size=18, color=(0.06, 0.6, 0.2, 1), bold=True, background_color=(1, 1, 1, 0.2)) dropdown_btn.bind(on_release=dropdown.open) self.root_layout = GridLayout(cols=1) logo_holder = _BoxLayout(orientation='horizontal') logo_img = Image(source='horizontal-logo.png', size_hint_x=None, width=360) logo_holder.padding = [10, 10, 10, 10] logo_holder.add_widget(logo_img) self.content_reload_btn = Button(text='Reload Content', size_hint_x =None, size_hint_y=None, size=(150, 40), font_size=18, color=(1, 1, 1, 1), bold=True) self.content_reload_btn.bind(on_press=kaliteApp.reload_content) space_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': 0.8} ) logo_holder.add_widget(space_holder) buttons_holder = AnchorLayout(anchor_x='center', anchor_y='center') dropdown.add_widget(self.content_reload_btn) logo_holder.add_widget(dropdown_btn) logo_holder.spacing = [300, 0] self.root_layout.add_widget(logo_holder) self.img_holder = BoxLayout(orientation='vertical', size=(200, 200), size_hint=(1, None)) self.img_holder.padding = [0, 80, 0, 10] self.root_layout.add_widget(self.img_holder) self.progress_bar = ProgressBar() self.messages = BoxLayout(orientation='vertical') self.root_layout.add_widget(self.messages) self.root_layout.add_widget(buttons_holder) self.root_layout.add_widget(self.progress_bar) def disable_reload_bnt(self): self.content_reload_btn.disabled = True def get_root_Layout(self): return self.root_layout def add_messages(self, message): self.messages.add_widget(message) def remove_messages(self, message): self.messages.remove_widget(message) def add_loading_gif(self): self.gif_img = Image(source='loading.zip', anim_delay=0.15) self.img_holder.add_widget(self.gif_img) def remove_loading_gif(self): self.img_holder.remove_widget(self.gif_img) def start_progress_bar(self, anim_value): self.anim = Animation(value=anim_value, duration=3) self.anim.start(self.progress_bar) def animation_bind(self, bindFunction): self.anim.bind(on_complete=bindFunction) <|reserved_special_token_1|> from kivy.uix.progressbar import ProgressBar from kivy.animation import Animation from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.image import Image from kivy.graphics import Color, Rectangle from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.gridlayout import GridLayout from kivy.core.window import Window from kivy.uix.dropdown import DropDown Window.clearcolor = (1, 1, 1, 1) class _BoxLayout(BoxLayout): def __init__(self, **kwargs): super(_BoxLayout, self).__init__(**kwargs) with self.canvas.before: Color(0.878, 0.941, 0.784) self.rect = Rectangle(size=self.size, pos=self.pos) self.bind(size=self._update_rect, pos=self._update_rect) def _update_rect(self, instance, value): self.rect.pos = instance.pos self.rect.size = instance.size class KaliteUI(object): def __init__(self, kaliteApp): dropdown = DropDown() dropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y=None, size=(150, 40), font_size=18 , color=(.06, .6, .2, 1), bold=True, background_color=(1, 1, 1, 0.2)) dropdown_btn.bind(on_release=dropdown.open) self.root_layout = GridLayout(cols=1) logo_holder = _BoxLayout(orientation='horizontal') logo_img = Image(source='horizontal-logo.png', size_hint_x=None, width=360) logo_holder.padding = [10,10,10,10] logo_holder.add_widget(logo_img) self.content_reload_btn= Button(text='Reload Content', size_hint_x=None, size_hint_y=None, size=(150, 40), font_size=18 , color=(1, 1, 1, 1), bold=True) self.content_reload_btn.bind(on_press=kaliteApp.reload_content) space_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': .8}) logo_holder.add_widget(space_holder) buttons_holder = AnchorLayout(anchor_x='center', anchor_y='center') dropdown.add_widget(self.content_reload_btn) logo_holder.add_widget(dropdown_btn) logo_holder.spacing = [300, 0] self.root_layout.add_widget(logo_holder) self.img_holder = BoxLayout(orientation='vertical', size=(200,200), size_hint=(1, None)) self.img_holder.padding = [0,80,0,10] self.root_layout.add_widget(self.img_holder) self.progress_bar = ProgressBar() self.messages = BoxLayout(orientation='vertical') self.root_layout.add_widget(self.messages) self.root_layout.add_widget(buttons_holder) self.root_layout.add_widget(self.progress_bar) def disable_reload_bnt(self): self.content_reload_btn.disabled = True def get_root_Layout(self): return self.root_layout def add_messages(self, message): self.messages.add_widget(message) def remove_messages(self, message): self.messages.remove_widget(message) def add_loading_gif(self): self.gif_img = Image(source='loading.zip', anim_delay = 0.15) self.img_holder.add_widget(self.gif_img) def remove_loading_gif(self): self.img_holder.remove_widget(self.gif_img) def start_progress_bar(self, anim_value): self.anim = Animation(value = anim_value, duration = 3) self.anim.start(self.progress_bar) def animation_bind(self, bindFunction): self.anim.bind(on_complete = bindFunction)
flexible
{ "blob_id": "35cd1c45294b826784eab9885ec5b0132624c957", "index": 4028, "step-1": "<mask token>\n\n\nclass KaliteUI(object):\n\n def __init__(self, kaliteApp):\n dropdown = DropDown()\n dropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y=\n None, size=(150, 40), font_size=18, color=(0.06, 0.6, 0.2, 1),\n bold=True, background_color=(1, 1, 1, 0.2))\n dropdown_btn.bind(on_release=dropdown.open)\n self.root_layout = GridLayout(cols=1)\n logo_holder = _BoxLayout(orientation='horizontal')\n logo_img = Image(source='horizontal-logo.png', size_hint_x=None,\n width=360)\n logo_holder.padding = [10, 10, 10, 10]\n logo_holder.add_widget(logo_img)\n self.content_reload_btn = Button(text='Reload Content', size_hint_x\n =None, size_hint_y=None, size=(150, 40), font_size=18, color=(1,\n 1, 1, 1), bold=True)\n self.content_reload_btn.bind(on_press=kaliteApp.reload_content)\n space_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': 0.8}\n )\n logo_holder.add_widget(space_holder)\n buttons_holder = AnchorLayout(anchor_x='center', anchor_y='center')\n dropdown.add_widget(self.content_reload_btn)\n logo_holder.add_widget(dropdown_btn)\n logo_holder.spacing = [300, 0]\n self.root_layout.add_widget(logo_holder)\n self.img_holder = BoxLayout(orientation='vertical', size=(200, 200),\n size_hint=(1, None))\n self.img_holder.padding = [0, 80, 0, 10]\n self.root_layout.add_widget(self.img_holder)\n self.progress_bar = ProgressBar()\n self.messages = BoxLayout(orientation='vertical')\n self.root_layout.add_widget(self.messages)\n self.root_layout.add_widget(buttons_holder)\n self.root_layout.add_widget(self.progress_bar)\n\n def disable_reload_bnt(self):\n self.content_reload_btn.disabled = True\n\n def get_root_Layout(self):\n return self.root_layout\n\n def add_messages(self, message):\n self.messages.add_widget(message)\n\n def remove_messages(self, message):\n self.messages.remove_widget(message)\n\n def add_loading_gif(self):\n self.gif_img = Image(source='loading.zip', anim_delay=0.15)\n self.img_holder.add_widget(self.gif_img)\n\n def remove_loading_gif(self):\n self.img_holder.remove_widget(self.gif_img)\n\n def start_progress_bar(self, anim_value):\n self.anim = Animation(value=anim_value, duration=3)\n self.anim.start(self.progress_bar)\n <mask token>\n", "step-2": "<mask token>\n\n\nclass _BoxLayout(BoxLayout):\n <mask token>\n <mask token>\n\n\nclass KaliteUI(object):\n\n def __init__(self, kaliteApp):\n dropdown = DropDown()\n dropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y=\n None, size=(150, 40), font_size=18, color=(0.06, 0.6, 0.2, 1),\n bold=True, background_color=(1, 1, 1, 0.2))\n dropdown_btn.bind(on_release=dropdown.open)\n self.root_layout = GridLayout(cols=1)\n logo_holder = _BoxLayout(orientation='horizontal')\n logo_img = Image(source='horizontal-logo.png', size_hint_x=None,\n width=360)\n logo_holder.padding = [10, 10, 10, 10]\n logo_holder.add_widget(logo_img)\n self.content_reload_btn = Button(text='Reload Content', size_hint_x\n =None, size_hint_y=None, size=(150, 40), font_size=18, color=(1,\n 1, 1, 1), bold=True)\n self.content_reload_btn.bind(on_press=kaliteApp.reload_content)\n space_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': 0.8}\n )\n logo_holder.add_widget(space_holder)\n buttons_holder = AnchorLayout(anchor_x='center', anchor_y='center')\n dropdown.add_widget(self.content_reload_btn)\n logo_holder.add_widget(dropdown_btn)\n logo_holder.spacing = [300, 0]\n self.root_layout.add_widget(logo_holder)\n self.img_holder = BoxLayout(orientation='vertical', size=(200, 200),\n size_hint=(1, None))\n self.img_holder.padding = [0, 80, 0, 10]\n self.root_layout.add_widget(self.img_holder)\n self.progress_bar = ProgressBar()\n self.messages = BoxLayout(orientation='vertical')\n self.root_layout.add_widget(self.messages)\n self.root_layout.add_widget(buttons_holder)\n self.root_layout.add_widget(self.progress_bar)\n\n def disable_reload_bnt(self):\n self.content_reload_btn.disabled = True\n\n def get_root_Layout(self):\n return self.root_layout\n\n def add_messages(self, message):\n self.messages.add_widget(message)\n\n def remove_messages(self, message):\n self.messages.remove_widget(message)\n\n def add_loading_gif(self):\n self.gif_img = Image(source='loading.zip', anim_delay=0.15)\n self.img_holder.add_widget(self.gif_img)\n\n def remove_loading_gif(self):\n self.img_holder.remove_widget(self.gif_img)\n\n def start_progress_bar(self, anim_value):\n self.anim = Animation(value=anim_value, duration=3)\n self.anim.start(self.progress_bar)\n\n def animation_bind(self, bindFunction):\n self.anim.bind(on_complete=bindFunction)\n", "step-3": "<mask token>\nWindow.clearcolor = 1, 1, 1, 1\n\n\nclass _BoxLayout(BoxLayout):\n\n def __init__(self, **kwargs):\n super(_BoxLayout, self).__init__(**kwargs)\n with self.canvas.before:\n Color(0.878, 0.941, 0.784)\n self.rect = Rectangle(size=self.size, pos=self.pos)\n self.bind(size=self._update_rect, pos=self._update_rect)\n\n def _update_rect(self, instance, value):\n self.rect.pos = instance.pos\n self.rect.size = instance.size\n\n\nclass KaliteUI(object):\n\n def __init__(self, kaliteApp):\n dropdown = DropDown()\n dropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y=\n None, size=(150, 40), font_size=18, color=(0.06, 0.6, 0.2, 1),\n bold=True, background_color=(1, 1, 1, 0.2))\n dropdown_btn.bind(on_release=dropdown.open)\n self.root_layout = GridLayout(cols=1)\n logo_holder = _BoxLayout(orientation='horizontal')\n logo_img = Image(source='horizontal-logo.png', size_hint_x=None,\n width=360)\n logo_holder.padding = [10, 10, 10, 10]\n logo_holder.add_widget(logo_img)\n self.content_reload_btn = Button(text='Reload Content', size_hint_x\n =None, size_hint_y=None, size=(150, 40), font_size=18, color=(1,\n 1, 1, 1), bold=True)\n self.content_reload_btn.bind(on_press=kaliteApp.reload_content)\n space_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': 0.8}\n )\n logo_holder.add_widget(space_holder)\n buttons_holder = AnchorLayout(anchor_x='center', anchor_y='center')\n dropdown.add_widget(self.content_reload_btn)\n logo_holder.add_widget(dropdown_btn)\n logo_holder.spacing = [300, 0]\n self.root_layout.add_widget(logo_holder)\n self.img_holder = BoxLayout(orientation='vertical', size=(200, 200),\n size_hint=(1, None))\n self.img_holder.padding = [0, 80, 0, 10]\n self.root_layout.add_widget(self.img_holder)\n self.progress_bar = ProgressBar()\n self.messages = BoxLayout(orientation='vertical')\n self.root_layout.add_widget(self.messages)\n self.root_layout.add_widget(buttons_holder)\n self.root_layout.add_widget(self.progress_bar)\n\n def disable_reload_bnt(self):\n self.content_reload_btn.disabled = True\n\n def get_root_Layout(self):\n return self.root_layout\n\n def add_messages(self, message):\n self.messages.add_widget(message)\n\n def remove_messages(self, message):\n self.messages.remove_widget(message)\n\n def add_loading_gif(self):\n self.gif_img = Image(source='loading.zip', anim_delay=0.15)\n self.img_holder.add_widget(self.gif_img)\n\n def remove_loading_gif(self):\n self.img_holder.remove_widget(self.gif_img)\n\n def start_progress_bar(self, anim_value):\n self.anim = Animation(value=anim_value, duration=3)\n self.anim.start(self.progress_bar)\n\n def animation_bind(self, bindFunction):\n self.anim.bind(on_complete=bindFunction)\n", "step-4": "from kivy.uix.progressbar import ProgressBar\nfrom kivy.animation import Animation\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.button import Button\nfrom kivy.uix.image import Image\nfrom kivy.graphics import Color, Rectangle\nfrom kivy.core.window import Window\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.anchorlayout import AnchorLayout\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.core.window import Window\nfrom kivy.uix.dropdown import DropDown\nWindow.clearcolor = 1, 1, 1, 1\n\n\nclass _BoxLayout(BoxLayout):\n\n def __init__(self, **kwargs):\n super(_BoxLayout, self).__init__(**kwargs)\n with self.canvas.before:\n Color(0.878, 0.941, 0.784)\n self.rect = Rectangle(size=self.size, pos=self.pos)\n self.bind(size=self._update_rect, pos=self._update_rect)\n\n def _update_rect(self, instance, value):\n self.rect.pos = instance.pos\n self.rect.size = instance.size\n\n\nclass KaliteUI(object):\n\n def __init__(self, kaliteApp):\n dropdown = DropDown()\n dropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y=\n None, size=(150, 40), font_size=18, color=(0.06, 0.6, 0.2, 1),\n bold=True, background_color=(1, 1, 1, 0.2))\n dropdown_btn.bind(on_release=dropdown.open)\n self.root_layout = GridLayout(cols=1)\n logo_holder = _BoxLayout(orientation='horizontal')\n logo_img = Image(source='horizontal-logo.png', size_hint_x=None,\n width=360)\n logo_holder.padding = [10, 10, 10, 10]\n logo_holder.add_widget(logo_img)\n self.content_reload_btn = Button(text='Reload Content', size_hint_x\n =None, size_hint_y=None, size=(150, 40), font_size=18, color=(1,\n 1, 1, 1), bold=True)\n self.content_reload_btn.bind(on_press=kaliteApp.reload_content)\n space_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': 0.8}\n )\n logo_holder.add_widget(space_holder)\n buttons_holder = AnchorLayout(anchor_x='center', anchor_y='center')\n dropdown.add_widget(self.content_reload_btn)\n logo_holder.add_widget(dropdown_btn)\n logo_holder.spacing = [300, 0]\n self.root_layout.add_widget(logo_holder)\n self.img_holder = BoxLayout(orientation='vertical', size=(200, 200),\n size_hint=(1, None))\n self.img_holder.padding = [0, 80, 0, 10]\n self.root_layout.add_widget(self.img_holder)\n self.progress_bar = ProgressBar()\n self.messages = BoxLayout(orientation='vertical')\n self.root_layout.add_widget(self.messages)\n self.root_layout.add_widget(buttons_holder)\n self.root_layout.add_widget(self.progress_bar)\n\n def disable_reload_bnt(self):\n self.content_reload_btn.disabled = True\n\n def get_root_Layout(self):\n return self.root_layout\n\n def add_messages(self, message):\n self.messages.add_widget(message)\n\n def remove_messages(self, message):\n self.messages.remove_widget(message)\n\n def add_loading_gif(self):\n self.gif_img = Image(source='loading.zip', anim_delay=0.15)\n self.img_holder.add_widget(self.gif_img)\n\n def remove_loading_gif(self):\n self.img_holder.remove_widget(self.gif_img)\n\n def start_progress_bar(self, anim_value):\n self.anim = Animation(value=anim_value, duration=3)\n self.anim.start(self.progress_bar)\n\n def animation_bind(self, bindFunction):\n self.anim.bind(on_complete=bindFunction)\n", "step-5": "from kivy.uix.progressbar import ProgressBar\nfrom kivy.animation import Animation\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.button import Button\nfrom kivy.uix.image import Image\nfrom kivy.graphics import Color, Rectangle\nfrom kivy.core.window import Window\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.anchorlayout import AnchorLayout\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.core.window import Window\nfrom kivy.uix.dropdown import DropDown\nWindow.clearcolor = (1, 1, 1, 1)\n\nclass _BoxLayout(BoxLayout):\n\tdef __init__(self, **kwargs):\n\t\tsuper(_BoxLayout, self).__init__(**kwargs)\n\t\twith self.canvas.before:\n\t\t Color(0.878, 0.941, 0.784)\n\t\t self.rect = Rectangle(size=self.size, pos=self.pos)\n\t\tself.bind(size=self._update_rect, pos=self._update_rect)\n\n\tdef _update_rect(self, instance, value):\n\t\tself.rect.pos = instance.pos\n\t\tself.rect.size = instance.size\n\nclass KaliteUI(object):\n\tdef __init__(self, kaliteApp):\n\t\tdropdown = DropDown()\n\t\tdropdown_btn = Button(text='menu', size_hint_x=None, size_hint_y=None, size=(150, 40), font_size=18\n\t\t , color=(.06, .6, .2, 1), bold=True, background_color=(1, 1, 1, 0.2))\n\t\tdropdown_btn.bind(on_release=dropdown.open)\n\n\t\tself.root_layout = GridLayout(cols=1)\n\t\tlogo_holder = _BoxLayout(orientation='horizontal')\n\t\tlogo_img = Image(source='horizontal-logo.png', size_hint_x=None, width=360)\n\n\t\tlogo_holder.padding = [10,10,10,10]\n\t\tlogo_holder.add_widget(logo_img)\n\n\t\tself.content_reload_btn= Button(text='Reload Content', size_hint_x=None, size_hint_y=None, size=(150, 40), font_size=18\n\t\t , color=(1, 1, 1, 1), bold=True)\n\n\t\tself.content_reload_btn.bind(on_press=kaliteApp.reload_content)\n\t\tspace_holder = _BoxLayout(orientation='horizontal', pos_hint={'x': .8})\n\t\tlogo_holder.add_widget(space_holder)\n\n\t\tbuttons_holder = AnchorLayout(anchor_x='center', anchor_y='center')\n\n\t\tdropdown.add_widget(self.content_reload_btn)\n\t\tlogo_holder.add_widget(dropdown_btn)\n\t\tlogo_holder.spacing = [300, 0]\n\t\tself.root_layout.add_widget(logo_holder)\n\n\t\tself.img_holder = BoxLayout(orientation='vertical', size=(200,200), size_hint=(1, None))\n\t\tself.img_holder.padding = [0,80,0,10]\n\t\tself.root_layout.add_widget(self.img_holder)\n\n\t\tself.progress_bar = ProgressBar()\n\n\t\tself.messages = BoxLayout(orientation='vertical')\n\n\t\tself.root_layout.add_widget(self.messages)\n\t\tself.root_layout.add_widget(buttons_holder)\n\t\tself.root_layout.add_widget(self.progress_bar)\n\n\tdef disable_reload_bnt(self):\n\t\tself.content_reload_btn.disabled = True\n\n\tdef get_root_Layout(self):\n\t\treturn self.root_layout\n\n\tdef add_messages(self, message):\n\t\tself.messages.add_widget(message)\n\n\tdef remove_messages(self, message):\n\t\tself.messages.remove_widget(message)\n\n\tdef add_loading_gif(self):\n\t\tself.gif_img = Image(source='loading.zip', anim_delay = 0.15)\n\t\tself.img_holder.add_widget(self.gif_img)\n\n\tdef remove_loading_gif(self):\n\t\tself.img_holder.remove_widget(self.gif_img)\n\n\tdef start_progress_bar(self, anim_value):\n\t\tself.anim = Animation(value = anim_value, duration = 3)\n\t\tself.anim.start(self.progress_bar)\n\n\tdef animation_bind(self, bindFunction):\n\t\tself.anim.bind(on_complete = bindFunction)\n\n\n", "step-ids": [ 9, 11, 14, 15, 16 ] }
[ 9, 11, 14, 15, 16 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get(url): return requests.get(url).text <|reserved_special_token_1|> import requests def get(url): return requests.get(url).text
flexible
{ "blob_id": "671ecf23df1da659d186014afa738d0608ad404d", "index": 9251, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get(url):\n return requests.get(url).text\n", "step-3": "import requests\n\n\ndef get(url):\n return requests.get(url).text\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
# Testing import sys, os sys.dont_write_bytecode = True import argparse, socket from requestframe import RequestFrame if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--header-mutate-level", type=int, choices=range(11), nargs='?', help="Set the mutation level for the headers (0-10). Default = 5", default=5) parser.add_argument("--body-mutate-level", type=int, choices=range(11), nargs='?', help="Set the mutation level for the body (0-10). Default = 5", default=5) parser.add_argument("--request-mutate-level", type=int, choices=range(11), nargs='?', help="Set the mutation level for the request line (0-10). Default = 5", default=5) parser.add_argument("--body-type", type=str, choices=['json', 'junk', 'rand'], help="Set the data generated in the request body. Default = rand", default='rand') parser.add_argument("--num-headers", type=int, help="Sets the maximum number of headers. Default = number of available headers", default=-1) parser.add_argument("--generate-num", type=int, help="Number of requests to generate. Any more than 1 generated request will output to a new folder called output/. Default = 1", default=1) parser.add_argument('-v', '--version', action='version', version='HTTPFuzz Version: 1.0.1') args = parser.parse_args() if args.generate_num > 1: try: os.mkdir("output") for i in range(args.generate_num): with open("output/{}.txt".format(i + 1), 'w') as f: request_frame = RequestFrame(args) request_frame.generate() f.write(request_frame.request) print("[+] Wrote request to /output/{}.txt".format(i + 1)) exit("[+] Finished creating requests") except: exit("[-] Couldn't make the output directory. It might already exist.") request_frame = RequestFrame(args) request_frame.generate() exit(request_frame.request)
normal
{ "blob_id": "350a79d6cead6814ad48292b14a204e753dc938c", "index": 4363, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--header-mutate-level', type=int, choices=range(11\n ), nargs='?', help=\n 'Set the mutation level for the headers (0-10). Default = 5', default=5\n )\n parser.add_argument('--body-mutate-level', type=int, choices=range(11),\n nargs='?', help=\n 'Set the mutation level for the body (0-10). Default = 5', default=5)\n parser.add_argument('--request-mutate-level', type=int, choices=range(\n 11), nargs='?', help=\n 'Set the mutation level for the request line (0-10). Default = 5',\n default=5)\n parser.add_argument('--body-type', type=str, choices=['json', 'junk',\n 'rand'], help=\n 'Set the data generated in the request body. Default = rand',\n default='rand')\n parser.add_argument('--num-headers', type=int, help=\n 'Sets the maximum number of headers. Default = number of available headers'\n , default=-1)\n parser.add_argument('--generate-num', type=int, help=\n 'Number of requests to generate. Any more than 1 generated request will output to a new folder called output/. Default = 1'\n , default=1)\n parser.add_argument('-v', '--version', action='version', version=\n 'HTTPFuzz Version: 1.0.1')\n args = parser.parse_args()\n if args.generate_num > 1:\n try:\n os.mkdir('output')\n for i in range(args.generate_num):\n with open('output/{}.txt'.format(i + 1), 'w') as f:\n request_frame = RequestFrame(args)\n request_frame.generate()\n f.write(request_frame.request)\n print('[+] Wrote request to /output/{}.txt'.format(i + 1))\n exit('[+] Finished creating requests')\n except:\n exit(\n \"[-] Couldn't make the output directory. It might already exist.\"\n )\n request_frame = RequestFrame(args)\n request_frame.generate()\n exit(request_frame.request)\n", "step-3": "<mask token>\nsys.dont_write_bytecode = True\n<mask token>\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--header-mutate-level', type=int, choices=range(11\n ), nargs='?', help=\n 'Set the mutation level for the headers (0-10). Default = 5', default=5\n )\n parser.add_argument('--body-mutate-level', type=int, choices=range(11),\n nargs='?', help=\n 'Set the mutation level for the body (0-10). Default = 5', default=5)\n parser.add_argument('--request-mutate-level', type=int, choices=range(\n 11), nargs='?', help=\n 'Set the mutation level for the request line (0-10). Default = 5',\n default=5)\n parser.add_argument('--body-type', type=str, choices=['json', 'junk',\n 'rand'], help=\n 'Set the data generated in the request body. Default = rand',\n default='rand')\n parser.add_argument('--num-headers', type=int, help=\n 'Sets the maximum number of headers. Default = number of available headers'\n , default=-1)\n parser.add_argument('--generate-num', type=int, help=\n 'Number of requests to generate. Any more than 1 generated request will output to a new folder called output/. Default = 1'\n , default=1)\n parser.add_argument('-v', '--version', action='version', version=\n 'HTTPFuzz Version: 1.0.1')\n args = parser.parse_args()\n if args.generate_num > 1:\n try:\n os.mkdir('output')\n for i in range(args.generate_num):\n with open('output/{}.txt'.format(i + 1), 'w') as f:\n request_frame = RequestFrame(args)\n request_frame.generate()\n f.write(request_frame.request)\n print('[+] Wrote request to /output/{}.txt'.format(i + 1))\n exit('[+] Finished creating requests')\n except:\n exit(\n \"[-] Couldn't make the output directory. It might already exist.\"\n )\n request_frame = RequestFrame(args)\n request_frame.generate()\n exit(request_frame.request)\n", "step-4": "import sys, os\nsys.dont_write_bytecode = True\nimport argparse, socket\nfrom requestframe import RequestFrame\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--header-mutate-level', type=int, choices=range(11\n ), nargs='?', help=\n 'Set the mutation level for the headers (0-10). Default = 5', default=5\n )\n parser.add_argument('--body-mutate-level', type=int, choices=range(11),\n nargs='?', help=\n 'Set the mutation level for the body (0-10). Default = 5', default=5)\n parser.add_argument('--request-mutate-level', type=int, choices=range(\n 11), nargs='?', help=\n 'Set the mutation level for the request line (0-10). Default = 5',\n default=5)\n parser.add_argument('--body-type', type=str, choices=['json', 'junk',\n 'rand'], help=\n 'Set the data generated in the request body. Default = rand',\n default='rand')\n parser.add_argument('--num-headers', type=int, help=\n 'Sets the maximum number of headers. Default = number of available headers'\n , default=-1)\n parser.add_argument('--generate-num', type=int, help=\n 'Number of requests to generate. Any more than 1 generated request will output to a new folder called output/. Default = 1'\n , default=1)\n parser.add_argument('-v', '--version', action='version', version=\n 'HTTPFuzz Version: 1.0.1')\n args = parser.parse_args()\n if args.generate_num > 1:\n try:\n os.mkdir('output')\n for i in range(args.generate_num):\n with open('output/{}.txt'.format(i + 1), 'w') as f:\n request_frame = RequestFrame(args)\n request_frame.generate()\n f.write(request_frame.request)\n print('[+] Wrote request to /output/{}.txt'.format(i + 1))\n exit('[+] Finished creating requests')\n except:\n exit(\n \"[-] Couldn't make the output directory. It might already exist.\"\n )\n request_frame = RequestFrame(args)\n request_frame.generate()\n exit(request_frame.request)\n", "step-5": "# Testing\nimport sys, os\nsys.dont_write_bytecode = True\n\nimport argparse, socket\nfrom requestframe import RequestFrame\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--header-mutate-level\", type=int, choices=range(11), nargs='?', help=\"Set the mutation level for the headers (0-10). Default = 5\", default=5)\n parser.add_argument(\"--body-mutate-level\", type=int, choices=range(11), nargs='?', help=\"Set the mutation level for the body (0-10). Default = 5\", default=5)\n parser.add_argument(\"--request-mutate-level\", type=int, choices=range(11), nargs='?', help=\"Set the mutation level for the request line (0-10). Default = 5\", default=5)\n parser.add_argument(\"--body-type\", type=str, choices=['json', 'junk', 'rand'], help=\"Set the data generated in the request body. Default = rand\", default='rand')\n parser.add_argument(\"--num-headers\", type=int, help=\"Sets the maximum number of headers. Default = number of available headers\", default=-1)\n parser.add_argument(\"--generate-num\", type=int, help=\"Number of requests to generate. Any more than 1 generated request will output to a new folder called output/. Default = 1\", default=1)\n parser.add_argument('-v', '--version', action='version', version='HTTPFuzz Version: 1.0.1')\n args = parser.parse_args()\n if args.generate_num > 1:\n try:\n os.mkdir(\"output\")\n for i in range(args.generate_num):\n with open(\"output/{}.txt\".format(i + 1), 'w') as f:\n request_frame = RequestFrame(args)\n request_frame.generate()\n f.write(request_frame.request)\n print(\"[+] Wrote request to /output/{}.txt\".format(i + 1))\n exit(\"[+] Finished creating requests\")\n except:\n exit(\"[-] Couldn't make the output directory. It might already exist.\")\n request_frame = RequestFrame(args)\n request_frame.generate()\n exit(request_frame.request)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def main(): str1 = 'パトカー' str2 = 'タクシー' print(''.join([(x[0] + x[1]) for x in zip(str1, str2)])) <|reserved_special_token_0|> <|reserved_special_token_1|> def question(): print('02. 「パトカー」+「タクシー」=「パタトクカシーー」') print('「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.') def main(): str1 = 'パトカー' str2 = 'タクシー' print(''.join([(x[0] + x[1]) for x in zip(str1, str2)])) <|reserved_special_token_0|> <|reserved_special_token_1|> def question(): print('02. 「パトカー」+「タクシー」=「パタトクカシーー」') print('「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.') def main(): str1 = 'パトカー' str2 = 'タクシー' print(''.join([(x[0] + x[1]) for x in zip(str1, str2)])) if __name__ == '__main__': question() main() <|reserved_special_token_1|> #!/usr/bin/env python def question(): print("02. 「パトカー」+「タクシー」=「パタトクカシーー」") print("「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.") def main(): str1 = "パトカー" str2 = "タクシー" print(''.join([x[0] + x[1] for x in zip(str1, str2)])) if __name__ == '__main__': question() main()
flexible
{ "blob_id": "32869a88bb59d47281249b6ebe2357328beb0359", "index": 3572, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n str1 = 'パトカー'\n str2 = 'タクシー'\n print(''.join([(x[0] + x[1]) for x in zip(str1, str2)]))\n\n\n<mask token>\n", "step-3": "def question():\n print('02. 「パトカー」+「タクシー」=「パタトクカシーー」')\n print('「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.')\n\n\ndef main():\n str1 = 'パトカー'\n str2 = 'タクシー'\n print(''.join([(x[0] + x[1]) for x in zip(str1, str2)]))\n\n\n<mask token>\n", "step-4": "def question():\n print('02. 「パトカー」+「タクシー」=「パタトクカシーー」')\n print('「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.')\n\n\ndef main():\n str1 = 'パトカー'\n str2 = 'タクシー'\n print(''.join([(x[0] + x[1]) for x in zip(str1, str2)]))\n\n\nif __name__ == '__main__':\n question()\n main()\n", "step-5": "#!/usr/bin/env python\n\ndef question():\n print(\"02. 「パトカー」+「タクシー」=「パタトクカシーー」\")\n print(\"「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.\")\n\ndef main():\n str1 = \"パトカー\"\n str2 = \"タクシー\"\n print(''.join([x[0] + x[1] for x in zip(str1, str2)]))\n\nif __name__ == '__main__':\n question()\n main()\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class Lenet(nn.Module): <|reserved_special_token_0|> def forward(self, x): layer_w = self.fc2.weight sigma = layer_w.std().data.cpu().numpy() layer_w_numpy = layer_w.data.cpu().numpy() scale = 0.17 noise = np.random.normal(0, scale * sigma, layer_w.size()) w_noise = np.add(layer_w_numpy, noise) w_noise_tensor = torch.tensor(w_noise) w_noise_tensor = w_noise_tensor.to('cuda') w_noise = torch.nn.Parameter(w_noise_tensor.float()) self.fc2.weight = w_noise x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 800) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return x <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Lenet(nn.Module): def __init__(self): super(Lenet, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(20, 50, 5) self.fc1 = nn.Linear(800, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): layer_w = self.fc2.weight sigma = layer_w.std().data.cpu().numpy() layer_w_numpy = layer_w.data.cpu().numpy() scale = 0.17 noise = np.random.normal(0, scale * sigma, layer_w.size()) w_noise = np.add(layer_w_numpy, noise) w_noise_tensor = torch.tensor(w_noise) w_noise_tensor = w_noise_tensor.to('cuda') w_noise = torch.nn.Parameter(w_noise_tensor.float()) self.fc2.weight = w_noise x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 800) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return x def lenet_mnist(): model = Lenet() return model <|reserved_special_token_1|> <|reserved_special_token_0|> __all__ = ['lenet_mnist'] class Lenet(nn.Module): def __init__(self): super(Lenet, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(20, 50, 5) self.fc1 = nn.Linear(800, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): layer_w = self.fc2.weight sigma = layer_w.std().data.cpu().numpy() layer_w_numpy = layer_w.data.cpu().numpy() scale = 0.17 noise = np.random.normal(0, scale * sigma, layer_w.size()) w_noise = np.add(layer_w_numpy, noise) w_noise_tensor = torch.tensor(w_noise) w_noise_tensor = w_noise_tensor.to('cuda') w_noise = torch.nn.Parameter(w_noise_tensor.float()) self.fc2.weight = w_noise x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 800) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return x def lenet_mnist(): model = Lenet() return model <|reserved_special_token_1|> import torch import torch.nn as nn import torch.nn.functional as F import numpy as np __all__ = ['lenet_mnist'] class Lenet(nn.Module): def __init__(self): super(Lenet, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(20, 50, 5) self.fc1 = nn.Linear(800, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): layer_w = self.fc2.weight sigma = layer_w.std().data.cpu().numpy() layer_w_numpy = layer_w.data.cpu().numpy() scale = 0.17 noise = np.random.normal(0, scale * sigma, layer_w.size()) w_noise = np.add(layer_w_numpy, noise) w_noise_tensor = torch.tensor(w_noise) w_noise_tensor = w_noise_tensor.to('cuda') w_noise = torch.nn.Parameter(w_noise_tensor.float()) self.fc2.weight = w_noise x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 800) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return x def lenet_mnist(): model = Lenet() return model <|reserved_special_token_1|> # # Copyright (c) 2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import torch import torch.nn as nn import torch.nn.functional as F import numpy as np __all__ = ['lenet_mnist'] class Lenet(nn.Module): def __init__(self): super(Lenet, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(20, 50, 5) self.fc1 = nn.Linear(800, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): #print("weights sizes") #print(self.conv1.weight.size()) layer_w = self.fc2.weight sigma = layer_w.std().data.cpu().numpy() layer_w_numpy = layer_w.data.cpu().numpy() scale = 0.17 noise = np.random.normal(0, scale*sigma, layer_w.size()) w_noise = np.add(layer_w_numpy, noise) w_noise_tensor = torch.tensor(w_noise) #print(w_noise_tensor.size()) w_noise_tensor = w_noise_tensor.to('cuda') w_noise = torch.nn.Parameter(w_noise_tensor.float()) self.fc2.weight = w_noise #print("---------------------") #print(self.conv2.weight.size()) #print("---------------------") #print(self.fc1.weight.size()) #print("---------------------") #print(self.fc2.weight.size()) #print("---------------------") x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 800) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) #x = nn.Threshold(0.2, 0.0)#ActivationZeroThreshold(x) return x def lenet_mnist(): model = Lenet() return model
flexible
{ "blob_id": "a38a5010c9edbed0929da225b4288396bb0d814e", "index": 6989, "step-1": "<mask token>\n\n\nclass Lenet(nn.Module):\n <mask token>\n\n def forward(self, x):\n layer_w = self.fc2.weight\n sigma = layer_w.std().data.cpu().numpy()\n layer_w_numpy = layer_w.data.cpu().numpy()\n scale = 0.17\n noise = np.random.normal(0, scale * sigma, layer_w.size())\n w_noise = np.add(layer_w_numpy, noise)\n w_noise_tensor = torch.tensor(w_noise)\n w_noise_tensor = w_noise_tensor.to('cuda')\n w_noise = torch.nn.Parameter(w_noise_tensor.float())\n self.fc2.weight = w_noise\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 800)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return x\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Lenet(nn.Module):\n\n def __init__(self):\n super(Lenet, self).__init__()\n self.conv1 = nn.Conv2d(1, 20, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(20, 50, 5)\n self.fc1 = nn.Linear(800, 500)\n self.fc2 = nn.Linear(500, 10)\n\n def forward(self, x):\n layer_w = self.fc2.weight\n sigma = layer_w.std().data.cpu().numpy()\n layer_w_numpy = layer_w.data.cpu().numpy()\n scale = 0.17\n noise = np.random.normal(0, scale * sigma, layer_w.size())\n w_noise = np.add(layer_w_numpy, noise)\n w_noise_tensor = torch.tensor(w_noise)\n w_noise_tensor = w_noise_tensor.to('cuda')\n w_noise = torch.nn.Parameter(w_noise_tensor.float())\n self.fc2.weight = w_noise\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 800)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return x\n\n\ndef lenet_mnist():\n model = Lenet()\n return model\n", "step-3": "<mask token>\n__all__ = ['lenet_mnist']\n\n\nclass Lenet(nn.Module):\n\n def __init__(self):\n super(Lenet, self).__init__()\n self.conv1 = nn.Conv2d(1, 20, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(20, 50, 5)\n self.fc1 = nn.Linear(800, 500)\n self.fc2 = nn.Linear(500, 10)\n\n def forward(self, x):\n layer_w = self.fc2.weight\n sigma = layer_w.std().data.cpu().numpy()\n layer_w_numpy = layer_w.data.cpu().numpy()\n scale = 0.17\n noise = np.random.normal(0, scale * sigma, layer_w.size())\n w_noise = np.add(layer_w_numpy, noise)\n w_noise_tensor = torch.tensor(w_noise)\n w_noise_tensor = w_noise_tensor.to('cuda')\n w_noise = torch.nn.Parameter(w_noise_tensor.float())\n self.fc2.weight = w_noise\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 800)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return x\n\n\ndef lenet_mnist():\n model = Lenet()\n return model\n", "step-4": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n__all__ = ['lenet_mnist']\n\n\nclass Lenet(nn.Module):\n\n def __init__(self):\n super(Lenet, self).__init__()\n self.conv1 = nn.Conv2d(1, 20, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(20, 50, 5)\n self.fc1 = nn.Linear(800, 500)\n self.fc2 = nn.Linear(500, 10)\n\n def forward(self, x):\n layer_w = self.fc2.weight\n sigma = layer_w.std().data.cpu().numpy()\n layer_w_numpy = layer_w.data.cpu().numpy()\n scale = 0.17\n noise = np.random.normal(0, scale * sigma, layer_w.size())\n w_noise = np.add(layer_w_numpy, noise)\n w_noise_tensor = torch.tensor(w_noise)\n w_noise_tensor = w_noise_tensor.to('cuda')\n w_noise = torch.nn.Parameter(w_noise_tensor.float())\n self.fc2.weight = w_noise\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 800)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return x\n\n\ndef lenet_mnist():\n model = Lenet()\n return model\n", "step-5": "#\n# Copyright (c) 2018 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np \n\n__all__ = ['lenet_mnist']\n\nclass Lenet(nn.Module):\n def __init__(self):\n super(Lenet, self).__init__()\n self.conv1 = nn.Conv2d(1, 20, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(20, 50, 5)\n self.fc1 = nn.Linear(800, 500)\n self.fc2 = nn.Linear(500, 10)\n\n def forward(self, x):\n #print(\"weights sizes\")\n #print(self.conv1.weight.size())\n layer_w = self.fc2.weight\n sigma = layer_w.std().data.cpu().numpy()\n layer_w_numpy = layer_w.data.cpu().numpy()\n scale = 0.17\n noise = np.random.normal(0, scale*sigma, layer_w.size())\n w_noise = np.add(layer_w_numpy, noise)\n w_noise_tensor = torch.tensor(w_noise)\n #print(w_noise_tensor.size())\n w_noise_tensor = w_noise_tensor.to('cuda')\n w_noise = torch.nn.Parameter(w_noise_tensor.float())\n self.fc2.weight = w_noise \n #print(\"---------------------\")\n #print(self.conv2.weight.size())\n #print(\"---------------------\")\n #print(self.fc1.weight.size())\n #print(\"---------------------\")\n #print(self.fc2.weight.size())\n #print(\"---------------------\")\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 800)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n #x = nn.Threshold(0.2, 0.0)#ActivationZeroThreshold(x)\n return x\n\ndef lenet_mnist():\n model = Lenet()\n return model\n", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
b = int(input('enter anum ')) for a in range(1, 11, 1): print(b, 'x', a, '=', a * b)
normal
{ "blob_id": "bf83556b8e8855a0e410fcfb3b42161fbc681830", "index": 3075, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor a in range(1, 11, 1):\n print(b, 'x', a, '=', a * b)\n", "step-3": "b = int(input('enter anum '))\nfor a in range(1, 11, 1):\n print(b, 'x', a, '=', a * b)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> @micropython.viper def viper_int(x: int, y: int) ->int: return x + y + 3 <|reserved_special_token_0|> @micropython.viper def viper_local(x: int) ->int: y = 4 return x + y <|reserved_special_token_0|> @micropython.viper def viper_no_annotation(x, y): return x * y <|reserved_special_token_0|> @micropython.viper def viper_for(a: int, b: int) ->int: total = 0 for x in range(a, b): total += x return total <|reserved_special_token_0|> @micropython.viper def viper_access_global(): global gl gl = 1 return gl <|reserved_special_token_0|> @micropython.viper def viper_print(x, y: int): print(x, y + 1) <|reserved_special_token_0|> @micropython.viper def viper_set(x, y: int): return {x, y + 1} <|reserved_special_token_0|> @micropython.viper def viper_raise(x: int): raise OSError(x) <|reserved_special_token_0|> @micropython.viper def viper_gc() ->int: return 1 <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @micropython.viper def viper_int(x: int, y: int) ->int: return x + y + 3 <|reserved_special_token_0|> @micropython.viper def viper_local(x: int) ->int: y = 4 return x + y <|reserved_special_token_0|> @micropython.viper def viper_no_annotation(x, y): return x * y <|reserved_special_token_0|> @micropython.viper def viper_for(a: int, b: int) ->int: total = 0 for x in range(a, b): total += x return total <|reserved_special_token_0|> @micropython.viper def viper_access_global(): global gl gl = 1 return gl <|reserved_special_token_0|> @micropython.viper def viper_print(x, y: int): print(x, y + 1) <|reserved_special_token_0|> @micropython.viper def viper_tuple(x, y: int): return x, y + 1 <|reserved_special_token_0|> @micropython.viper def viper_set(x, y: int): return {x, y + 1} <|reserved_special_token_0|> @micropython.viper def viper_raise(x: int): raise OSError(x) <|reserved_special_token_0|> @micropython.viper def viper_gc() ->int: return 1 <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @micropython.viper def viper_int(x: int, y: int) ->int: return x + y + 3 <|reserved_special_token_0|> @micropython.viper def viper_object(x: object, y: object) ->object: return x + y <|reserved_special_token_0|> @micropython.viper def viper_local(x: int) ->int: y = 4 return x + y <|reserved_special_token_0|> @micropython.viper def viper_no_annotation(x, y): return x * y <|reserved_special_token_0|> @micropython.viper def viper_for(a: int, b: int) ->int: total = 0 for x in range(a, b): total += x return total <|reserved_special_token_0|> @micropython.viper def viper_access_global(): global gl gl = 1 return gl <|reserved_special_token_0|> @micropython.viper def viper_print(x, y: int): print(x, y + 1) <|reserved_special_token_0|> @micropython.viper def viper_tuple(x, y: int): return x, y + 1 <|reserved_special_token_0|> @micropython.viper def viper_list(x, y: int): return [x, y + 1] <|reserved_special_token_0|> @micropython.viper def viper_set(x, y: int): return {x, y + 1} <|reserved_special_token_0|> @micropython.viper def viper_raise(x: int): raise OSError(x) <|reserved_special_token_0|> @micropython.viper def viper_gc() ->int: return 1 <|reserved_special_token_0|> <|reserved_special_token_1|> import micropython @micropython.viper def viper_int(x: int, y: int) ->int: return x + y + 3 print(viper_int(1, 2)) @micropython.viper def viper_object(x: object, y: object) ->object: return x + y print(viper_object(1, 2)) @micropython.viper def viper_local(x: int) ->int: y = 4 return x + y print(viper_local(3)) @micropython.viper def viper_no_annotation(x, y): return x * y print(viper_no_annotation(4, 5)) @micropython.viper def viper_for(a: int, b: int) ->int: total = 0 for x in range(a, b): total += x return total print(viper_for(10, 10000)) @micropython.viper def viper_access_global(): global gl gl = 1 return gl print(viper_access_global(), gl) @micropython.viper def viper_print(x, y: int): print(x, y + 1) viper_print(1, 2) @micropython.viper def viper_tuple(x, y: int): return x, y + 1 print(viper_tuple(1, 2)) @micropython.viper def viper_list(x, y: int): return [x, y + 1] print(viper_list(1, 2)) @micropython.viper def viper_set(x, y: int): return {x, y + 1} print(sorted(list(viper_set(1, 2)))) @micropython.viper def viper_raise(x: int): raise OSError(x) try: viper_raise(1) except OSError as e: print(repr(e)) @micropython.viper def viper_gc() ->int: return 1 print(viper_gc()) import gc gc.collect() print(viper_gc()) <|reserved_special_token_1|> import micropython # viper function taking and returning ints @micropython.viper def viper_int(x:int, y:int) -> int: return x + y + 3 print(viper_int(1, 2)) # viper function taking and returning objects @micropython.viper def viper_object(x:object, y:object) -> object: return x + y print(viper_object(1, 2)) # a local (should have automatic type int) @micropython.viper def viper_local(x:int) -> int: y = 4 return x + y print(viper_local(3)) # without type annotation, types should default to object @micropython.viper def viper_no_annotation(x, y): return x * y print(viper_no_annotation(4, 5)) # a for loop @micropython.viper def viper_for(a:int, b:int) -> int: total = 0 for x in range(a, b): total += x return total print(viper_for(10, 10000)) # accessing a global @micropython.viper def viper_access_global(): global gl gl = 1 return gl print(viper_access_global(), gl) # calling print with object and int types @micropython.viper def viper_print(x, y:int): print(x, y + 1) viper_print(1, 2) # making a tuple from an object and an int @micropython.viper def viper_tuple(x, y:int): return (x, y + 1) print(viper_tuple(1, 2)) # making a list from an object and an int @micropython.viper def viper_list(x, y:int): return [x, y + 1] print(viper_list(1, 2)) # making a set from an object and an int @micropython.viper def viper_set(x, y:int): return {x, y + 1} print(sorted(list(viper_set(1, 2)))) # raising an exception @micropython.viper def viper_raise(x:int): raise OSError(x) try: viper_raise(1) except OSError as e: print(repr(e)) # this doesn't work at the moment #@micropython.viper #def g() -> uint: # return -1 # calling GC after defining the function @micropython.viper def viper_gc() -> int: return 1 print(viper_gc()) import gc gc.collect() print(viper_gc())
flexible
{ "blob_id": "eec52695e5afcc21e5fed6453e96cc3a58e7c1df", "index": 101, "step-1": "<mask token>\n\n\n@micropython.viper\ndef viper_int(x: int, y: int) ->int:\n return x + y + 3\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_local(x: int) ->int:\n y = 4\n return x + y\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_no_annotation(x, y):\n return x * y\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_for(a: int, b: int) ->int:\n total = 0\n for x in range(a, b):\n total += x\n return total\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_access_global():\n global gl\n gl = 1\n return gl\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_print(x, y: int):\n print(x, y + 1)\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_set(x, y: int):\n return {x, y + 1}\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_raise(x: int):\n raise OSError(x)\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_gc() ->int:\n return 1\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@micropython.viper\ndef viper_int(x: int, y: int) ->int:\n return x + y + 3\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_local(x: int) ->int:\n y = 4\n return x + y\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_no_annotation(x, y):\n return x * y\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_for(a: int, b: int) ->int:\n total = 0\n for x in range(a, b):\n total += x\n return total\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_access_global():\n global gl\n gl = 1\n return gl\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_print(x, y: int):\n print(x, y + 1)\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_tuple(x, y: int):\n return x, y + 1\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_set(x, y: int):\n return {x, y + 1}\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_raise(x: int):\n raise OSError(x)\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_gc() ->int:\n return 1\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\n@micropython.viper\ndef viper_int(x: int, y: int) ->int:\n return x + y + 3\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_object(x: object, y: object) ->object:\n return x + y\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_local(x: int) ->int:\n y = 4\n return x + y\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_no_annotation(x, y):\n return x * y\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_for(a: int, b: int) ->int:\n total = 0\n for x in range(a, b):\n total += x\n return total\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_access_global():\n global gl\n gl = 1\n return gl\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_print(x, y: int):\n print(x, y + 1)\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_tuple(x, y: int):\n return x, y + 1\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_list(x, y: int):\n return [x, y + 1]\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_set(x, y: int):\n return {x, y + 1}\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_raise(x: int):\n raise OSError(x)\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_gc() ->int:\n return 1\n\n\n<mask token>\n", "step-4": "import micropython\n\n\n@micropython.viper\ndef viper_int(x: int, y: int) ->int:\n return x + y + 3\n\n\nprint(viper_int(1, 2))\n\n\n@micropython.viper\ndef viper_object(x: object, y: object) ->object:\n return x + y\n\n\nprint(viper_object(1, 2))\n\n\n@micropython.viper\ndef viper_local(x: int) ->int:\n y = 4\n return x + y\n\n\nprint(viper_local(3))\n\n\n@micropython.viper\ndef viper_no_annotation(x, y):\n return x * y\n\n\nprint(viper_no_annotation(4, 5))\n\n\n@micropython.viper\ndef viper_for(a: int, b: int) ->int:\n total = 0\n for x in range(a, b):\n total += x\n return total\n\n\nprint(viper_for(10, 10000))\n\n\n@micropython.viper\ndef viper_access_global():\n global gl\n gl = 1\n return gl\n\n\nprint(viper_access_global(), gl)\n\n\n@micropython.viper\ndef viper_print(x, y: int):\n print(x, y + 1)\n\n\nviper_print(1, 2)\n\n\n@micropython.viper\ndef viper_tuple(x, y: int):\n return x, y + 1\n\n\nprint(viper_tuple(1, 2))\n\n\n@micropython.viper\ndef viper_list(x, y: int):\n return [x, y + 1]\n\n\nprint(viper_list(1, 2))\n\n\n@micropython.viper\ndef viper_set(x, y: int):\n return {x, y + 1}\n\n\nprint(sorted(list(viper_set(1, 2))))\n\n\n@micropython.viper\ndef viper_raise(x: int):\n raise OSError(x)\n\n\ntry:\n viper_raise(1)\nexcept OSError as e:\n print(repr(e))\n\n\n@micropython.viper\ndef viper_gc() ->int:\n return 1\n\n\nprint(viper_gc())\nimport gc\ngc.collect()\nprint(viper_gc())\n", "step-5": "import micropython\r\n\r\n# viper function taking and returning ints\r\n@micropython.viper\r\ndef viper_int(x:int, y:int) -> int:\r\n return x + y + 3\r\nprint(viper_int(1, 2))\r\n\r\n# viper function taking and returning objects\r\n@micropython.viper\r\ndef viper_object(x:object, y:object) -> object:\r\n return x + y\r\nprint(viper_object(1, 2))\r\n\r\n# a local (should have automatic type int)\r\n@micropython.viper\r\ndef viper_local(x:int) -> int:\r\n y = 4\r\n return x + y\r\nprint(viper_local(3))\r\n\r\n# without type annotation, types should default to object\r\n@micropython.viper\r\ndef viper_no_annotation(x, y):\r\n return x * y\r\nprint(viper_no_annotation(4, 5))\r\n\r\n# a for loop\r\n@micropython.viper\r\ndef viper_for(a:int, b:int) -> int:\r\n total = 0\r\n for x in range(a, b):\r\n total += x\r\n return total\r\nprint(viper_for(10, 10000))\r\n\r\n# accessing a global\r\n@micropython.viper\r\ndef viper_access_global():\r\n global gl\r\n gl = 1\r\n return gl\r\nprint(viper_access_global(), gl)\r\n\r\n# calling print with object and int types\r\n@micropython.viper\r\ndef viper_print(x, y:int):\r\n print(x, y + 1)\r\nviper_print(1, 2)\r\n\r\n# making a tuple from an object and an int\r\n@micropython.viper\r\ndef viper_tuple(x, y:int):\r\n return (x, y + 1)\r\nprint(viper_tuple(1, 2))\r\n\r\n# making a list from an object and an int\r\n@micropython.viper\r\ndef viper_list(x, y:int):\r\n return [x, y + 1]\r\nprint(viper_list(1, 2))\r\n\r\n# making a set from an object and an int\r\n@micropython.viper\r\ndef viper_set(x, y:int):\r\n return {x, y + 1}\r\nprint(sorted(list(viper_set(1, 2))))\r\n\r\n# raising an exception\r\n@micropython.viper\r\ndef viper_raise(x:int):\r\n raise OSError(x)\r\ntry:\r\n viper_raise(1)\r\nexcept OSError as e:\r\n print(repr(e))\r\n\r\n# this doesn't work at the moment\r\n#@micropython.viper\r\n#def g() -> uint:\r\n# return -1\r\n\r\n# calling GC after defining the function\r\n@micropython.viper\r\ndef viper_gc() -> int:\r\n return 1\r\nprint(viper_gc())\r\nimport gc\r\ngc.collect()\r\nprint(viper_gc())\r\n", "step-ids": [ 9, 10, 12, 14, 15 ] }
[ 9, 10, 12, 14, 15 ]
def main(): num = int(input('dia: ')) dia(num) def dia(a): if a == 1: print('Domingo !') elif a == 2: print('Segunda !') else: print('valor invalido !') main()
normal
{ "blob_id": "07332e2da5458fda2112de2507037a759d3c62db", "index": 3382, "step-1": "<mask token>\n", "step-2": "def main():\n num = int(input('dia: '))\n dia(num)\n\n\n<mask token>\n", "step-3": "def main():\n num = int(input('dia: '))\n dia(num)\n\n\ndef dia(a):\n if a == 1:\n print('Domingo !')\n elif a == 2:\n print('Segunda !')\n else:\n print('valor invalido !')\n\n\n<mask token>\n", "step-4": "def main():\n num = int(input('dia: '))\n dia(num)\n\n\ndef dia(a):\n if a == 1:\n print('Domingo !')\n elif a == 2:\n print('Segunda !')\n else:\n print('valor invalido !')\n\n\nmain()\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
""" contains generic code for use in main menus. currently this is a function which turns dictionaries of functions into a menu. I envision any further menu functions being stored here so don't expect it to run like a pipeline but rather like a suite of individual menus. TODO - refactor spider selection function as jesus christ that things fat - incorporate spider selector in config manager options """ import re import os import json from datetime import date, datetime from collections import defaultdict import pandas as pd from HousingPriceScraper.HousingPriceScraper.functions.basic_functions import return_false, end_process, \ alphabet_list_length, flatten_list_of_lists from HousingPriceScraper.HousingPriceScraper.functions.data_management import save_list_to_txt def final_option(dict_of_options, back): """ adds the final option to the dictionary based on a boolean :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important that these functions don't require parameters. :param back: boolean :return: dict_of_options but with a new, final key added in """ if back: dict_of_options['back'] = return_false else: dict_of_options['end_process'] = end_process return dict_of_options def basic_menu(dict_of_options, back=False): """ basic text based user interface, allows user to select a function to run from a dictionary of options, by using a simple numeric code. User will see this dictionaries keys enumerated on screen to choose from. :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important that these functions don't require parameters. :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to ending process since that's how the main menu does it and unsure of where else function will be called :return: run the chosen function """ choose = True dict_of_options = final_option(dict_of_options, back) list_of_options = list(dict_of_options.keys()) while choose: print('The following options are available:\n') for option in enumerate(list_of_options): print('\t{} - {}'.format(option[0], option[1])) pick = input('\nType the numeric code you wish to run\n\n') if pick in [str(i) for i in range((len(dict_of_options)))]: choose = dict_of_options[list_of_options[int(pick)]]() else: print('{} is not currently an option!\n'.format(pick)) def basic_menu_non_functional(list_of_options): """ basic text based user interface, allows user to select multiple options from a list of available choices. :param list_of_options: list of available choices :return: a list of chosen strings """ choose = True list_of_options.append('back') while choose: print('The following options are available:\n') for option in enumerate(list_of_options): print('\t{} - {}'.format(option[0], option[1])) picks = input('\nType the numeric codes you wish to run\n\n').split(',') choice = [] if str(len(list_of_options)) in picks: return True for pick in picks: if pick in [str(i) for i in range((len(list_of_options)))]: choice.append(list_of_options[int(pick)]) else: print('{} is not currently an option!\n'.format(pick)) if len(choice) > 0: return choice def select_spiders(spiders_dict): """ select from spiders available. allows user to select all spiders, select all spiders within a project group, select some comma separated list of individual/groups of spiders, or by prefixing a given selection with "-", the user can remove a spider from his or her selection. :param spiders_dict: dictionary who's keys are broad options and values are lists of spiders :return: list containing the spiders the user has selected to run """ print('Available spiders include:\n') enumerated_keys = list(enumerate(spiders_dict.keys())) for key_group in enumerated_keys: print('{} - {}'.format(key_group[0], key_group[1])) for spider in zip(alphabet_list_length(len(key_group[1])), spiders_dict[key_group[1]]): print('\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name)) print('{} - run all'.format(len(spiders_dict.keys()))) print('{} - back'.format(len(spiders_dict.keys())+1)) choices = input('\nfor multiple, comma separate. To remove, use "-" prefix\ni.e.: 0,-0a to run all of group 0 except the first\n').replace(' ', '').split(',') if str(len(spiders_dict.keys())+1) in choices: return False if str(len(spiders_dict.keys())) in choices: chosen_spiders = list(spiders_dict.values()) else: chosen_spiders = [] for choice in choices: if choice.isdigit(): if choice in [str(i[0]) for i in enumerated_keys]: chosen_spiders.append(spiders_dict[enumerated_keys[int(choice)][1]]) else: print('{} is not an option!'.format(choice)) elif '-' not in choice: numeric = re.findall(r'\d+', choice) if len(numeric) == 1: alpha = choice.split(numeric[0])[1] alpha = len(alphabet_list_length(0, index=alpha))-1 try: chosen_spiders.append(spiders_dict[enumerated_keys[int(numeric[0])][1]][alpha]) except IndexError: print('{} is not an option!'.format(choice)) else: print('{} is not an option!'.format(choice)) if any(isinstance(el, list) for el in chosen_spiders): chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True) else: chosen_spiders = list(set(chosen_spiders)) to_remove = [choice for choice in choices if '-' in choice] if len(to_remove) > 0: for removee in to_remove: if removee.replace('-', '').isdigit(): if removee.replace('-', '') in [str(i[0]) for i in enumerated_keys]: for spider in spiders_dict[enumerated_keys[int(removee.replace('-', ''))][1]]: chosen_spiders.remove(spider) else: print('{} is not an option!'.format(removee)) else: numeric = re.findall(r'\d+', removee) if len(numeric) == 1: alpha = removee.split(numeric[0])[1] alpha = len(alphabet_list_length(0, index=alpha)) - 1 try: chosen_spiders.remove(spiders_dict[enumerated_keys[int(numeric[0])][1]][alpha]) except IndexError: print('{} is not an option!'.format(removee)) else: print('{} is not an option!'.format(removee)) if len(chosen_spiders) > 0: return chosen_spiders else: print("You haven't selected any spiders!") return False def project_visibility_menu(): """ creates menu to allow user to set which project groups are visible in the run_scrapers menu :return: creates a txt file containing the list of desired project names, one per row. """ projects = [i.split('.')[0] for i in os.listdir('HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]] print('Available projects are:\n') for project in enumerate(projects): print('\t{} - {}'.format(project[0], project[1])) print('\t{} - back'.format(len(projects))) choices = input('\nType the options you wish to select.\nFor multiple, comma separate\n\n').split(',') if str(len(projects)) in choices: return True else: choice_list = [] for choice in choices: if choice.isdigit() and int(choice) in range(len(projects)): choice_list.append(projects[int(choice)]) print('You have selected to display the following spider groupings:\n\t{}\n'.format(choice_list)) save_list_to_txt(choice_list, 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt') return True def set_config(): """ menu to set the url configs. :return: will set the start_urls of the spiders. """ available_configs = open('HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt', 'r') options = available_configs.readlines() options_dict = {} print('available configs include:\n') for option in enumerate(options): options_dict[option[0]] = option[1].split(':')[0] print('\t{} - {}'.format(option[0], option[1].replace('\n', ''))) print('\t{} - back'.format(len(options))) chosen = input('\ncomma separate for multiple\n').split(',') if (str(len(options)) in chosen) or (chosen == ['']): return True configs = [] for choice in chosen: if int(choice) in options_dict: with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'.format(options_dict[int(choice)])) as f: configs.append(json.load(f)) final_config = defaultdict(list) for config in configs: for key, value in config.items(): if key in final_config: final_config[key] += value else: final_config[key] = value for key, value in final_config.items(): if any(isinstance(val, list) for val in value): final_config[key] = flatten_list_of_lists(value, make_set=True) with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json: default_dict = json.load(default_urls_json) for key, value in default_dict.items(): if key not in final_config.keys(): final_config[key] = value with open('HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w') as fp: json.dump(final_config, fp, sort_keys=True, indent=4) return True def append_recent_urls(): """ function for appending recent scraped urls to default urls json :return: default.json is updated """ with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json: default_dict = json.load(default_urls_json) with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json: recent_dict = json.load(recent_urls_json) for key, value in recent_dict.items(): default_dict.setdefault(key, []).extend(value) with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json', 'w') as fp: json.dump(default_dict, fp, sort_keys=True, indent=4) def replace_default_urls(): """ function for replacing default urls config with recent scrapes :return: defaults.json is updated """ with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json: default_dict = json.load(default_urls_json) with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json: recent_dict = json.load(recent_urls_json) for key, value in recent_dict.items(): default_dict[key] = value with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json', 'w') as fp: json.dump(default_dict, fp, sort_keys=True, indent=4) def create_new_config(): """ function which creates a whole new config file to store recent scraped urls in :return: new config is created """ with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json: urls_dict = json.load(recent_urls_json) config_name = input('Type a name for the new config file:\n').replace(' ', '_').replace(':', '') config_desc = input('Type a brief description for the new config file:\n') with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'.format(config_name), 'w') as fp: json.dump(urls_dict, fp, sort_keys=True, indent=4) with open('HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt', 'a') as input_descs: input_descs.write('\n{}: {}'.format(config_name, config_desc)) print('\nSuccessfully saved recently scraped urls to new config: {}.json'.format(config_name)) def clear_recent_urls(): """ function which bleaches the recent urls config in order to start fresh next time :return: recent_urls will become an empty dictionary. """ with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json: recent_dict = json.load(recent_urls_json) for key in recent_dict.keys(): recent_dict[key] = [] with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json', 'w') as fp: json.dump(recent_dict, fp, sort_keys=True, indent=4) def select_date_interval_menu(): """ function allows user to inout start and end date to define an interval of dates :return: list of dates """ while True: start_date = input('\nInput desired start date with format dd-mm-yyyy:\n') try: start_date = datetime.strptime(start_date, '%d-%m-%Y') break except ValueError: print('invalid start date selected') while True: end_date = input('\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n') if end_date == '': end_date = date.today() break else: try: end_date = datetime.strptime(end_date, '%d-%m-%Y') break except ValueError: print('invalid end date selected') list_of_dates = pd.date_range(start_date, end_date, freq='d') list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates] return list_of_dates
normal
{ "blob_id": "f28b47e1b07011ce9d0708331f68d7f16195c567", "index": 7225, "step-1": "<mask token>\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range(len(dict_of_options))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(','\n )\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range(len(list_of_options))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\n<mask token>\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir(\n 'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input(\n '\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n'\n ).split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print(\n 'You have selected to display the following spider groupings:\\n\\t{}\\n'\n .format(choice_list))\n save_list_to_txt(choice_list,\n 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'\n )\n return True\n\n\n<mask token>\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ',\n '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'\n .format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n , 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input(\n '\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input(\n \"\"\"\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n\"\"\"\n )\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n", "step-2": "<mask token>\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range(len(dict_of_options))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(','\n )\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range(len(list_of_options))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\n<mask token>\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir(\n 'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input(\n '\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n'\n ).split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print(\n 'You have selected to display the following spider groupings:\\n\\t{}\\n'\n .format(choice_list))\n save_list_to_txt(choice_list,\n 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'\n )\n return True\n\n\ndef set_config():\n \"\"\"\n menu to set the url configs.\n\n :return: will set the start_urls of the spiders.\n \"\"\"\n available_configs = open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'r')\n options = available_configs.readlines()\n options_dict = {}\n print('available configs include:\\n')\n for option in enumerate(options):\n options_dict[option[0]] = option[1].split(':')[0]\n print('\\t{} - {}'.format(option[0], option[1].replace('\\n', '')))\n print('\\t{} - back'.format(len(options)))\n chosen = input('\\ncomma separate for multiple\\n').split(',')\n if str(len(options)) in chosen or chosen == ['']:\n return True\n configs = []\n for choice in chosen:\n if int(choice) in options_dict:\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(options_dict[int(choice)])) as f:\n configs.append(json.load(f))\n final_config = defaultdict(list)\n for config in configs:\n for key, value in config.items():\n if key in final_config:\n final_config[key] += value\n else:\n final_config[key] = value\n for key, value in final_config.items():\n if any(isinstance(val, list) for val in value):\n final_config[key] = flatten_list_of_lists(value, make_set=True)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n for key, value in default_dict.items():\n if key not in final_config.keys():\n final_config[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w'\n ) as fp:\n json.dump(final_config, fp, sort_keys=True, indent=4)\n return True\n\n\ndef append_recent_urls():\n \"\"\"\n function for appending recent scraped urls to default urls json\n\n :return: default.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict.setdefault(key, []).extend(value)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ',\n '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'\n .format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n , 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input(\n '\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input(\n \"\"\"\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n\"\"\"\n )\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n", "step-3": "<mask token>\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range(len(dict_of_options))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(','\n )\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range(len(list_of_options))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\ndef select_spiders(spiders_dict):\n \"\"\"\n select from spiders available. allows user to select all spiders, select all spiders within a\n project group, select some comma separated list of individual/groups of spiders, or by prefixing a\n given selection with \"-\", the user can remove a spider from his or her selection.\n\n :param spiders_dict: dictionary who's keys are broad options and values are lists of spiders\n :return: list containing the spiders the user has selected to run\n \"\"\"\n print('Available spiders include:\\n')\n enumerated_keys = list(enumerate(spiders_dict.keys()))\n for key_group in enumerated_keys:\n print('{} - {}'.format(key_group[0], key_group[1]))\n for spider in zip(alphabet_list_length(len(key_group[1])),\n spiders_dict[key_group[1]]):\n print('\\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name)\n )\n print('{} - run all'.format(len(spiders_dict.keys())))\n print('{} - back'.format(len(spiders_dict.keys()) + 1))\n choices = input(\n \"\"\"\nfor multiple, comma separate. To remove, use \"-\" prefix\ni.e.: 0,-0a to run all of group 0 except the first\n\"\"\"\n ).replace(' ', '').split(',')\n if str(len(spiders_dict.keys()) + 1) in choices:\n return False\n if str(len(spiders_dict.keys())) in choices:\n chosen_spiders = list(spiders_dict.values())\n else:\n chosen_spiders = []\n for choice in choices:\n if choice.isdigit():\n if choice in [str(i[0]) for i in enumerated_keys]:\n chosen_spiders.append(spiders_dict[enumerated_keys[int(\n choice)][1]])\n else:\n print('{} is not an option!'.format(choice))\n elif '-' not in choice:\n numeric = re.findall('\\\\d+', choice)\n if len(numeric) == 1:\n alpha = choice.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.append(spiders_dict[enumerated_keys[\n int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(choice))\n else:\n print('{} is not an option!'.format(choice))\n if any(isinstance(el, list) for el in chosen_spiders):\n chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True)\n else:\n chosen_spiders = list(set(chosen_spiders))\n to_remove = [choice for choice in choices if '-' in choice]\n if len(to_remove) > 0:\n for removee in to_remove:\n if removee.replace('-', '').isdigit():\n if removee.replace('-', '') in [str(i[0]) for i in\n enumerated_keys]:\n for spider in spiders_dict[enumerated_keys[int(removee.\n replace('-', ''))][1]]:\n chosen_spiders.remove(spider)\n else:\n print('{} is not an option!'.format(removee))\n else:\n numeric = re.findall('\\\\d+', removee)\n if len(numeric) == 1:\n alpha = removee.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.remove(spiders_dict[enumerated_keys[\n int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(removee))\n else:\n print('{} is not an option!'.format(removee))\n if len(chosen_spiders) > 0:\n return chosen_spiders\n else:\n print(\"You haven't selected any spiders!\")\n return False\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir(\n 'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input(\n '\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n'\n ).split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print(\n 'You have selected to display the following spider groupings:\\n\\t{}\\n'\n .format(choice_list))\n save_list_to_txt(choice_list,\n 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'\n )\n return True\n\n\ndef set_config():\n \"\"\"\n menu to set the url configs.\n\n :return: will set the start_urls of the spiders.\n \"\"\"\n available_configs = open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'r')\n options = available_configs.readlines()\n options_dict = {}\n print('available configs include:\\n')\n for option in enumerate(options):\n options_dict[option[0]] = option[1].split(':')[0]\n print('\\t{} - {}'.format(option[0], option[1].replace('\\n', '')))\n print('\\t{} - back'.format(len(options)))\n chosen = input('\\ncomma separate for multiple\\n').split(',')\n if str(len(options)) in chosen or chosen == ['']:\n return True\n configs = []\n for choice in chosen:\n if int(choice) in options_dict:\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(options_dict[int(choice)])) as f:\n configs.append(json.load(f))\n final_config = defaultdict(list)\n for config in configs:\n for key, value in config.items():\n if key in final_config:\n final_config[key] += value\n else:\n final_config[key] = value\n for key, value in final_config.items():\n if any(isinstance(val, list) for val in value):\n final_config[key] = flatten_list_of_lists(value, make_set=True)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n for key, value in default_dict.items():\n if key not in final_config.keys():\n final_config[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w'\n ) as fp:\n json.dump(final_config, fp, sort_keys=True, indent=4)\n return True\n\n\ndef append_recent_urls():\n \"\"\"\n function for appending recent scraped urls to default urls json\n\n :return: default.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict.setdefault(key, []).extend(value)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ',\n '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'\n .format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n , 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input(\n '\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input(\n \"\"\"\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n\"\"\"\n )\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n", "step-4": "<mask token>\nimport re\nimport os\nimport json\nfrom datetime import date, datetime\nfrom collections import defaultdict\nimport pandas as pd\nfrom HousingPriceScraper.HousingPriceScraper.functions.basic_functions import return_false, end_process, alphabet_list_length, flatten_list_of_lists\nfrom HousingPriceScraper.HousingPriceScraper.functions.data_management import save_list_to_txt\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range(len(dict_of_options))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(','\n )\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range(len(list_of_options))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\ndef select_spiders(spiders_dict):\n \"\"\"\n select from spiders available. allows user to select all spiders, select all spiders within a\n project group, select some comma separated list of individual/groups of spiders, or by prefixing a\n given selection with \"-\", the user can remove a spider from his or her selection.\n\n :param spiders_dict: dictionary who's keys are broad options and values are lists of spiders\n :return: list containing the spiders the user has selected to run\n \"\"\"\n print('Available spiders include:\\n')\n enumerated_keys = list(enumerate(spiders_dict.keys()))\n for key_group in enumerated_keys:\n print('{} - {}'.format(key_group[0], key_group[1]))\n for spider in zip(alphabet_list_length(len(key_group[1])),\n spiders_dict[key_group[1]]):\n print('\\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name)\n )\n print('{} - run all'.format(len(spiders_dict.keys())))\n print('{} - back'.format(len(spiders_dict.keys()) + 1))\n choices = input(\n \"\"\"\nfor multiple, comma separate. To remove, use \"-\" prefix\ni.e.: 0,-0a to run all of group 0 except the first\n\"\"\"\n ).replace(' ', '').split(',')\n if str(len(spiders_dict.keys()) + 1) in choices:\n return False\n if str(len(spiders_dict.keys())) in choices:\n chosen_spiders = list(spiders_dict.values())\n else:\n chosen_spiders = []\n for choice in choices:\n if choice.isdigit():\n if choice in [str(i[0]) for i in enumerated_keys]:\n chosen_spiders.append(spiders_dict[enumerated_keys[int(\n choice)][1]])\n else:\n print('{} is not an option!'.format(choice))\n elif '-' not in choice:\n numeric = re.findall('\\\\d+', choice)\n if len(numeric) == 1:\n alpha = choice.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.append(spiders_dict[enumerated_keys[\n int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(choice))\n else:\n print('{} is not an option!'.format(choice))\n if any(isinstance(el, list) for el in chosen_spiders):\n chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True)\n else:\n chosen_spiders = list(set(chosen_spiders))\n to_remove = [choice for choice in choices if '-' in choice]\n if len(to_remove) > 0:\n for removee in to_remove:\n if removee.replace('-', '').isdigit():\n if removee.replace('-', '') in [str(i[0]) for i in\n enumerated_keys]:\n for spider in spiders_dict[enumerated_keys[int(removee.\n replace('-', ''))][1]]:\n chosen_spiders.remove(spider)\n else:\n print('{} is not an option!'.format(removee))\n else:\n numeric = re.findall('\\\\d+', removee)\n if len(numeric) == 1:\n alpha = removee.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.remove(spiders_dict[enumerated_keys[\n int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(removee))\n else:\n print('{} is not an option!'.format(removee))\n if len(chosen_spiders) > 0:\n return chosen_spiders\n else:\n print(\"You haven't selected any spiders!\")\n return False\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir(\n 'HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input(\n '\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n'\n ).split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print(\n 'You have selected to display the following spider groupings:\\n\\t{}\\n'\n .format(choice_list))\n save_list_to_txt(choice_list,\n 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt'\n )\n return True\n\n\ndef set_config():\n \"\"\"\n menu to set the url configs.\n\n :return: will set the start_urls of the spiders.\n \"\"\"\n available_configs = open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'r')\n options = available_configs.readlines()\n options_dict = {}\n print('available configs include:\\n')\n for option in enumerate(options):\n options_dict[option[0]] = option[1].split(':')[0]\n print('\\t{} - {}'.format(option[0], option[1].replace('\\n', '')))\n print('\\t{} - back'.format(len(options)))\n chosen = input('\\ncomma separate for multiple\\n').split(',')\n if str(len(options)) in chosen or chosen == ['']:\n return True\n configs = []\n for choice in chosen:\n if int(choice) in options_dict:\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(options_dict[int(choice)])) as f:\n configs.append(json.load(f))\n final_config = defaultdict(list)\n for config in configs:\n for key, value in config.items():\n if key in final_config:\n final_config[key] += value\n else:\n final_config[key] = value\n for key, value in final_config.items():\n if any(isinstance(val, list) for val in value):\n final_config[key] = flatten_list_of_lists(value, make_set=True)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n for key, value in default_dict.items():\n if key not in final_config.keys():\n final_config[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w'\n ) as fp:\n json.dump(final_config, fp, sort_keys=True, indent=4)\n return True\n\n\ndef append_recent_urls():\n \"\"\"\n function for appending recent scraped urls to default urls json\n\n :return: default.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict.setdefault(key, []).extend(value)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n ) as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json'\n , 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ',\n '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'\n .format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt'\n , 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'\n .format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n ) as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open(\n 'HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json'\n , 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input(\n '\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input(\n \"\"\"\nInput desired start date with format dd-mm-yyyy,\nor hit enter to select todays date\n\"\"\"\n )\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n", "step-5": "\"\"\"\ncontains generic code for use in main menus. currently this is a function which turns dictionaries of functions\ninto a menu. I envision any further menu functions being stored here so don't expect it to run like a pipeline but\nrather like a suite of individual menus.\n\nTODO - refactor spider selection function as jesus christ that things fat\n - incorporate spider selector in config manager options\n\"\"\"\nimport re\nimport os\nimport json\nfrom datetime import date, datetime\nfrom collections import defaultdict\nimport pandas as pd\nfrom HousingPriceScraper.HousingPriceScraper.functions.basic_functions import return_false, end_process, \\\n alphabet_list_length, flatten_list_of_lists\nfrom HousingPriceScraper.HousingPriceScraper.functions.data_management import save_list_to_txt\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean\n :return: dict_of_options but with a new, final key added in\n \"\"\"\n if back:\n dict_of_options['back'] = return_false\n else:\n dict_of_options['end_process'] = end_process\n return dict_of_options\n\n\ndef basic_menu(dict_of_options, back=False):\n \"\"\"\n basic text based user interface, allows user to select a function to run from a dictionary of options, by using a\n simple numeric code. User will see this dictionaries keys enumerated on screen to choose from.\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as values. It is important\n that these functions don't require parameters.\n :param back: boolean. choose between scrolling back to previous menu or ending the process entirely. defaults to\n ending process since that's how the main menu does it and unsure of where else function will be called\n :return: run the chosen function\n \"\"\"\n choose = True\n dict_of_options = final_option(dict_of_options, back)\n list_of_options = list(dict_of_options.keys())\n\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n pick = input('\\nType the numeric code you wish to run\\n\\n')\n if pick in [str(i) for i in range((len(dict_of_options)))]:\n choose = dict_of_options[list_of_options[int(pick)]]()\n else:\n print('{} is not currently an option!\\n'.format(pick))\n\n\ndef basic_menu_non_functional(list_of_options):\n \"\"\"\n basic text based user interface, allows user to select multiple options from a list of available choices.\n\n :param list_of_options: list of available choices\n :return: a list of chosen strings\n \"\"\"\n choose = True\n list_of_options.append('back')\n\n while choose:\n print('The following options are available:\\n')\n for option in enumerate(list_of_options):\n print('\\t{} - {}'.format(option[0], option[1]))\n picks = input('\\nType the numeric codes you wish to run\\n\\n').split(',')\n choice = []\n if str(len(list_of_options)) in picks:\n return True\n for pick in picks:\n if pick in [str(i) for i in range((len(list_of_options)))]:\n choice.append(list_of_options[int(pick)])\n else:\n print('{} is not currently an option!\\n'.format(pick))\n if len(choice) > 0:\n return choice\n\n\ndef select_spiders(spiders_dict):\n \"\"\"\n select from spiders available. allows user to select all spiders, select all spiders within a\n project group, select some comma separated list of individual/groups of spiders, or by prefixing a\n given selection with \"-\", the user can remove a spider from his or her selection.\n\n :param spiders_dict: dictionary who's keys are broad options and values are lists of spiders\n :return: list containing the spiders the user has selected to run\n \"\"\"\n print('Available spiders include:\\n')\n enumerated_keys = list(enumerate(spiders_dict.keys()))\n for key_group in enumerated_keys:\n print('{} - {}'.format(key_group[0], key_group[1]))\n for spider in zip(alphabet_list_length(len(key_group[1])), spiders_dict[key_group[1]]):\n print('\\t{}{} - {}'.format(key_group[0], spider[0], spider[1].name))\n print('{} - run all'.format(len(spiders_dict.keys())))\n print('{} - back'.format(len(spiders_dict.keys())+1))\n choices = input('\\nfor multiple, comma separate. To remove, use \"-\" prefix\\ni.e.: 0,-0a to run all of group 0 except the first\\n').replace(' ', '').split(',')\n if str(len(spiders_dict.keys())+1) in choices:\n return False\n if str(len(spiders_dict.keys())) in choices:\n chosen_spiders = list(spiders_dict.values())\n else:\n chosen_spiders = []\n for choice in choices:\n if choice.isdigit():\n if choice in [str(i[0]) for i in enumerated_keys]:\n chosen_spiders.append(spiders_dict[enumerated_keys[int(choice)][1]])\n else:\n print('{} is not an option!'.format(choice))\n elif '-' not in choice:\n numeric = re.findall(r'\\d+', choice)\n if len(numeric) == 1:\n alpha = choice.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha))-1\n try:\n chosen_spiders.append(spiders_dict[enumerated_keys[int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(choice))\n else:\n print('{} is not an option!'.format(choice))\n if any(isinstance(el, list) for el in chosen_spiders):\n chosen_spiders = flatten_list_of_lists(chosen_spiders, make_set=True)\n else:\n chosen_spiders = list(set(chosen_spiders))\n to_remove = [choice for choice in choices if '-' in choice]\n if len(to_remove) > 0:\n for removee in to_remove:\n if removee.replace('-', '').isdigit():\n if removee.replace('-', '') in [str(i[0]) for i in enumerated_keys]:\n for spider in spiders_dict[enumerated_keys[int(removee.replace('-', ''))][1]]:\n chosen_spiders.remove(spider)\n else:\n print('{} is not an option!'.format(removee))\n else:\n numeric = re.findall(r'\\d+', removee)\n if len(numeric) == 1:\n alpha = removee.split(numeric[0])[1]\n alpha = len(alphabet_list_length(0, index=alpha)) - 1\n try:\n chosen_spiders.remove(spiders_dict[enumerated_keys[int(numeric[0])][1]][alpha])\n except IndexError:\n print('{} is not an option!'.format(removee))\n else:\n print('{} is not an option!'.format(removee))\n if len(chosen_spiders) > 0:\n return chosen_spiders\n else:\n print(\"You haven't selected any spiders!\")\n return False\n\n\ndef project_visibility_menu():\n \"\"\"\n creates menu to allow user to set which project groups are visible in the run_scrapers menu\n\n :return: creates a txt file containing the list of desired project names, one per row.\n \"\"\"\n projects = [i.split('.')[0] for i in os.listdir('HousingPriceScraper/HousingPriceScraper/spiders/SpiderGroups')[:-1]]\n print('Available projects are:\\n')\n for project in enumerate(projects):\n print('\\t{} - {}'.format(project[0], project[1]))\n print('\\t{} - back'.format(len(projects)))\n choices = input('\\nType the options you wish to select.\\nFor multiple, comma separate\\n\\n').split(',')\n if str(len(projects)) in choices:\n return True\n else:\n choice_list = []\n for choice in choices:\n if choice.isdigit() and int(choice) in range(len(projects)):\n choice_list.append(projects[int(choice)])\n print('You have selected to display the following spider groupings:\\n\\t{}\\n'.format(choice_list))\n save_list_to_txt(choice_list, 'HousingPriceScraper/HousingPriceScraper/configs/visible_projects_to_scrape.txt')\n return True\n\n\ndef set_config():\n \"\"\"\n menu to set the url configs.\n\n :return: will set the start_urls of the spiders.\n \"\"\"\n available_configs = open('HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt', 'r')\n options = available_configs.readlines()\n options_dict = {}\n print('available configs include:\\n')\n for option in enumerate(options):\n options_dict[option[0]] = option[1].split(':')[0]\n print('\\t{} - {}'.format(option[0], option[1].replace('\\n', '')))\n print('\\t{} - back'.format(len(options)))\n chosen = input('\\ncomma separate for multiple\\n').split(',')\n if (str(len(options)) in chosen) or (chosen == ['']):\n return True\n configs = []\n for choice in chosen:\n if int(choice) in options_dict:\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'.format(options_dict[int(choice)])) as f:\n configs.append(json.load(f))\n final_config = defaultdict(list)\n for config in configs:\n for key, value in config.items():\n if key in final_config:\n final_config[key] += value\n else:\n final_config[key] = value\n for key, value in final_config.items():\n if any(isinstance(val, list) for val in value):\n final_config[key] = flatten_list_of_lists(value, make_set=True)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json:\n default_dict = json.load(default_urls_json)\n for key, value in default_dict.items():\n if key not in final_config.keys():\n final_config[key] = value\n with open('HousingPriceScraper/HousingPriceScraper/configs/chosen_urls.json', 'w') as fp:\n json.dump(final_config, fp, sort_keys=True, indent=4)\n return True\n\n\ndef append_recent_urls():\n \"\"\"\n function for appending recent scraped urls to default urls json\n\n :return: default.json is updated\n \"\"\"\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict.setdefault(key, []).extend(value)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json', 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef replace_default_urls():\n \"\"\"\n function for replacing default urls config with recent scrapes\n\n :return: defaults.json is updated\n \"\"\"\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json') as default_urls_json:\n default_dict = json.load(default_urls_json)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key, value in recent_dict.items():\n default_dict[key] = value\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/defaults.json', 'w') as fp:\n json.dump(default_dict, fp, sort_keys=True, indent=4)\n\n\ndef create_new_config():\n \"\"\"\n function which creates a whole new config file to store recent scraped urls in\n\n :return: new config is created\n \"\"\"\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:\n urls_dict = json.load(recent_urls_json)\n config_name = input('Type a name for the new config file:\\n').replace(' ', '_').replace(':', '')\n config_desc = input('Type a brief description for the new config file:\\n')\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/{}.json'.format(config_name), 'w') as fp:\n json.dump(urls_dict, fp, sort_keys=True, indent=4)\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_url_config_descriptions.txt', 'a') as input_descs:\n input_descs.write('\\n{}: {}'.format(config_name, config_desc))\n print('\\nSuccessfully saved recently scraped urls to new config: {}.json'.format(config_name))\n\n\ndef clear_recent_urls():\n \"\"\"\n function which bleaches the recent urls config in order to start fresh next time\n\n :return: recent_urls will become an empty dictionary.\n \"\"\"\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json') as recent_urls_json:\n recent_dict = json.load(recent_urls_json)\n for key in recent_dict.keys():\n recent_dict[key] = []\n with open('HousingPriceScraper/HousingPriceScraper/configs/input_urls/recent_urls.json', 'w') as fp:\n json.dump(recent_dict, fp, sort_keys=True, indent=4)\n\n\ndef select_date_interval_menu():\n \"\"\"\n function allows user to inout start and end date to define an interval of dates\n\n :return: list of dates\n \"\"\"\n while True:\n start_date = input('\\nInput desired start date with format dd-mm-yyyy:\\n')\n try:\n start_date = datetime.strptime(start_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid start date selected')\n while True:\n end_date = input('\\nInput desired start date with format dd-mm-yyyy,\\nor hit enter to select todays date\\n')\n if end_date == '':\n end_date = date.today()\n break\n else:\n try:\n end_date = datetime.strptime(end_date, '%d-%m-%Y')\n break\n except ValueError:\n print('invalid end date selected')\n list_of_dates = pd.date_range(start_date, end_date, freq='d')\n list_of_dates = [i.strftime('%d%m%Y') for i in list_of_dates]\n return list_of_dates\n", "step-ids": [ 8, 10, 11, 12, 13 ] }
[ 8, 10, 11, 12, 13 ]
<|reserved_special_token_0|> class Post(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __str__(self): return self.title class User(models.Model): id = models.CharField(max_length=30, primary_key='true') password = models.CharField(max_length=50) reg_date = models.DateField(default=timezone.now) upt_date = models.DateField(default=timezone.now) last_pwd = models.CharField(max_length=50) def chg_password(self): self.last_pwd = self.password self.save() def __id__(self): return self.id <|reserved_special_token_1|> <|reserved_special_token_0|> class Post(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class User(models.Model): id = models.CharField(max_length=30, primary_key='true') password = models.CharField(max_length=50) reg_date = models.DateField(default=timezone.now) upt_date = models.DateField(default=timezone.now) last_pwd = models.CharField(max_length=50) def chg_password(self): self.last_pwd = self.password self.save() def __id__(self): return self.id <|reserved_special_token_1|> <|reserved_special_token_0|> class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class User(models.Model): id = models.CharField(max_length=30, primary_key='true') password = models.CharField(max_length=50) reg_date = models.DateField(default=timezone.now) upt_date = models.DateField(default=timezone.now) last_pwd = models.CharField(max_length=50) def chg_password(self): self.last_pwd = self.password self.save() def __id__(self): return self.id <|reserved_special_token_1|> from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class User(models.Model): id = models.CharField(max_length=30, primary_key='true') password = models.CharField(max_length=50) reg_date = models.DateField(default=timezone.now) upt_date = models.DateField(default=timezone.now) last_pwd = models.CharField(max_length=50) def chg_password(self): self.last_pwd = self.password self.save() def __id__(self): return self.id <|reserved_special_token_1|> from django.db import models # db에 있는 models을 가져옴 from django.utils import timezone # 유틸에 있는 timezone을 가져옴 # Create your models here. class Post(models.Model): # Post라는 객체를 정의함 인수로 장고모델을 가져왔음 # 장고모델이기 때문에 데이터베이스에 저장된다. author = models.ForeignKey('auth.User') # 외래키, 다른 객체에 대한 링크 title = models.CharField(max_length=200) # 글자수 제한 text = models.TextField() # 글자수제한없음 created_date = models.DateTimeField(default=timezone.now) # Date형식 published_date = models.DateTimeField(blank=True, null=True) def publish(self): # 파이썬의 메소드 self.published_date = timezone.now() self.save() def __str__(self): return self.title class User(models.Model): id = models.CharField(max_length=30, primary_key='true') password = models.CharField(max_length=50) reg_date = models.DateField(default=timezone.now) upt_date = models.DateField(default=timezone.now) last_pwd = models.CharField(max_length=50) def chg_password(self): self.last_pwd = self.password self.save() def __id__(self): return self.id
flexible
{ "blob_id": "3aa8c9b39174f0ed5799d6991516b34ca669b7d6", "index": 9765, "step-1": "<mask token>\n\n\nclass Post(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n", "step-2": "<mask token>\n\n\nclass Post(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def publish(self):\n self.published_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n", "step-3": "<mask token>\n\n\nclass Post(models.Model):\n author = models.ForeignKey('auth.User')\n title = models.CharField(max_length=200)\n text = models.TextField()\n created_date = models.DateTimeField(default=timezone.now)\n published_date = models.DateTimeField(blank=True, null=True)\n\n def publish(self):\n self.published_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n", "step-4": "from django.db import models\nfrom django.utils import timezone\n\n\nclass Post(models.Model):\n author = models.ForeignKey('auth.User')\n title = models.CharField(max_length=200)\n text = models.TextField()\n created_date = models.DateTimeField(default=timezone.now)\n published_date = models.DateTimeField(blank=True, null=True)\n\n def publish(self):\n self.published_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n", "step-5": "from django.db import models # db에 있는 models을 가져옴\nfrom django.utils import timezone # 유틸에 있는 timezone을 가져옴\n\n\n# Create your models here.\n\nclass Post(models.Model):\n # Post라는 객체를 정의함 인수로 장고모델을 가져왔음\n # 장고모델이기 때문에 데이터베이스에 저장된다.\n author = models.ForeignKey('auth.User') # 외래키, 다른 객체에 대한 링크\n title = models.CharField(max_length=200) # 글자수 제한\n text = models.TextField() # 글자수제한없음\n created_date = models.DateTimeField(default=timezone.now) # Date형식\n published_date = models.DateTimeField(blank=True, null=True)\n\n def publish(self): # 파이썬의 메소드\n self.published_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.title\n\n\nclass User(models.Model):\n id = models.CharField(max_length=30, primary_key='true')\n password = models.CharField(max_length=50)\n reg_date = models.DateField(default=timezone.now)\n upt_date = models.DateField(default=timezone.now)\n last_pwd = models.CharField(max_length=50)\n\n def chg_password(self):\n self.last_pwd = self.password\n self.save()\n\n def __id__(self):\n return self.id\n\n", "step-ids": [ 6, 7, 8, 9, 10 ] }
[ 6, 7, 8, 9, 10 ]
<|reserved_special_token_0|> class Button: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def read_button(self): self.status = GPIO.input(self.button_pin) def light(self, stat): if stat: GPIO.output(self.LED_pin, 1) else: GPIO.output(self.LED_pin, 0) def cleanup(self): GPIO.cleanup() <|reserved_special_token_1|> <|reserved_special_token_0|> class Button: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __init__(self): self.status = True GPIO.setmode(GPIO.BCM) GPIO.setup(self.LED_pin, GPIO.OUT) self.status = get_button(self.button_pin) def read_button(self): self.status = GPIO.input(self.button_pin) def light(self, stat): if stat: GPIO.output(self.LED_pin, 1) else: GPIO.output(self.LED_pin, 0) def cleanup(self): GPIO.cleanup() <|reserved_special_token_1|> <|reserved_special_token_0|> class Button: status = bool() LED_pin = 25 button_pin = 23 def __init__(self): self.status = True GPIO.setmode(GPIO.BCM) GPIO.setup(self.LED_pin, GPIO.OUT) self.status = get_button(self.button_pin) def read_button(self): self.status = GPIO.input(self.button_pin) def light(self, stat): if stat: GPIO.output(self.LED_pin, 1) else: GPIO.output(self.LED_pin, 0) def cleanup(self): GPIO.cleanup() <|reserved_special_token_1|> <|reserved_special_token_0|> import RPi.GPIO as GPIO from aiy.voicehat import * class Button: status = bool() LED_pin = 25 button_pin = 23 def __init__(self): self.status = True GPIO.setmode(GPIO.BCM) GPIO.setup(self.LED_pin, GPIO.OUT) self.status = get_button(self.button_pin) def read_button(self): self.status = GPIO.input(self.button_pin) def light(self, stat): if stat: GPIO.output(self.LED_pin, 1) else: GPIO.output(self.LED_pin, 0) def cleanup(self): GPIO.cleanup() <|reserved_special_token_1|> ''' This module is used for handling the button. ''' import RPi.GPIO as GPIO from aiy.voicehat import * class Button: status = bool() #status indicates whether it is supposed to be on or off. LED_pin = 25 #Pin for the LED in the button in the Google AIY kit. button_pin = 23#The button is handled through the Google AIY lib because that one might actually work. def __init__(self): self.status = True GPIO.setmode(GPIO.BCM) GPIO.setup(self.LED_pin , GPIO.OUT) self.status = get_button(self.button_pin) def read_button(self): self.status = GPIO.input(self.button_pin) #Turns on the button light as prompted def light(self, stat): if (stat): GPIO.output(self.LED_pin, 1) else: GPIO.output(self.LED_pin, 0) def cleanup(self): GPIO.cleanup()
flexible
{ "blob_id": "878937e19d6a48a0d44309efbac1d41c208ce849", "index": 6195, "step-1": "<mask token>\n\n\nclass Button:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def read_button(self):\n self.status = GPIO.input(self.button_pin)\n\n def light(self, stat):\n if stat:\n GPIO.output(self.LED_pin, 1)\n else:\n GPIO.output(self.LED_pin, 0)\n\n def cleanup(self):\n GPIO.cleanup()\n", "step-2": "<mask token>\n\n\nclass Button:\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self):\n self.status = True\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(self.LED_pin, GPIO.OUT)\n self.status = get_button(self.button_pin)\n\n def read_button(self):\n self.status = GPIO.input(self.button_pin)\n\n def light(self, stat):\n if stat:\n GPIO.output(self.LED_pin, 1)\n else:\n GPIO.output(self.LED_pin, 0)\n\n def cleanup(self):\n GPIO.cleanup()\n", "step-3": "<mask token>\n\n\nclass Button:\n status = bool()\n LED_pin = 25\n button_pin = 23\n\n def __init__(self):\n self.status = True\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(self.LED_pin, GPIO.OUT)\n self.status = get_button(self.button_pin)\n\n def read_button(self):\n self.status = GPIO.input(self.button_pin)\n\n def light(self, stat):\n if stat:\n GPIO.output(self.LED_pin, 1)\n else:\n GPIO.output(self.LED_pin, 0)\n\n def cleanup(self):\n GPIO.cleanup()\n", "step-4": "<mask token>\nimport RPi.GPIO as GPIO\nfrom aiy.voicehat import *\n\n\nclass Button:\n status = bool()\n LED_pin = 25\n button_pin = 23\n\n def __init__(self):\n self.status = True\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(self.LED_pin, GPIO.OUT)\n self.status = get_button(self.button_pin)\n\n def read_button(self):\n self.status = GPIO.input(self.button_pin)\n\n def light(self, stat):\n if stat:\n GPIO.output(self.LED_pin, 1)\n else:\n GPIO.output(self.LED_pin, 0)\n\n def cleanup(self):\n GPIO.cleanup()\n", "step-5": "'''\nThis module is used for handling the button. \n'''\nimport RPi.GPIO as GPIO\nfrom aiy.voicehat import *\n\nclass Button:\n status = bool() #status indicates whether it is supposed to be on or off. \n LED_pin = 25 #Pin for the LED in the button in the Google AIY kit. \n button_pin = 23#The button is handled through the Google AIY lib because that one might actually work. \n \n def __init__(self):\n self.status = True\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(self.LED_pin , GPIO.OUT)\n self.status = get_button(self.button_pin)\n \n def read_button(self):\n self.status = GPIO.input(self.button_pin)\n \n #Turns on the button light as prompted\n def light(self, stat):\n if (stat):\n GPIO.output(self.LED_pin, 1)\n else:\n GPIO.output(self.LED_pin, 0)\n \n def cleanup(self):\n GPIO.cleanup()", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
import os from flask import Flask, request, redirect, url_for, render_template, send_from_directory from werkzeug.utils import secure_filename import chardet as chardet import pandas as pd UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/' DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/' ALLOWED_EXTENSIONS = {'csv', 'txt'} app = Flask(__name__, static_url_path="/static") DIR_PATH = os.path.dirname(os.path.realpath(__file__)) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER # limit upload size upto 8mb app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024 def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return redirect(request.url) file = request.files['file'] if file.filename == '': print('No file selected') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), filename) return redirect(url_for('uploaded_file', filename=filename)) return render_template('index.html') def process_file(path, filename): check_encoding(path, filename) # with open(path, 'a') as f: # f.write("\nAdded processed content") def check_encoding(path, filename): with open(path, 'rb') as rawdata: result = chardet.detect(rawdata.read(10000)) df = pd.read_csv(path, encoding=result['encoding']) GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit('.', 1)[0] + '.xlsx') df.to_excel(GFG, index=False, encoding='utf-8') #output_stream = open(app.config['DOWNLOAD_FOLDER'] + 'output.xlsx', 'wb') #GFG.write(output_stream) GFG.save() @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.rsplit('.', 1)[0] + '.xlsx', as_attachment=True) if __name__ == '__main__': port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
normal
{ "blob_id": "eb17de8828a600832253c4cfeeb91503b6876dd7", "index": 9963, "step-1": "<mask token>\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename\n ), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit(\n '.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n GFG.save()\n\n\n@app.route('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename\n ), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit(\n '.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n GFG.save()\n\n\n@app.route('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n", "step-3": "<mask token>\nUPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'\nDOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'\nALLOWED_EXTENSIONS = {'csv', 'txt'}\napp = Flask(__name__, static_url_path='/static')\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename\n ), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit(\n '.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n GFG.save()\n\n\n@app.route('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n", "step-4": "import os\nfrom flask import Flask, request, redirect, url_for, render_template, send_from_directory\nfrom werkzeug.utils import secure_filename\nimport chardet as chardet\nimport pandas as pd\nUPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'\nDOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'\nALLOWED_EXTENSIONS = {'csv', 'txt'}\napp = Flask(__name__, static_url_path='/static')\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename\n ), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit(\n '.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n GFG.save()\n\n\n@app.route('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.\n rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n", "step-5": "import os\nfrom flask import Flask, request, redirect, url_for, render_template, send_from_directory\nfrom werkzeug.utils import secure_filename\nimport chardet as chardet\nimport pandas as pd\n\nUPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'\nDOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'\nALLOWED_EXTENSIONS = {'csv', 'txt'}\n\napp = Flask(__name__, static_url_path=\"/static\")\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER\n# limit upload size upto 8mb\napp.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n if 'file' not in request.files:\n print('No file attached in request')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n print('No file selected')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), filename)\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('index.html')\n\n\ndef process_file(path, filename):\n check_encoding(path, filename)\n # with open(path, 'a') as f:\n # f.write(\"\\nAdded processed content\")\n\n\ndef check_encoding(path, filename):\n with open(path, 'rb') as rawdata:\n result = chardet.detect(rawdata.read(10000))\n df = pd.read_csv(path, encoding=result['encoding'])\n GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit('.', 1)[0] + '.xlsx')\n df.to_excel(GFG, index=False, encoding='utf-8')\n #output_stream = open(app.config['DOWNLOAD_FOLDER'] + 'output.xlsx', 'wb')\n #GFG.write(output_stream)\n GFG.save()\n\n \n\n@app.route('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.rsplit('.', 1)[0] + '.xlsx', as_attachment=True)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
<|reserved_special_token_0|> class SQLiteConnection(ConnectionBackend): <|reserved_special_token_0|> <|reserved_special_token_0|> async def connect(self): self.db = await aiosqlite.connect(self.db_name) self.db.row_factory = aiosqlite.Row async def disconnect(self): await self.db.close() async def execute(self, query: Query): q = self._compile(query) await self.db.execute(q['query'], q['values']) async def fetch(self, query: Query) ->Dict[str, Any]: q = self._compile(query) cursor = await self.db.execute(q['query'], q['values']) res = await cursor.fetchone() await cursor.close() return dict(res) async def fetch_all(self, query: Query) ->List[Dict[str, Any]]: q = self._compile(query) cursor = await self.db.execute(q['query'], q['values']) res = await cursor.fetchall() await cursor.close() return [dict(r) for r in res] def transaction(self) ->'TransactionBackend': return SQLiteTransaction(self) class SQLiteTransaction(TransactionBackend): async def start(self): return async def commit(self): await self._connection.database.commit() async def rollback(self): await self._connection.database.rollback() <|reserved_special_token_1|> <|reserved_special_token_0|> class SQLiteConnection(ConnectionBackend): <|reserved_special_token_0|> @staticmethod def _compile(query: Query) ->dict: q = query.statement v = [] if query.placeholders: for p in query.placeholders: v.append(query.values[p.replace('$', '')]) q = re.sub(f'\\{p}', '?', q) return {'query': q, 'values': v} async def connect(self): self.db = await aiosqlite.connect(self.db_name) self.db.row_factory = aiosqlite.Row async def disconnect(self): await self.db.close() async def execute(self, query: Query): q = self._compile(query) await self.db.execute(q['query'], q['values']) async def fetch(self, query: Query) ->Dict[str, Any]: q = self._compile(query) cursor = await self.db.execute(q['query'], q['values']) res = await cursor.fetchone() await cursor.close() return dict(res) async def fetch_all(self, query: Query) ->List[Dict[str, Any]]: q = self._compile(query) cursor = await self.db.execute(q['query'], q['values']) res = await cursor.fetchall() await cursor.close() return [dict(r) for r in res] def transaction(self) ->'TransactionBackend': return SQLiteTransaction(self) class SQLiteTransaction(TransactionBackend): async def start(self): return async def commit(self): await self._connection.database.commit() async def rollback(self): await self._connection.database.rollback() <|reserved_special_token_1|> <|reserved_special_token_0|> class SQLiteConnection(ConnectionBackend): _dialect = 'sqlite' @staticmethod def _compile(query: Query) ->dict: q = query.statement v = [] if query.placeholders: for p in query.placeholders: v.append(query.values[p.replace('$', '')]) q = re.sub(f'\\{p}', '?', q) return {'query': q, 'values': v} async def connect(self): self.db = await aiosqlite.connect(self.db_name) self.db.row_factory = aiosqlite.Row async def disconnect(self): await self.db.close() async def execute(self, query: Query): q = self._compile(query) await self.db.execute(q['query'], q['values']) async def fetch(self, query: Query) ->Dict[str, Any]: q = self._compile(query) cursor = await self.db.execute(q['query'], q['values']) res = await cursor.fetchone() await cursor.close() return dict(res) async def fetch_all(self, query: Query) ->List[Dict[str, Any]]: q = self._compile(query) cursor = await self.db.execute(q['query'], q['values']) res = await cursor.fetchall() await cursor.close() return [dict(r) for r in res] def transaction(self) ->'TransactionBackend': return SQLiteTransaction(self) class SQLiteTransaction(TransactionBackend): async def start(self): return async def commit(self): await self._connection.database.commit() async def rollback(self): await self._connection.database.rollback() <|reserved_special_token_1|> import re from typing import Any, Dict, List import aiosqlite from migri.elements import Query from migri.interfaces import ConnectionBackend, TransactionBackend class SQLiteConnection(ConnectionBackend): _dialect = 'sqlite' @staticmethod def _compile(query: Query) ->dict: q = query.statement v = [] if query.placeholders: for p in query.placeholders: v.append(query.values[p.replace('$', '')]) q = re.sub(f'\\{p}', '?', q) return {'query': q, 'values': v} async def connect(self): self.db = await aiosqlite.connect(self.db_name) self.db.row_factory = aiosqlite.Row async def disconnect(self): await self.db.close() async def execute(self, query: Query): q = self._compile(query) await self.db.execute(q['query'], q['values']) async def fetch(self, query: Query) ->Dict[str, Any]: q = self._compile(query) cursor = await self.db.execute(q['query'], q['values']) res = await cursor.fetchone() await cursor.close() return dict(res) async def fetch_all(self, query: Query) ->List[Dict[str, Any]]: q = self._compile(query) cursor = await self.db.execute(q['query'], q['values']) res = await cursor.fetchall() await cursor.close() return [dict(r) for r in res] def transaction(self) ->'TransactionBackend': return SQLiteTransaction(self) class SQLiteTransaction(TransactionBackend): async def start(self): return async def commit(self): await self._connection.database.commit() async def rollback(self): await self._connection.database.rollback() <|reserved_special_token_1|> import re from typing import Any, Dict, List import aiosqlite from migri.elements import Query from migri.interfaces import ConnectionBackend, TransactionBackend class SQLiteConnection(ConnectionBackend): _dialect = "sqlite" @staticmethod def _compile(query: Query) -> dict: q = query.statement v = [] if query.placeholders: for p in query.placeholders: # Append value v.append(query.values[p.replace("$", "")]) # Substitute q = re.sub(f"\\{p}", "?", q) return {"query": q, "values": v} async def connect(self): self.db = await aiosqlite.connect(self.db_name) self.db.row_factory = aiosqlite.Row async def disconnect(self): await self.db.close() async def execute(self, query: Query): q = self._compile(query) await self.db.execute(q["query"], q["values"]) async def fetch(self, query: Query) -> Dict[str, Any]: q = self._compile(query) cursor = await self.db.execute(q["query"], q["values"]) res = await cursor.fetchone() await cursor.close() return dict(res) async def fetch_all(self, query: Query) -> List[Dict[str, Any]]: q = self._compile(query) cursor = await self.db.execute(q["query"], q["values"]) res = await cursor.fetchall() await cursor.close() return [dict(r) for r in res] def transaction(self) -> "TransactionBackend": return SQLiteTransaction(self) class SQLiteTransaction(TransactionBackend): async def start(self): # Nothing to do return async def commit(self): await self._connection.database.commit() async def rollback(self): await self._connection.database.rollback()
flexible
{ "blob_id": "191a57d3f13fcbe217ff6d0bd92dea163d5fb3cf", "index": 4822, "step-1": "<mask token>\n\n\nclass SQLiteConnection(ConnectionBackend):\n <mask token>\n <mask token>\n\n async def connect(self):\n self.db = await aiosqlite.connect(self.db_name)\n self.db.row_factory = aiosqlite.Row\n\n async def disconnect(self):\n await self.db.close()\n\n async def execute(self, query: Query):\n q = self._compile(query)\n await self.db.execute(q['query'], q['values'])\n\n async def fetch(self, query: Query) ->Dict[str, Any]:\n q = self._compile(query)\n cursor = await self.db.execute(q['query'], q['values'])\n res = await cursor.fetchone()\n await cursor.close()\n return dict(res)\n\n async def fetch_all(self, query: Query) ->List[Dict[str, Any]]:\n q = self._compile(query)\n cursor = await self.db.execute(q['query'], q['values'])\n res = await cursor.fetchall()\n await cursor.close()\n return [dict(r) for r in res]\n\n def transaction(self) ->'TransactionBackend':\n return SQLiteTransaction(self)\n\n\nclass SQLiteTransaction(TransactionBackend):\n\n async def start(self):\n return\n\n async def commit(self):\n await self._connection.database.commit()\n\n async def rollback(self):\n await self._connection.database.rollback()\n", "step-2": "<mask token>\n\n\nclass SQLiteConnection(ConnectionBackend):\n <mask token>\n\n @staticmethod\n def _compile(query: Query) ->dict:\n q = query.statement\n v = []\n if query.placeholders:\n for p in query.placeholders:\n v.append(query.values[p.replace('$', '')])\n q = re.sub(f'\\\\{p}', '?', q)\n return {'query': q, 'values': v}\n\n async def connect(self):\n self.db = await aiosqlite.connect(self.db_name)\n self.db.row_factory = aiosqlite.Row\n\n async def disconnect(self):\n await self.db.close()\n\n async def execute(self, query: Query):\n q = self._compile(query)\n await self.db.execute(q['query'], q['values'])\n\n async def fetch(self, query: Query) ->Dict[str, Any]:\n q = self._compile(query)\n cursor = await self.db.execute(q['query'], q['values'])\n res = await cursor.fetchone()\n await cursor.close()\n return dict(res)\n\n async def fetch_all(self, query: Query) ->List[Dict[str, Any]]:\n q = self._compile(query)\n cursor = await self.db.execute(q['query'], q['values'])\n res = await cursor.fetchall()\n await cursor.close()\n return [dict(r) for r in res]\n\n def transaction(self) ->'TransactionBackend':\n return SQLiteTransaction(self)\n\n\nclass SQLiteTransaction(TransactionBackend):\n\n async def start(self):\n return\n\n async def commit(self):\n await self._connection.database.commit()\n\n async def rollback(self):\n await self._connection.database.rollback()\n", "step-3": "<mask token>\n\n\nclass SQLiteConnection(ConnectionBackend):\n _dialect = 'sqlite'\n\n @staticmethod\n def _compile(query: Query) ->dict:\n q = query.statement\n v = []\n if query.placeholders:\n for p in query.placeholders:\n v.append(query.values[p.replace('$', '')])\n q = re.sub(f'\\\\{p}', '?', q)\n return {'query': q, 'values': v}\n\n async def connect(self):\n self.db = await aiosqlite.connect(self.db_name)\n self.db.row_factory = aiosqlite.Row\n\n async def disconnect(self):\n await self.db.close()\n\n async def execute(self, query: Query):\n q = self._compile(query)\n await self.db.execute(q['query'], q['values'])\n\n async def fetch(self, query: Query) ->Dict[str, Any]:\n q = self._compile(query)\n cursor = await self.db.execute(q['query'], q['values'])\n res = await cursor.fetchone()\n await cursor.close()\n return dict(res)\n\n async def fetch_all(self, query: Query) ->List[Dict[str, Any]]:\n q = self._compile(query)\n cursor = await self.db.execute(q['query'], q['values'])\n res = await cursor.fetchall()\n await cursor.close()\n return [dict(r) for r in res]\n\n def transaction(self) ->'TransactionBackend':\n return SQLiteTransaction(self)\n\n\nclass SQLiteTransaction(TransactionBackend):\n\n async def start(self):\n return\n\n async def commit(self):\n await self._connection.database.commit()\n\n async def rollback(self):\n await self._connection.database.rollback()\n", "step-4": "import re\nfrom typing import Any, Dict, List\nimport aiosqlite\nfrom migri.elements import Query\nfrom migri.interfaces import ConnectionBackend, TransactionBackend\n\n\nclass SQLiteConnection(ConnectionBackend):\n _dialect = 'sqlite'\n\n @staticmethod\n def _compile(query: Query) ->dict:\n q = query.statement\n v = []\n if query.placeholders:\n for p in query.placeholders:\n v.append(query.values[p.replace('$', '')])\n q = re.sub(f'\\\\{p}', '?', q)\n return {'query': q, 'values': v}\n\n async def connect(self):\n self.db = await aiosqlite.connect(self.db_name)\n self.db.row_factory = aiosqlite.Row\n\n async def disconnect(self):\n await self.db.close()\n\n async def execute(self, query: Query):\n q = self._compile(query)\n await self.db.execute(q['query'], q['values'])\n\n async def fetch(self, query: Query) ->Dict[str, Any]:\n q = self._compile(query)\n cursor = await self.db.execute(q['query'], q['values'])\n res = await cursor.fetchone()\n await cursor.close()\n return dict(res)\n\n async def fetch_all(self, query: Query) ->List[Dict[str, Any]]:\n q = self._compile(query)\n cursor = await self.db.execute(q['query'], q['values'])\n res = await cursor.fetchall()\n await cursor.close()\n return [dict(r) for r in res]\n\n def transaction(self) ->'TransactionBackend':\n return SQLiteTransaction(self)\n\n\nclass SQLiteTransaction(TransactionBackend):\n\n async def start(self):\n return\n\n async def commit(self):\n await self._connection.database.commit()\n\n async def rollback(self):\n await self._connection.database.rollback()\n", "step-5": "import re\nfrom typing import Any, Dict, List\n\nimport aiosqlite\n\nfrom migri.elements import Query\nfrom migri.interfaces import ConnectionBackend, TransactionBackend\n\n\nclass SQLiteConnection(ConnectionBackend):\n _dialect = \"sqlite\"\n\n @staticmethod\n def _compile(query: Query) -> dict:\n q = query.statement\n v = []\n\n if query.placeholders:\n for p in query.placeholders:\n # Append value\n v.append(query.values[p.replace(\"$\", \"\")])\n\n # Substitute\n q = re.sub(f\"\\\\{p}\", \"?\", q)\n\n return {\"query\": q, \"values\": v}\n\n async def connect(self):\n self.db = await aiosqlite.connect(self.db_name)\n self.db.row_factory = aiosqlite.Row\n\n async def disconnect(self):\n await self.db.close()\n\n async def execute(self, query: Query):\n q = self._compile(query)\n await self.db.execute(q[\"query\"], q[\"values\"])\n\n async def fetch(self, query: Query) -> Dict[str, Any]:\n q = self._compile(query)\n cursor = await self.db.execute(q[\"query\"], q[\"values\"])\n res = await cursor.fetchone()\n await cursor.close()\n\n return dict(res)\n\n async def fetch_all(self, query: Query) -> List[Dict[str, Any]]:\n q = self._compile(query)\n cursor = await self.db.execute(q[\"query\"], q[\"values\"])\n res = await cursor.fetchall()\n await cursor.close()\n\n return [dict(r) for r in res]\n\n def transaction(self) -> \"TransactionBackend\":\n return SQLiteTransaction(self)\n\n\nclass SQLiteTransaction(TransactionBackend):\n async def start(self):\n # Nothing to do\n return\n\n async def commit(self):\n await self._connection.database.commit()\n\n async def rollback(self):\n await self._connection.database.rollback()\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> while no != 0: r = no % 10 no = no // 10 rev = rev * 10 + r print('reverse no is:', rev) <|reserved_special_token_1|> no = int(input('enter no:')) rev = 0 while no != 0: r = no % 10 no = no // 10 rev = rev * 10 + r print('reverse no is:', rev) <|reserved_special_token_1|> no=int(input("enter no:")) rev=0 while no!=0: r=no%10 no=no//10 rev=rev*10+r print("reverse no is:",rev)
flexible
{ "blob_id": "b2371f9c774c605a52ff1a4fae2dd44a856076aa", "index": 5522, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile no != 0:\n r = no % 10\n no = no // 10\n rev = rev * 10 + r\nprint('reverse no is:', rev)\n", "step-3": "no = int(input('enter no:'))\nrev = 0\nwhile no != 0:\n r = no % 10\n no = no // 10\n rev = rev * 10 + r\nprint('reverse no is:', rev)\n", "step-4": "no=int(input(\"enter no:\"))\nrev=0\nwhile no!=0:\n r=no%10\n no=no//10\n rev=rev*10+r\nprint(\"reverse no is:\",rev)\n ", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> def process_std(standard_input_file): try: with open(standard_input_file, 'r') as in_handle: lin_reg_lst = [] for line in in_handle: line = line.strip('\n') lin_reg_lst.append(line) except IOError: print('Could not open ' + standard_input_file + ' for reading.') quit(1) return lin_reg_lst <|reserved_special_token_0|> def abs_to_subconc(meas_df, info_dict, m, c): for sample in info_dict.keys(): for well in info_dict[sample]['wells']: i = np.where(meas_df == well) for row in meas_df[i[0]]: count = 1 for el in row: if type(el) != str: conc = (el - c) / m meas_df[i[0], count] = conc count += 1 return meas_df <|reserved_special_token_0|> def act_calc(meas_df, info_dict, b_m, std_m, std_c): act_dict = {} while True: print('How many time intervals you want to take for the ' + 'analysis? (most linear part from first to x)') m_lin = input() if m_lin.isnumeric() == True and int(m_lin) > 1: break m_lin = int(m_lin) while True: print('What is the volume per well? (in µL)') well_v = input() print('\n') if well_v.isnumeric() == True: break time = np.where(meas_df == 'Time [s]') if len(time[0]) == 0: m_arr = [] time = np.where(meas_df == 'Time [ms]') for row in meas_df[time[0]]: arr = [] count = 1 for el in row: if type(el) != str: sec = el * 0.001 arr.append(sec) count += 1 m_arr.append(arr) x = np.vstack(m_arr) av_lst = [] for row in np.transpose(x): av = sum(row) / len(row) av_lst.append(av) x = np.transpose(np.array(av_lst[0:m_lin])) else: x = meas_df[time[0]] x = np.array(x[0, 1:m_lin + 1]) for sample in info_dict.keys(): e_conc = info_dict[sample]['conc'] e_dil = info_dict[sample]['dil'] e_conc = float(e_conc) / (float(e_dil) * 1000) for well in info_dict[sample]['wells']: i = np.where(meas_df == well) y = meas_df[i[0]] y = np.array(y[0, 1:m_lin + 1]) m, c, r, p, stderr = stats.linregress(x.astype(float), y.astype (float)) print(sample + ' >R²' + str(r)) plt.figure(1, figsize=[10, 5], frameon=False) plt.plot(x, y, 'x', markersize=2, label=sample) plt.plot(x, m * x + c, 'r', linestyle='--', color='gray') plt.savefig('activity_plot.png') m = abs(m - b_m) sact = m * 60 * int(well_v) / (10 * 1000000 * float(e_conc)) act_dict.setdefault(sample, []) act_dict[sample].append(sact) summery_dict = {} summery_dict['interval'] = m_lin for sample in act_dict.keys(): av_sact = sum(act_dict[sample]) / len(act_dict[sample]) print('average specific activity of ' + sample + ' = ' + str( av_sact) + ' U/mg') std = np.std(act_dict[sample]) print('standard deviation for ' + sample + ': +/-' + str(std)) summery_dict[sample] = {'av_sact': av_sact, 'std': std} return summery_dict <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def process_std(standard_input_file): try: with open(standard_input_file, 'r') as in_handle: lin_reg_lst = [] for line in in_handle: line = line.strip('\n') lin_reg_lst.append(line) except IOError: print('Could not open ' + standard_input_file + ' for reading.') quit(1) return lin_reg_lst def process_info(info_file): try: info_dict = {} with open(info_file, 'r') as in_handle: for line in in_handle: line = line.strip() items = re.split(' ', line) well_lst = re.split(',', items[1]) info_dict[items[0]] = {'wells': well_lst, 'conc': float( items[2]), 'dil': float(items[3])} except IOError: print('Could not open ' + args.info + ' for reading.') quit(1) return info_dict def abs_to_subconc(meas_df, info_dict, m, c): for sample in info_dict.keys(): for well in info_dict[sample]['wells']: i = np.where(meas_df == well) for row in meas_df[i[0]]: count = 1 for el in row: if type(el) != str: conc = (el - c) / m meas_df[i[0], count] = conc count += 1 return meas_df <|reserved_special_token_0|> def act_calc(meas_df, info_dict, b_m, std_m, std_c): act_dict = {} while True: print('How many time intervals you want to take for the ' + 'analysis? (most linear part from first to x)') m_lin = input() if m_lin.isnumeric() == True and int(m_lin) > 1: break m_lin = int(m_lin) while True: print('What is the volume per well? (in µL)') well_v = input() print('\n') if well_v.isnumeric() == True: break time = np.where(meas_df == 'Time [s]') if len(time[0]) == 0: m_arr = [] time = np.where(meas_df == 'Time [ms]') for row in meas_df[time[0]]: arr = [] count = 1 for el in row: if type(el) != str: sec = el * 0.001 arr.append(sec) count += 1 m_arr.append(arr) x = np.vstack(m_arr) av_lst = [] for row in np.transpose(x): av = sum(row) / len(row) av_lst.append(av) x = np.transpose(np.array(av_lst[0:m_lin])) else: x = meas_df[time[0]] x = np.array(x[0, 1:m_lin + 1]) for sample in info_dict.keys(): e_conc = info_dict[sample]['conc'] e_dil = info_dict[sample]['dil'] e_conc = float(e_conc) / (float(e_dil) * 1000) for well in info_dict[sample]['wells']: i = np.where(meas_df == well) y = meas_df[i[0]] y = np.array(y[0, 1:m_lin + 1]) m, c, r, p, stderr = stats.linregress(x.astype(float), y.astype (float)) print(sample + ' >R²' + str(r)) plt.figure(1, figsize=[10, 5], frameon=False) plt.plot(x, y, 'x', markersize=2, label=sample) plt.plot(x, m * x + c, 'r', linestyle='--', color='gray') plt.savefig('activity_plot.png') m = abs(m - b_m) sact = m * 60 * int(well_v) / (10 * 1000000 * float(e_conc)) act_dict.setdefault(sample, []) act_dict[sample].append(sact) summery_dict = {} summery_dict['interval'] = m_lin for sample in act_dict.keys(): av_sact = sum(act_dict[sample]) / len(act_dict[sample]) print('average specific activity of ' + sample + ' = ' + str( av_sact) + ' U/mg') std = np.std(act_dict[sample]) print('standard deviation for ' + sample + ': +/-' + str(std)) summery_dict[sample] = {'av_sact': av_sact, 'std': std} return summery_dict <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def process_std(standard_input_file): try: with open(standard_input_file, 'r') as in_handle: lin_reg_lst = [] for line in in_handle: line = line.strip('\n') lin_reg_lst.append(line) except IOError: print('Could not open ' + standard_input_file + ' for reading.') quit(1) return lin_reg_lst def process_info(info_file): try: info_dict = {} with open(info_file, 'r') as in_handle: for line in in_handle: line = line.strip() items = re.split(' ', line) well_lst = re.split(',', items[1]) info_dict[items[0]] = {'wells': well_lst, 'conc': float( items[2]), 'dil': float(items[3])} except IOError: print('Could not open ' + args.info + ' for reading.') quit(1) return info_dict def abs_to_subconc(meas_df, info_dict, m, c): for sample in info_dict.keys(): for well in info_dict[sample]['wells']: i = np.where(meas_df == well) for row in meas_df[i[0]]: count = 1 for el in row: if type(el) != str: conc = (el - c) / m meas_df[i[0], count] = conc count += 1 return meas_df def process_blank(blank_file, std_m, std_c): blank_df = pd.read_csv(blank_file) blank_df = blank_df.to_numpy() i = np.where(blank_df == 'Time [s]') if len(i[0]) == 0: b_arr = [] i = np.where(blank_df == 'Time [ms]') for row in blank_df[i[0]]: count = 1 arr = [] for el in row: if type(el) != str: sec = el * 0.001 arr.append(sec) count += 1 b_arr.append(arr) blank_x = np.vstack(b_arr) av_lst = [] for row in np.transpose(blank_x): av = sum(row) / len(row) av_lst.append(av) blank_x = np.transpose(np.array(av_lst)) else: blank_x = np.array(blank_df[i[0]][0, 1:]) arr = [] for row in blank_df: if re.search('^[A-Z]\\d\\d?$', row[0]): arr.append(row[1:]) if len(arr) < 2: blank_arr = np.array(arr) else: blank_arr = np.vstack(arr) count_r = 0 for row in blank_arr: count_c = 0 for el in row: if type(el) != str: conc = (el - std_c) / std_m blank_arr[count_r, count_c] = conc count_c += 1 count_r += 1 av_lst = [] for row in np.transpose(blank_arr): av = sum(row) / len(row) av_lst.append(av) if len(av_lst) < 2: blank_y = np.transpose(np.array(av_lst)) else: blank_y = np.transpose(np.vstack(av_lst)) b_m, b_c, b_r, b_p, stderr = stats.linregress(blank_x.astype(float), blank_y.astype(float)) return b_m def act_calc(meas_df, info_dict, b_m, std_m, std_c): act_dict = {} while True: print('How many time intervals you want to take for the ' + 'analysis? (most linear part from first to x)') m_lin = input() if m_lin.isnumeric() == True and int(m_lin) > 1: break m_lin = int(m_lin) while True: print('What is the volume per well? (in µL)') well_v = input() print('\n') if well_v.isnumeric() == True: break time = np.where(meas_df == 'Time [s]') if len(time[0]) == 0: m_arr = [] time = np.where(meas_df == 'Time [ms]') for row in meas_df[time[0]]: arr = [] count = 1 for el in row: if type(el) != str: sec = el * 0.001 arr.append(sec) count += 1 m_arr.append(arr) x = np.vstack(m_arr) av_lst = [] for row in np.transpose(x): av = sum(row) / len(row) av_lst.append(av) x = np.transpose(np.array(av_lst[0:m_lin])) else: x = meas_df[time[0]] x = np.array(x[0, 1:m_lin + 1]) for sample in info_dict.keys(): e_conc = info_dict[sample]['conc'] e_dil = info_dict[sample]['dil'] e_conc = float(e_conc) / (float(e_dil) * 1000) for well in info_dict[sample]['wells']: i = np.where(meas_df == well) y = meas_df[i[0]] y = np.array(y[0, 1:m_lin + 1]) m, c, r, p, stderr = stats.linregress(x.astype(float), y.astype (float)) print(sample + ' >R²' + str(r)) plt.figure(1, figsize=[10, 5], frameon=False) plt.plot(x, y, 'x', markersize=2, label=sample) plt.plot(x, m * x + c, 'r', linestyle='--', color='gray') plt.savefig('activity_plot.png') m = abs(m - b_m) sact = m * 60 * int(well_v) / (10 * 1000000 * float(e_conc)) act_dict.setdefault(sample, []) act_dict[sample].append(sact) summery_dict = {} summery_dict['interval'] = m_lin for sample in act_dict.keys(): av_sact = sum(act_dict[sample]) / len(act_dict[sample]) print('average specific activity of ' + sample + ' = ' + str( av_sact) + ' U/mg') std = np.std(act_dict[sample]) print('standard deviation for ' + sample + ': +/-' + str(std)) summery_dict[sample] = {'av_sact': av_sact, 'std': std} return summery_dict <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def process_std(standard_input_file): try: with open(standard_input_file, 'r') as in_handle: lin_reg_lst = [] for line in in_handle: line = line.strip('\n') lin_reg_lst.append(line) except IOError: print('Could not open ' + standard_input_file + ' for reading.') quit(1) return lin_reg_lst def process_info(info_file): try: info_dict = {} with open(info_file, 'r') as in_handle: for line in in_handle: line = line.strip() items = re.split(' ', line) well_lst = re.split(',', items[1]) info_dict[items[0]] = {'wells': well_lst, 'conc': float( items[2]), 'dil': float(items[3])} except IOError: print('Could not open ' + args.info + ' for reading.') quit(1) return info_dict def abs_to_subconc(meas_df, info_dict, m, c): for sample in info_dict.keys(): for well in info_dict[sample]['wells']: i = np.where(meas_df == well) for row in meas_df[i[0]]: count = 1 for el in row: if type(el) != str: conc = (el - c) / m meas_df[i[0], count] = conc count += 1 return meas_df def process_blank(blank_file, std_m, std_c): blank_df = pd.read_csv(blank_file) blank_df = blank_df.to_numpy() i = np.where(blank_df == 'Time [s]') if len(i[0]) == 0: b_arr = [] i = np.where(blank_df == 'Time [ms]') for row in blank_df[i[0]]: count = 1 arr = [] for el in row: if type(el) != str: sec = el * 0.001 arr.append(sec) count += 1 b_arr.append(arr) blank_x = np.vstack(b_arr) av_lst = [] for row in np.transpose(blank_x): av = sum(row) / len(row) av_lst.append(av) blank_x = np.transpose(np.array(av_lst)) else: blank_x = np.array(blank_df[i[0]][0, 1:]) arr = [] for row in blank_df: if re.search('^[A-Z]\\d\\d?$', row[0]): arr.append(row[1:]) if len(arr) < 2: blank_arr = np.array(arr) else: blank_arr = np.vstack(arr) count_r = 0 for row in blank_arr: count_c = 0 for el in row: if type(el) != str: conc = (el - std_c) / std_m blank_arr[count_r, count_c] = conc count_c += 1 count_r += 1 av_lst = [] for row in np.transpose(blank_arr): av = sum(row) / len(row) av_lst.append(av) if len(av_lst) < 2: blank_y = np.transpose(np.array(av_lst)) else: blank_y = np.transpose(np.vstack(av_lst)) b_m, b_c, b_r, b_p, stderr = stats.linregress(blank_x.astype(float), blank_y.astype(float)) return b_m def act_calc(meas_df, info_dict, b_m, std_m, std_c): act_dict = {} while True: print('How many time intervals you want to take for the ' + 'analysis? (most linear part from first to x)') m_lin = input() if m_lin.isnumeric() == True and int(m_lin) > 1: break m_lin = int(m_lin) while True: print('What is the volume per well? (in µL)') well_v = input() print('\n') if well_v.isnumeric() == True: break time = np.where(meas_df == 'Time [s]') if len(time[0]) == 0: m_arr = [] time = np.where(meas_df == 'Time [ms]') for row in meas_df[time[0]]: arr = [] count = 1 for el in row: if type(el) != str: sec = el * 0.001 arr.append(sec) count += 1 m_arr.append(arr) x = np.vstack(m_arr) av_lst = [] for row in np.transpose(x): av = sum(row) / len(row) av_lst.append(av) x = np.transpose(np.array(av_lst[0:m_lin])) else: x = meas_df[time[0]] x = np.array(x[0, 1:m_lin + 1]) for sample in info_dict.keys(): e_conc = info_dict[sample]['conc'] e_dil = info_dict[sample]['dil'] e_conc = float(e_conc) / (float(e_dil) * 1000) for well in info_dict[sample]['wells']: i = np.where(meas_df == well) y = meas_df[i[0]] y = np.array(y[0, 1:m_lin + 1]) m, c, r, p, stderr = stats.linregress(x.astype(float), y.astype (float)) print(sample + ' >R²' + str(r)) plt.figure(1, figsize=[10, 5], frameon=False) plt.plot(x, y, 'x', markersize=2, label=sample) plt.plot(x, m * x + c, 'r', linestyle='--', color='gray') plt.savefig('activity_plot.png') m = abs(m - b_m) sact = m * 60 * int(well_v) / (10 * 1000000 * float(e_conc)) act_dict.setdefault(sample, []) act_dict[sample].append(sact) summery_dict = {} summery_dict['interval'] = m_lin for sample in act_dict.keys(): av_sact = sum(act_dict[sample]) / len(act_dict[sample]) print('average specific activity of ' + sample + ' = ' + str( av_sact) + ' U/mg') std = np.std(act_dict[sample]) print('standard deviation for ' + sample + ': +/-' + str(std)) summery_dict[sample] = {'av_sact': av_sact, 'std': std} return summery_dict def gen_output(summery_dict, name): try: with open(name + '_activity.out', 'w') as out_handle: out_handle.write('time interval from 1. to ' + str(summery_dict ['interval']) + """. was used for calculations. """) for sample in summery_dict.keys(): if sample == 'interval': continue else: out_handle.write(str(sample) + ': s = ' + str( summery_dict[sample]['av_sact']) + ' +/- ' + str( summery_dict[sample]['std']) + '\n') except IOError: print('Could not open activity.out for writing.') quit(1) <|reserved_special_token_1|> ############################## Import Modules ################################## import pandas as pd import numpy as np import re from scipy import stats import matplotlib.pyplot as plt ############################## Define Functions ################################ # generate list containing data of standard curve def process_std(standard_input_file): try: with open(standard_input_file, 'r') as in_handle: lin_reg_lst = [] for line in in_handle: line = line.strip('\n') lin_reg_lst.append(line) except IOError: print("Could not open " + standard_input_file + " for reading.") quit(1) return lin_reg_lst # generate info_dict containing information about the samples def process_info(info_file): try: info_dict = {} with open(info_file, 'r') as in_handle: for line in in_handle: line = line.strip() items = re.split(' ', line) well_lst = re.split(',', items[1]) info_dict[items[0]] = {'wells': well_lst, 'conc': float(items[2]), 'dil': float(items[3])} except IOError: print("Could not open " + args.info + " for reading.") quit(1) return info_dict # calculate substrate concentration from absorption values def abs_to_subconc(meas_df, info_dict, m, c): # find data series belonging to a sample for sample in info_dict.keys(): for well in info_dict[sample]['wells']: i = np.where(meas_df == well) # convert absorption values to substrate concentration for row in meas_df[i[0]]: count = 1 for el in row: if type(el) != str: conc = (el - c)/m meas_df[i[0], count] = conc count += 1 return meas_df # process blank to get slope def process_blank(blank_file, std_m, std_c): blank_df = pd.read_csv(blank_file) blank_df = blank_df.to_numpy() # define x values i = np.where(blank_df == 'Time [s]') # fall-back for case that time per well is measured if len(i[0]) == 0: b_arr = [] i = np.where(blank_df == 'Time [ms]') # convert ms to s for row in blank_df[i[0]]: count = 1 arr = [] for el in row: if type(el) != str: sec = el*0.001 arr.append(sec) count += 1 b_arr.append(arr) blank_x = np.vstack(b_arr) # make average for time av_lst = [] for row in np.transpose(blank_x): av = sum(row) / len(row) av_lst.append(av) blank_x = np.transpose(np.array(av_lst)) else: blank_x = np.array(blank_df[i[0]][0, 1:]) # define y values arr = [] for row in blank_df: if re.search(r'^[A-Z]\d\d?$', row[0]): arr.append(row[1:]) if len(arr) < 2: blank_arr = np.array(arr) else: blank_arr = np.vstack(arr) count_r = 0 for row in blank_arr: count_c = 0 for el in row: if type(el) != str: conc = (el - std_c)/std_m blank_arr[count_r, count_c] = conc count_c += 1 count_r += 1 av_lst = [] for row in np.transpose(blank_arr): av = sum(row) / len(row) av_lst.append(av) if len(av_lst) < 2: blank_y = np.transpose(np.array(av_lst)) else: blank_y = np.transpose(np.vstack(av_lst)) b_m, b_c, b_r, b_p, stderr = stats.linregress(blank_x.astype(float), blank_y.astype(float)) return b_m # calculate average activity and standard deviation of each sample def act_calc(meas_df, info_dict, b_m, std_m, std_c): act_dict = {} # m_lin defines most linear part from first point while True: print("How many time intervals you want to take for the " + "analysis? (most linear part from first to x)") m_lin = input() if m_lin.isnumeric() == True and int(m_lin) > 1: break m_lin = int(m_lin) # define volume per well while True: print("What is the volume per well? (in µL)") well_v = input() print("\n") if well_v.isnumeric() == True: break # define x values time = np.where(meas_df == 'Time [s]') # fall-back for case that time per well is measured if len(time[0]) == 0: m_arr = [] time = np.where(meas_df == 'Time [ms]') # convert ms to s for row in meas_df[time[0]]: arr = [] count = 1 for el in row: if type(el) != str: sec = el*0.001 arr.append(sec) count += 1 m_arr.append(arr) x = np.vstack(m_arr) # make average for time values av_lst = [] for row in np.transpose(x): av = sum(row) / len(row) av_lst.append(av) x = np.transpose(np.array(av_lst[0:m_lin])) else: x = meas_df[time[0]] x = np.array(x[0, 1:m_lin + 1]) # process sample data for sample in info_dict.keys(): e_conc = info_dict[sample]['conc'] e_dil = info_dict[sample]['dil'] e_conc = float(e_conc)/ (float(e_dil)*1000) for well in info_dict[sample]['wells']: i = np.where(meas_df == well) y = meas_df[i[0]] y = np.array(y[0, 1:m_lin + 1]) m, c, r, p, stderr = stats.linregress(x.astype(float), y.astype(float)) print(sample + ' >R²' + str(r)) # plot substrate decrease plt.figure(1, figsize=[10,5], frameon=False) plt.plot(x, y, 'x', markersize=2, label=sample) plt.plot(x, m*x + c, 'r', linestyle='--', color='gray') plt.savefig('activity_plot.png') # calculate specific activity m = abs(m - b_m) sact = (m*60*int(well_v)) / (10*1000000*float(e_conc)) act_dict.setdefault(sample, []) act_dict[sample].append(sact) # calculate average specific activity per sample summery_dict = {} summery_dict['interval'] = m_lin for sample in act_dict.keys(): av_sact = sum(act_dict[sample]) / len(act_dict[sample]) print("average specific activity of " + sample + " = " + str(av_sact) + " U/mg") # calculate standard deviation per sample std = np.std(act_dict[sample]) print("standard deviation for " + sample + ": +/-" + str(std)) # generate summery_dict for output file summery_dict[sample] = {'av_sact': av_sact, 'std': std} return summery_dict # process summery_dict to generate output file def gen_output(summery_dict, name): try: with open(name + '_activity.out', 'w') as out_handle: out_handle.write('time interval from 1. to ' + str(summery_dict['interval']) + '. was used for calculations.\n') for sample in summery_dict.keys(): if sample == 'interval': continue else: out_handle.write(str(sample) + ': s = ' + str(summery_dict[sample]['av_sact']) + ' +/- ' + str(summery_dict[sample]['std']) + '\n') except IOError: print("Could not open activity.out for writing.") quit(1)
flexible
{ "blob_id": "19949b07c866d66b3ef00b6a386bf89f03e06294", "index": 7984, "step-1": "<mask token>\n\n\ndef process_std(standard_input_file):\n try:\n with open(standard_input_file, 'r') as in_handle:\n lin_reg_lst = []\n for line in in_handle:\n line = line.strip('\\n')\n lin_reg_lst.append(line)\n except IOError:\n print('Could not open ' + standard_input_file + ' for reading.')\n quit(1)\n return lin_reg_lst\n\n\n<mask token>\n\n\ndef abs_to_subconc(meas_df, info_dict, m, c):\n for sample in info_dict.keys():\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n for row in meas_df[i[0]]:\n count = 1\n for el in row:\n if type(el) != str:\n conc = (el - c) / m\n meas_df[i[0], count] = conc\n count += 1\n return meas_df\n\n\n<mask token>\n\n\ndef act_calc(meas_df, info_dict, b_m, std_m, std_c):\n act_dict = {}\n while True:\n print('How many time intervals you want to take for the ' +\n 'analysis? (most linear part from first to x)')\n m_lin = input()\n if m_lin.isnumeric() == True and int(m_lin) > 1:\n break\n m_lin = int(m_lin)\n while True:\n print('What is the volume per well? (in µL)')\n well_v = input()\n print('\\n')\n if well_v.isnumeric() == True:\n break\n time = np.where(meas_df == 'Time [s]')\n if len(time[0]) == 0:\n m_arr = []\n time = np.where(meas_df == 'Time [ms]')\n for row in meas_df[time[0]]:\n arr = []\n count = 1\n for el in row:\n if type(el) != str:\n sec = el * 0.001\n arr.append(sec)\n count += 1\n m_arr.append(arr)\n x = np.vstack(m_arr)\n av_lst = []\n for row in np.transpose(x):\n av = sum(row) / len(row)\n av_lst.append(av)\n x = np.transpose(np.array(av_lst[0:m_lin]))\n else:\n x = meas_df[time[0]]\n x = np.array(x[0, 1:m_lin + 1])\n for sample in info_dict.keys():\n e_conc = info_dict[sample]['conc']\n e_dil = info_dict[sample]['dil']\n e_conc = float(e_conc) / (float(e_dil) * 1000)\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n y = meas_df[i[0]]\n y = np.array(y[0, 1:m_lin + 1])\n m, c, r, p, stderr = stats.linregress(x.astype(float), y.astype\n (float))\n print(sample + ' >R²' + str(r))\n plt.figure(1, figsize=[10, 5], frameon=False)\n plt.plot(x, y, 'x', markersize=2, label=sample)\n plt.plot(x, m * x + c, 'r', linestyle='--', color='gray')\n plt.savefig('activity_plot.png')\n m = abs(m - b_m)\n sact = m * 60 * int(well_v) / (10 * 1000000 * float(e_conc))\n act_dict.setdefault(sample, [])\n act_dict[sample].append(sact)\n summery_dict = {}\n summery_dict['interval'] = m_lin\n for sample in act_dict.keys():\n av_sact = sum(act_dict[sample]) / len(act_dict[sample])\n print('average specific activity of ' + sample + ' = ' + str(\n av_sact) + ' U/mg')\n std = np.std(act_dict[sample])\n print('standard deviation for ' + sample + ': +/-' + str(std))\n summery_dict[sample] = {'av_sact': av_sact, 'std': std}\n return summery_dict\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef process_std(standard_input_file):\n try:\n with open(standard_input_file, 'r') as in_handle:\n lin_reg_lst = []\n for line in in_handle:\n line = line.strip('\\n')\n lin_reg_lst.append(line)\n except IOError:\n print('Could not open ' + standard_input_file + ' for reading.')\n quit(1)\n return lin_reg_lst\n\n\ndef process_info(info_file):\n try:\n info_dict = {}\n with open(info_file, 'r') as in_handle:\n for line in in_handle:\n line = line.strip()\n items = re.split(' ', line)\n well_lst = re.split(',', items[1])\n info_dict[items[0]] = {'wells': well_lst, 'conc': float(\n items[2]), 'dil': float(items[3])}\n except IOError:\n print('Could not open ' + args.info + ' for reading.')\n quit(1)\n return info_dict\n\n\ndef abs_to_subconc(meas_df, info_dict, m, c):\n for sample in info_dict.keys():\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n for row in meas_df[i[0]]:\n count = 1\n for el in row:\n if type(el) != str:\n conc = (el - c) / m\n meas_df[i[0], count] = conc\n count += 1\n return meas_df\n\n\n<mask token>\n\n\ndef act_calc(meas_df, info_dict, b_m, std_m, std_c):\n act_dict = {}\n while True:\n print('How many time intervals you want to take for the ' +\n 'analysis? (most linear part from first to x)')\n m_lin = input()\n if m_lin.isnumeric() == True and int(m_lin) > 1:\n break\n m_lin = int(m_lin)\n while True:\n print('What is the volume per well? (in µL)')\n well_v = input()\n print('\\n')\n if well_v.isnumeric() == True:\n break\n time = np.where(meas_df == 'Time [s]')\n if len(time[0]) == 0:\n m_arr = []\n time = np.where(meas_df == 'Time [ms]')\n for row in meas_df[time[0]]:\n arr = []\n count = 1\n for el in row:\n if type(el) != str:\n sec = el * 0.001\n arr.append(sec)\n count += 1\n m_arr.append(arr)\n x = np.vstack(m_arr)\n av_lst = []\n for row in np.transpose(x):\n av = sum(row) / len(row)\n av_lst.append(av)\n x = np.transpose(np.array(av_lst[0:m_lin]))\n else:\n x = meas_df[time[0]]\n x = np.array(x[0, 1:m_lin + 1])\n for sample in info_dict.keys():\n e_conc = info_dict[sample]['conc']\n e_dil = info_dict[sample]['dil']\n e_conc = float(e_conc) / (float(e_dil) * 1000)\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n y = meas_df[i[0]]\n y = np.array(y[0, 1:m_lin + 1])\n m, c, r, p, stderr = stats.linregress(x.astype(float), y.astype\n (float))\n print(sample + ' >R²' + str(r))\n plt.figure(1, figsize=[10, 5], frameon=False)\n plt.plot(x, y, 'x', markersize=2, label=sample)\n plt.plot(x, m * x + c, 'r', linestyle='--', color='gray')\n plt.savefig('activity_plot.png')\n m = abs(m - b_m)\n sact = m * 60 * int(well_v) / (10 * 1000000 * float(e_conc))\n act_dict.setdefault(sample, [])\n act_dict[sample].append(sact)\n summery_dict = {}\n summery_dict['interval'] = m_lin\n for sample in act_dict.keys():\n av_sact = sum(act_dict[sample]) / len(act_dict[sample])\n print('average specific activity of ' + sample + ' = ' + str(\n av_sact) + ' U/mg')\n std = np.std(act_dict[sample])\n print('standard deviation for ' + sample + ': +/-' + str(std))\n summery_dict[sample] = {'av_sact': av_sact, 'std': std}\n return summery_dict\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef process_std(standard_input_file):\n try:\n with open(standard_input_file, 'r') as in_handle:\n lin_reg_lst = []\n for line in in_handle:\n line = line.strip('\\n')\n lin_reg_lst.append(line)\n except IOError:\n print('Could not open ' + standard_input_file + ' for reading.')\n quit(1)\n return lin_reg_lst\n\n\ndef process_info(info_file):\n try:\n info_dict = {}\n with open(info_file, 'r') as in_handle:\n for line in in_handle:\n line = line.strip()\n items = re.split(' ', line)\n well_lst = re.split(',', items[1])\n info_dict[items[0]] = {'wells': well_lst, 'conc': float(\n items[2]), 'dil': float(items[3])}\n except IOError:\n print('Could not open ' + args.info + ' for reading.')\n quit(1)\n return info_dict\n\n\ndef abs_to_subconc(meas_df, info_dict, m, c):\n for sample in info_dict.keys():\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n for row in meas_df[i[0]]:\n count = 1\n for el in row:\n if type(el) != str:\n conc = (el - c) / m\n meas_df[i[0], count] = conc\n count += 1\n return meas_df\n\n\ndef process_blank(blank_file, std_m, std_c):\n blank_df = pd.read_csv(blank_file)\n blank_df = blank_df.to_numpy()\n i = np.where(blank_df == 'Time [s]')\n if len(i[0]) == 0:\n b_arr = []\n i = np.where(blank_df == 'Time [ms]')\n for row in blank_df[i[0]]:\n count = 1\n arr = []\n for el in row:\n if type(el) != str:\n sec = el * 0.001\n arr.append(sec)\n count += 1\n b_arr.append(arr)\n blank_x = np.vstack(b_arr)\n av_lst = []\n for row in np.transpose(blank_x):\n av = sum(row) / len(row)\n av_lst.append(av)\n blank_x = np.transpose(np.array(av_lst))\n else:\n blank_x = np.array(blank_df[i[0]][0, 1:])\n arr = []\n for row in blank_df:\n if re.search('^[A-Z]\\\\d\\\\d?$', row[0]):\n arr.append(row[1:])\n if len(arr) < 2:\n blank_arr = np.array(arr)\n else:\n blank_arr = np.vstack(arr)\n count_r = 0\n for row in blank_arr:\n count_c = 0\n for el in row:\n if type(el) != str:\n conc = (el - std_c) / std_m\n blank_arr[count_r, count_c] = conc\n count_c += 1\n count_r += 1\n av_lst = []\n for row in np.transpose(blank_arr):\n av = sum(row) / len(row)\n av_lst.append(av)\n if len(av_lst) < 2:\n blank_y = np.transpose(np.array(av_lst))\n else:\n blank_y = np.transpose(np.vstack(av_lst))\n b_m, b_c, b_r, b_p, stderr = stats.linregress(blank_x.astype(float),\n blank_y.astype(float))\n return b_m\n\n\ndef act_calc(meas_df, info_dict, b_m, std_m, std_c):\n act_dict = {}\n while True:\n print('How many time intervals you want to take for the ' +\n 'analysis? (most linear part from first to x)')\n m_lin = input()\n if m_lin.isnumeric() == True and int(m_lin) > 1:\n break\n m_lin = int(m_lin)\n while True:\n print('What is the volume per well? (in µL)')\n well_v = input()\n print('\\n')\n if well_v.isnumeric() == True:\n break\n time = np.where(meas_df == 'Time [s]')\n if len(time[0]) == 0:\n m_arr = []\n time = np.where(meas_df == 'Time [ms]')\n for row in meas_df[time[0]]:\n arr = []\n count = 1\n for el in row:\n if type(el) != str:\n sec = el * 0.001\n arr.append(sec)\n count += 1\n m_arr.append(arr)\n x = np.vstack(m_arr)\n av_lst = []\n for row in np.transpose(x):\n av = sum(row) / len(row)\n av_lst.append(av)\n x = np.transpose(np.array(av_lst[0:m_lin]))\n else:\n x = meas_df[time[0]]\n x = np.array(x[0, 1:m_lin + 1])\n for sample in info_dict.keys():\n e_conc = info_dict[sample]['conc']\n e_dil = info_dict[sample]['dil']\n e_conc = float(e_conc) / (float(e_dil) * 1000)\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n y = meas_df[i[0]]\n y = np.array(y[0, 1:m_lin + 1])\n m, c, r, p, stderr = stats.linregress(x.astype(float), y.astype\n (float))\n print(sample + ' >R²' + str(r))\n plt.figure(1, figsize=[10, 5], frameon=False)\n plt.plot(x, y, 'x', markersize=2, label=sample)\n plt.plot(x, m * x + c, 'r', linestyle='--', color='gray')\n plt.savefig('activity_plot.png')\n m = abs(m - b_m)\n sact = m * 60 * int(well_v) / (10 * 1000000 * float(e_conc))\n act_dict.setdefault(sample, [])\n act_dict[sample].append(sact)\n summery_dict = {}\n summery_dict['interval'] = m_lin\n for sample in act_dict.keys():\n av_sact = sum(act_dict[sample]) / len(act_dict[sample])\n print('average specific activity of ' + sample + ' = ' + str(\n av_sact) + ' U/mg')\n std = np.std(act_dict[sample])\n print('standard deviation for ' + sample + ': +/-' + str(std))\n summery_dict[sample] = {'av_sact': av_sact, 'std': std}\n return summery_dict\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef process_std(standard_input_file):\n try:\n with open(standard_input_file, 'r') as in_handle:\n lin_reg_lst = []\n for line in in_handle:\n line = line.strip('\\n')\n lin_reg_lst.append(line)\n except IOError:\n print('Could not open ' + standard_input_file + ' for reading.')\n quit(1)\n return lin_reg_lst\n\n\ndef process_info(info_file):\n try:\n info_dict = {}\n with open(info_file, 'r') as in_handle:\n for line in in_handle:\n line = line.strip()\n items = re.split(' ', line)\n well_lst = re.split(',', items[1])\n info_dict[items[0]] = {'wells': well_lst, 'conc': float(\n items[2]), 'dil': float(items[3])}\n except IOError:\n print('Could not open ' + args.info + ' for reading.')\n quit(1)\n return info_dict\n\n\ndef abs_to_subconc(meas_df, info_dict, m, c):\n for sample in info_dict.keys():\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n for row in meas_df[i[0]]:\n count = 1\n for el in row:\n if type(el) != str:\n conc = (el - c) / m\n meas_df[i[0], count] = conc\n count += 1\n return meas_df\n\n\ndef process_blank(blank_file, std_m, std_c):\n blank_df = pd.read_csv(blank_file)\n blank_df = blank_df.to_numpy()\n i = np.where(blank_df == 'Time [s]')\n if len(i[0]) == 0:\n b_arr = []\n i = np.where(blank_df == 'Time [ms]')\n for row in blank_df[i[0]]:\n count = 1\n arr = []\n for el in row:\n if type(el) != str:\n sec = el * 0.001\n arr.append(sec)\n count += 1\n b_arr.append(arr)\n blank_x = np.vstack(b_arr)\n av_lst = []\n for row in np.transpose(blank_x):\n av = sum(row) / len(row)\n av_lst.append(av)\n blank_x = np.transpose(np.array(av_lst))\n else:\n blank_x = np.array(blank_df[i[0]][0, 1:])\n arr = []\n for row in blank_df:\n if re.search('^[A-Z]\\\\d\\\\d?$', row[0]):\n arr.append(row[1:])\n if len(arr) < 2:\n blank_arr = np.array(arr)\n else:\n blank_arr = np.vstack(arr)\n count_r = 0\n for row in blank_arr:\n count_c = 0\n for el in row:\n if type(el) != str:\n conc = (el - std_c) / std_m\n blank_arr[count_r, count_c] = conc\n count_c += 1\n count_r += 1\n av_lst = []\n for row in np.transpose(blank_arr):\n av = sum(row) / len(row)\n av_lst.append(av)\n if len(av_lst) < 2:\n blank_y = np.transpose(np.array(av_lst))\n else:\n blank_y = np.transpose(np.vstack(av_lst))\n b_m, b_c, b_r, b_p, stderr = stats.linregress(blank_x.astype(float),\n blank_y.astype(float))\n return b_m\n\n\ndef act_calc(meas_df, info_dict, b_m, std_m, std_c):\n act_dict = {}\n while True:\n print('How many time intervals you want to take for the ' +\n 'analysis? (most linear part from first to x)')\n m_lin = input()\n if m_lin.isnumeric() == True and int(m_lin) > 1:\n break\n m_lin = int(m_lin)\n while True:\n print('What is the volume per well? (in µL)')\n well_v = input()\n print('\\n')\n if well_v.isnumeric() == True:\n break\n time = np.where(meas_df == 'Time [s]')\n if len(time[0]) == 0:\n m_arr = []\n time = np.where(meas_df == 'Time [ms]')\n for row in meas_df[time[0]]:\n arr = []\n count = 1\n for el in row:\n if type(el) != str:\n sec = el * 0.001\n arr.append(sec)\n count += 1\n m_arr.append(arr)\n x = np.vstack(m_arr)\n av_lst = []\n for row in np.transpose(x):\n av = sum(row) / len(row)\n av_lst.append(av)\n x = np.transpose(np.array(av_lst[0:m_lin]))\n else:\n x = meas_df[time[0]]\n x = np.array(x[0, 1:m_lin + 1])\n for sample in info_dict.keys():\n e_conc = info_dict[sample]['conc']\n e_dil = info_dict[sample]['dil']\n e_conc = float(e_conc) / (float(e_dil) * 1000)\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n y = meas_df[i[0]]\n y = np.array(y[0, 1:m_lin + 1])\n m, c, r, p, stderr = stats.linregress(x.astype(float), y.astype\n (float))\n print(sample + ' >R²' + str(r))\n plt.figure(1, figsize=[10, 5], frameon=False)\n plt.plot(x, y, 'x', markersize=2, label=sample)\n plt.plot(x, m * x + c, 'r', linestyle='--', color='gray')\n plt.savefig('activity_plot.png')\n m = abs(m - b_m)\n sact = m * 60 * int(well_v) / (10 * 1000000 * float(e_conc))\n act_dict.setdefault(sample, [])\n act_dict[sample].append(sact)\n summery_dict = {}\n summery_dict['interval'] = m_lin\n for sample in act_dict.keys():\n av_sact = sum(act_dict[sample]) / len(act_dict[sample])\n print('average specific activity of ' + sample + ' = ' + str(\n av_sact) + ' U/mg')\n std = np.std(act_dict[sample])\n print('standard deviation for ' + sample + ': +/-' + str(std))\n summery_dict[sample] = {'av_sact': av_sact, 'std': std}\n return summery_dict\n\n\ndef gen_output(summery_dict, name):\n try:\n with open(name + '_activity.out', 'w') as out_handle:\n out_handle.write('time interval from 1. to ' + str(summery_dict\n ['interval']) + \"\"\". was used for calculations.\n\"\"\")\n for sample in summery_dict.keys():\n if sample == 'interval':\n continue\n else:\n out_handle.write(str(sample) + ': s = ' + str(\n summery_dict[sample]['av_sact']) + ' +/- ' + str(\n summery_dict[sample]['std']) + '\\n')\n except IOError:\n print('Could not open activity.out for writing.')\n quit(1)\n", "step-5": "############################## Import Modules ##################################\nimport pandas as pd\nimport numpy as np\nimport re\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n\n############################## Define Functions ################################\n# generate list containing data of standard curve\ndef process_std(standard_input_file):\n try:\n with open(standard_input_file, 'r') as in_handle:\n lin_reg_lst = []\n for line in in_handle:\n line = line.strip('\\n')\n lin_reg_lst.append(line)\n except IOError:\n print(\"Could not open \" + standard_input_file + \" for reading.\")\n quit(1)\n return lin_reg_lst\n\n# generate info_dict containing information about the samples\ndef process_info(info_file):\n try:\n info_dict = {}\n with open(info_file, 'r') as in_handle:\n for line in in_handle:\n line = line.strip()\n items = re.split(' ', line)\n well_lst = re.split(',', items[1])\n info_dict[items[0]] = {'wells': well_lst,\n 'conc': float(items[2]),\n 'dil': float(items[3])}\n except IOError:\n print(\"Could not open \" + args.info + \" for reading.\")\n quit(1)\n return info_dict\n\n# calculate substrate concentration from absorption values\ndef abs_to_subconc(meas_df, info_dict, m, c):\n # find data series belonging to a sample\n for sample in info_dict.keys():\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n # convert absorption values to substrate concentration\n for row in meas_df[i[0]]:\n count = 1\n for el in row:\n if type(el) != str:\n conc = (el - c)/m\n meas_df[i[0], count] = conc\n count += 1\n return meas_df\n\n# process blank to get slope\ndef process_blank(blank_file, std_m, std_c):\n blank_df = pd.read_csv(blank_file)\n blank_df = blank_df.to_numpy()\n # define x values\n i = np.where(blank_df == 'Time [s]')\n # fall-back for case that time per well is measured \n if len(i[0]) == 0:\n b_arr = []\n i = np.where(blank_df == 'Time [ms]')\n # convert ms to s\n for row in blank_df[i[0]]:\n count = 1\n arr = []\n for el in row:\n if type(el) != str:\n sec = el*0.001\n arr.append(sec)\n count += 1\n b_arr.append(arr)\n blank_x = np.vstack(b_arr)\n # make average for time\n av_lst = []\n for row in np.transpose(blank_x):\n av = sum(row) / len(row)\n av_lst.append(av)\n blank_x = np.transpose(np.array(av_lst))\n else:\n blank_x = np.array(blank_df[i[0]][0, 1:])\n # define y values\n arr = []\n for row in blank_df:\n if re.search(r'^[A-Z]\\d\\d?$', row[0]):\n arr.append(row[1:])\n if len(arr) < 2:\n blank_arr = np.array(arr)\n else:\n blank_arr = np.vstack(arr)\n count_r = 0\n for row in blank_arr:\n count_c = 0\n for el in row:\n if type(el) != str:\n conc = (el - std_c)/std_m\n blank_arr[count_r, count_c] = conc\n count_c += 1\n count_r += 1\n av_lst = []\n for row in np.transpose(blank_arr):\n av = sum(row) / len(row)\n av_lst.append(av)\n if len(av_lst) < 2:\n blank_y = np.transpose(np.array(av_lst))\n else:\n blank_y = np.transpose(np.vstack(av_lst))\n b_m, b_c, b_r, b_p, stderr = stats.linregress(blank_x.astype(float),\n blank_y.astype(float))\n return b_m\n\n# calculate average activity and standard deviation of each sample\ndef act_calc(meas_df, info_dict, b_m, std_m, std_c):\n act_dict = {}\n # m_lin defines most linear part from first point\n while True:\n print(\"How many time intervals you want to take for the \"\n + \"analysis? (most linear part from first to x)\")\n m_lin = input()\n if m_lin.isnumeric() == True and int(m_lin) > 1:\n break\n m_lin = int(m_lin)\n # define volume per well\n while True:\n print(\"What is the volume per well? (in µL)\")\n well_v = input()\n print(\"\\n\")\n if well_v.isnumeric() == True:\n break\n # define x values\n time = np.where(meas_df == 'Time [s]')\n # fall-back for case that time per well is measured \n if len(time[0]) == 0:\n m_arr = []\n time = np.where(meas_df == 'Time [ms]')\n # convert ms to s\n for row in meas_df[time[0]]:\n arr = []\n count = 1\n for el in row:\n if type(el) != str:\n sec = el*0.001\n arr.append(sec)\n count += 1\n m_arr.append(arr)\n x = np.vstack(m_arr)\n # make average for time values\n av_lst = []\n for row in np.transpose(x):\n av = sum(row) / len(row)\n av_lst.append(av)\n x = np.transpose(np.array(av_lst[0:m_lin]))\n else:\n x = meas_df[time[0]]\n x = np.array(x[0, 1:m_lin + 1])\n # process sample data\n for sample in info_dict.keys():\n e_conc = info_dict[sample]['conc']\n e_dil = info_dict[sample]['dil']\n e_conc = float(e_conc)/ (float(e_dil)*1000)\n for well in info_dict[sample]['wells']:\n i = np.where(meas_df == well)\n y = meas_df[i[0]]\n y = np.array(y[0, 1:m_lin + 1])\n m, c, r, p, stderr = stats.linregress(x.astype(float),\n y.astype(float))\n print(sample + ' >R²' + str(r))\n # plot substrate decrease\n plt.figure(1, figsize=[10,5], frameon=False)\n plt.plot(x, y, 'x', markersize=2, label=sample)\n plt.plot(x, m*x + c, 'r', linestyle='--', color='gray')\n plt.savefig('activity_plot.png')\n # calculate specific activity\n m = abs(m - b_m)\n sact = (m*60*int(well_v)) / (10*1000000*float(e_conc))\n act_dict.setdefault(sample, [])\n act_dict[sample].append(sact)\n # calculate average specific activity per sample\n summery_dict = {}\n summery_dict['interval'] = m_lin\n for sample in act_dict.keys():\n av_sact = sum(act_dict[sample]) / len(act_dict[sample])\n print(\"average specific activity of \" + sample + \" = \"\n + str(av_sact) + \" U/mg\")\n # calculate standard deviation per sample\n std = np.std(act_dict[sample])\n print(\"standard deviation for \" + sample + \": +/-\" + str(std))\n # generate summery_dict for output file\n summery_dict[sample] = {'av_sact': av_sact, 'std': std}\n return summery_dict\n\n# process summery_dict to generate output file\ndef gen_output(summery_dict, name):\n try:\n with open(name + '_activity.out', 'w') as out_handle:\n out_handle.write('time interval from 1. to '\n + str(summery_dict['interval'])\n + '. was used for calculations.\\n')\n for sample in summery_dict.keys():\n if sample == 'interval':\n continue\n else:\n out_handle.write(str(sample) + ': s = '\n + str(summery_dict[sample]['av_sact'])\n + ' +/- '\n + str(summery_dict[sample]['std']) + '\\n')\n except IOError:\n print(\"Could not open activity.out for writing.\")\n quit(1)\n", "step-ids": [ 3, 4, 5, 6, 8 ] }
[ 3, 4, 5, 6, 8 ]
# -*- coding: utf-8 -*- """ Created on Tue Oct 9 16:22:21 2018 @author: SDis """ #import Code.Members_module class Resources: """ Parent class for Books and eResources containg the main data fields and related setters and getters""" def __init__(self, title, author, publisher, year): self.title = title self.author = author self.publisher = publisher self.year = year #Setters def set_title (self, title): """Method that sets the title of a resource object""" self.title = title def set_author (self, author): """Method that sets the author of a resource object""" self.author = author def set_publisher (self, publisher): """Method that sets the publisher of a resource object""" self.publisher = publisher def set_year (self, year): """Method that sets the year of a resource object""" self.year = year #Getters def get_title(self): """Method that gets the title of a resource object""" return self.title def get_author(self): """Method that gets the author of a resource object""" return self.author def get_publisher(self): """Method that gets the publisher of a resource object""" return self.publisher def get_year(self): """Method that gets the year of a resource object""" return self.year def get_resource_details (self): """Method that returns the main details of a resource object""" return (f"[Title:\"{self.get_title()}\"] [Author:{self.get_author()}] [Publisher:{self.get_publisher()}] [Year:{self.get_year()}]")
normal
{ "blob_id": "0709d413ddbe41a0c97f94b7819fdfded241d3fc", "index": 691, "step-1": "<mask token>\n\n\nclass Resources:\n <mask token>\n\n def __init__(self, title, author, publisher, year):\n self.title = title\n self.author = author\n self.publisher = publisher\n self.year = year\n <mask token>\n <mask token>\n\n def set_publisher(self, publisher):\n \"\"\"Method that sets the publisher of a resource object\"\"\"\n self.publisher = publisher\n <mask token>\n <mask token>\n <mask token>\n\n def get_publisher(self):\n \"\"\"Method that gets the publisher of a resource object\"\"\"\n return self.publisher\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Resources:\n <mask token>\n\n def __init__(self, title, author, publisher, year):\n self.title = title\n self.author = author\n self.publisher = publisher\n self.year = year\n\n def set_title(self, title):\n \"\"\"Method that sets the title of a resource object\"\"\"\n self.title = title\n\n def set_author(self, author):\n \"\"\"Method that sets the author of a resource object\"\"\"\n self.author = author\n\n def set_publisher(self, publisher):\n \"\"\"Method that sets the publisher of a resource object\"\"\"\n self.publisher = publisher\n\n def set_year(self, year):\n \"\"\"Method that sets the year of a resource object\"\"\"\n self.year = year\n <mask token>\n\n def get_author(self):\n \"\"\"Method that gets the author of a resource object\"\"\"\n return self.author\n\n def get_publisher(self):\n \"\"\"Method that gets the publisher of a resource object\"\"\"\n return self.publisher\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Resources:\n <mask token>\n\n def __init__(self, title, author, publisher, year):\n self.title = title\n self.author = author\n self.publisher = publisher\n self.year = year\n\n def set_title(self, title):\n \"\"\"Method that sets the title of a resource object\"\"\"\n self.title = title\n\n def set_author(self, author):\n \"\"\"Method that sets the author of a resource object\"\"\"\n self.author = author\n\n def set_publisher(self, publisher):\n \"\"\"Method that sets the publisher of a resource object\"\"\"\n self.publisher = publisher\n\n def set_year(self, year):\n \"\"\"Method that sets the year of a resource object\"\"\"\n self.year = year\n <mask token>\n\n def get_author(self):\n \"\"\"Method that gets the author of a resource object\"\"\"\n return self.author\n\n def get_publisher(self):\n \"\"\"Method that gets the publisher of a resource object\"\"\"\n return self.publisher\n <mask token>\n\n def get_resource_details(self):\n \"\"\"Method that returns the main details of a resource object\"\"\"\n return (\n f'[Title:\"{self.get_title()}\"] [Author:{self.get_author()}] [Publisher:{self.get_publisher()}] [Year:{self.get_year()}]'\n )\n", "step-4": "<mask token>\n\n\nclass Resources:\n <mask token>\n\n def __init__(self, title, author, publisher, year):\n self.title = title\n self.author = author\n self.publisher = publisher\n self.year = year\n\n def set_title(self, title):\n \"\"\"Method that sets the title of a resource object\"\"\"\n self.title = title\n\n def set_author(self, author):\n \"\"\"Method that sets the author of a resource object\"\"\"\n self.author = author\n\n def set_publisher(self, publisher):\n \"\"\"Method that sets the publisher of a resource object\"\"\"\n self.publisher = publisher\n\n def set_year(self, year):\n \"\"\"Method that sets the year of a resource object\"\"\"\n self.year = year\n <mask token>\n\n def get_author(self):\n \"\"\"Method that gets the author of a resource object\"\"\"\n return self.author\n\n def get_publisher(self):\n \"\"\"Method that gets the publisher of a resource object\"\"\"\n return self.publisher\n\n def get_year(self):\n \"\"\"Method that gets the year of a resource object\"\"\"\n return self.year\n\n def get_resource_details(self):\n \"\"\"Method that returns the main details of a resource object\"\"\"\n return (\n f'[Title:\"{self.get_title()}\"] [Author:{self.get_author()}] [Publisher:{self.get_publisher()}] [Year:{self.get_year()}]'\n )\n", "step-5": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 9 16:22:21 2018\n\n@author: SDis\n\"\"\"\n#import Code.Members_module\n\nclass Resources:\n \"\"\" Parent class for Books and eResources containg the main data fields and related setters and getters\"\"\"\n def __init__(self, title, author, publisher, year):\n self.title = title\n self.author = author\n self.publisher = publisher\n self.year = year \n#Setters \n def set_title (self, title):\n \"\"\"Method that sets the title of a resource object\"\"\"\n self.title = title \n def set_author (self, author):\n \"\"\"Method that sets the author of a resource object\"\"\"\n self.author = author\n def set_publisher (self, publisher):\n \"\"\"Method that sets the publisher of a resource object\"\"\"\n self.publisher = publisher\n def set_year (self, year):\n \"\"\"Method that sets the year of a resource object\"\"\"\n self.year = year\n#Getters \n def get_title(self):\n \"\"\"Method that gets the title of a resource object\"\"\"\n return self.title\n def get_author(self):\n \"\"\"Method that gets the author of a resource object\"\"\"\n return self.author\n def get_publisher(self):\n \"\"\"Method that gets the publisher of a resource object\"\"\"\n return self.publisher\n def get_year(self):\n \"\"\"Method that gets the year of a resource object\"\"\"\n return self.year\n\n def get_resource_details (self):\n \"\"\"Method that returns the main details of a resource object\"\"\"\n return (f\"[Title:\\\"{self.get_title()}\\\"] [Author:{self.get_author()}] [Publisher:{self.get_publisher()}] [Year:{self.get_year()}]\")\n \n\n \n\n\n\n\n", "step-ids": [ 4, 8, 9, 10, 13 ] }
[ 4, 8, 9, 10, 13 ]
from __future__ import unicode_literals import json, alice_static import logging from random import choice # Импортируем подмодули Flask для запуска веб-сервиса. from flask import Flask, request app = Flask(__name__) logging.basicConfig(level=logging.DEBUG) # Хранилище данных о сессиях. sessionStorage = {} # Задаем параметры приложения Flask. @app.route("/", methods=['POST']) def format_new_question(quest): question = choice(alice_static.questions) return question.format(quest=quest) def timerout() user_storage['try'] += 1 timeup = choice(alice_static.answer_timeup) right_answer=choice(alice_static.right_answer) real_answer=quest_data[user_storage['answer']] again=choice(alice_static.again) response.set_text('{timeup}\n{right_answer}{real_answer}\n{again}'.format( timeup=timeup, right_answer=right_answer real_answer=real_answer again=again )) buttons = [{ "title": "Да", "hide": True }, { "title": "Нет", "hide": True }] response.set_buttons(buttons) #Выводим кнопочки user_storage['state'] = REPLY #Меняем состояние пользователя def handle_dialog(request, response, user_storage): if request.is_new_session: # Это новый пользователь. # Инициализируем сессию и поприветствуем его. greetings = choice(alice_static.greetings) user_storage = { 'quest': quest, 'state': STOP, #STOP-вопрос не задан Wait-ожидается ответ Reply - ответ получен 'wins': 0, 'tries':0 } response.set_text('{greetings}'.format( greetings=greetings )) if user_storage.get('state') == STOP: newquest = choice(alice_static.newquest) response.set_text('{newquest}'.format( newquest=newquest, )) buttons = [{ "title": "Да", "hide": True }, { "title": "Нет", "hide": True }] response.set_buttons(buttons) if request.command.lower() == 'да': quest = choice(list(quest_data.keys())) user_storage = { 'quest': quest, 'state': WAIT, 'wins': user_storage['wins'], 'tries': user_storage ['tries'] } response.set_text(format_new_question(quest)) elif request.command.lower() == 'нет': response.set_text("Желаете выйти?") buttons = [{ "title": "Да", "hide": True }, { "title": "Нет", "hide": True }] response.set_buttons(buttons) if request.command.lower() == 'нет': user_storage['state'] = STOP elif request.command.lower() == 'да': response.set_end_session(True) goodbye = choice(alice_static.goodbye) response.set_text(goodbye) else: response.set_buttons(buttons) response.set_text ('Извините я не понимаю, вы хотите выйти?') else: buttons = [{ "title": "Да", "hide": True }, { "title": "Нет", "hide": True }] response.set_buttons(buttons) response.set_text('Выбери один из двух вариантов - Да или Нет') if user_storage.get('state') == WAIT: # Обрабатываем ответ пользователя. timer = Timer(30.0, timerout) timer.start() if request.command.lower() == quest_data[user_storage['answer']].lower(): # Пользователь угадал. user_storage['wins'] += 1 user_storage['try'] +=1 #Добавляем победу и попытку correct = choice(alice_static.answer_correct) again=choice(alice_static.again) #Выбираем реплику для поздравления response.set_text('{correct}\n{again}'.format( correct=correct again=again )) #Поздравляем и спрашиваем хочет ли пользователь сыграть ещё раз buttons = [{ "title": "Да", "hide": True }, { "title": "Нет", "hide": True }] response.set_buttons(buttons) #Выводим кнопочки user_storage['state'] = REPLY #Меняем состояние пользователя else: user_storage['try'] += 1 incorrect = choice(alice_static.answer_incorrect) right_answer=choice(alice_static.right_answer) real_answer=quest_data[user_storage['answer']] again=choice(alice_static.again) response.set_text('{incorrect}\n{right_answer}{real_answer}\n{again}'.format( incorrect=incorrect, right_answer=right_answer real_answer=real_answer again=again )) buttons = [{ "title": "Да", "hide": True }, { "title": "Нет", "hide": True }] response.set_buttons(buttons) #Выводим кнопочки user_storage['state'] = REPLY #Меняем состояние пользователя elif user_storage.get('state') == REPLY: if request.command.lower() == 'да': quest = choice(list(quest_data.keys())) user_storage = { 'quest': quest, 'state': WAIT, 'wins': user_storage['wins'], 'tries': user_storage ['tries'] } response.set_text(format_new_question(quest)) elif request.command.lower() == 'нет': response.set_end_session(True) goodbye = choice(alice_static.goodbye) response.set_text(goodbye) else: buttons = [{ "title": "Да", "hide": True }, { "title": "Нет", "hide": True }] response.set_buttons(buttons) response.set_text('Выбери один из двух вариантов - Да или Нет')
normal
{ "blob_id": "2df679fc3407c15f5d0c006e9da8d1fc74bcf875", "index": 5705, "step-1": "from __future__ import unicode_literals\nimport json, alice_static\nimport logging\nfrom random import choice\n# Импортируем подмодули Flask для запуска веб-сервиса.\nfrom flask import Flask, request\napp = Flask(__name__)\n\n\nlogging.basicConfig(level=logging.DEBUG)\n\n# Хранилище данных о сессиях.\nsessionStorage = {}\n\n# Задаем параметры приложения Flask.\n@app.route(\"/\", methods=['POST'])\n\ndef format_new_question(quest):\n question = choice(alice_static.questions)\n return question.format(quest=quest)\ndef timerout()\n user_storage['try'] += 1\n timeup = choice(alice_static.answer_timeup)\n right_answer=choice(alice_static.right_answer)\n real_answer=quest_data[user_storage['answer']]\n again=choice(alice_static.again)\n response.set_text('{timeup}\\n{right_answer}{real_answer}\\n{again}'.format(\n timeup=timeup,\n right_answer=right_answer\n real_answer=real_answer\n again=again\n ))\n buttons = [{\n \"title\": \"Да\",\n \"hide\": True\n }, {\n \"title\": \"Нет\",\n \"hide\": True\n }]\n response.set_buttons(buttons)\n #Выводим кнопочки\n user_storage['state'] = REPLY\n #Меняем состояние пользователя\n\ndef handle_dialog(request, response, user_storage):\n if request.is_new_session:\n # Это новый пользователь.\n # Инициализируем сессию и поприветствуем его.\n greetings = choice(alice_static.greetings)\n \n user_storage = {\n 'quest': quest,\n 'state': STOP,\n #STOP-вопрос не задан Wait-ожидается ответ Reply - ответ получен\n 'wins': 0,\n 'tries':0\n }\n\n response.set_text('{greetings}'.format(\n greetings=greetings\n ))\n if user_storage.get('state') == STOP:\n newquest = choice(alice_static.newquest)\n response.set_text('{newquest}'.format(\n newquest=newquest,\n ))\n buttons = [{\n \"title\": \"Да\",\n \"hide\": True\n }, {\n \"title\": \"Нет\",\n \"hide\": True\n }]\n response.set_buttons(buttons)\n if request.command.lower() == 'да':\n quest = choice(list(quest_data.keys()))\n user_storage = {\n 'quest': quest,\n 'state': WAIT,\n 'wins': user_storage['wins'],\n 'tries': user_storage ['tries']\n }\n response.set_text(format_new_question(quest))\n elif request.command.lower() == 'нет':\n response.set_text(\"Желаете выйти?\")\n buttons = [{\n \"title\": \"Да\",\n \"hide\": True\n }, {\n \"title\": \"Нет\",\n \"hide\": True\n }]\n response.set_buttons(buttons)\n if request.command.lower() == 'нет': \n user_storage['state'] = STOP\n elif request.command.lower() == 'да':\n response.set_end_session(True)\n goodbye = choice(alice_static.goodbye)\n response.set_text(goodbye)\n else:\n response.set_buttons(buttons)\n response.set_text ('Извините я не понимаю, вы хотите выйти?')\n else:\n buttons = [{\n \"title\": \"Да\",\n \"hide\": True\n }, {\n \"title\": \"Нет\",\n \"hide\": True\n }]\n response.set_buttons(buttons)\n response.set_text('Выбери один из двух вариантов - Да или Нет') \n if user_storage.get('state') == WAIT:\n # Обрабатываем ответ пользователя.\n timer = Timer(30.0, timerout)\n timer.start()\n if request.command.lower() == quest_data[user_storage['answer']].lower():\n # Пользователь угадал.\n user_storage['wins'] += 1\n user_storage['try'] +=1\n #Добавляем победу и попытку\n correct = choice(alice_static.answer_correct)\n again=choice(alice_static.again)\n #Выбираем реплику для поздравления\n\n response.set_text('{correct}\\n{again}'.format(\n correct=correct\n again=again\n ))\n #Поздравляем и спрашиваем хочет ли пользователь сыграть ещё раз\n\n buttons = [{\n \"title\": \"Да\",\n \"hide\": True\n }, {\n \"title\": \"Нет\",\n \"hide\": True\n }]\n response.set_buttons(buttons)\n #Выводим кнопочки\n user_storage['state'] = REPLY\n #Меняем состояние пользователя\n else:\n user_storage['try'] += 1\n incorrect = choice(alice_static.answer_incorrect)\n right_answer=choice(alice_static.right_answer)\n real_answer=quest_data[user_storage['answer']]\n again=choice(alice_static.again)\n response.set_text('{incorrect}\\n{right_answer}{real_answer}\\n{again}'.format(\n incorrect=incorrect,\n right_answer=right_answer\n real_answer=real_answer\n again=again\n ))\n buttons = [{\n \"title\": \"Да\",\n \"hide\": True\n }, {\n \"title\": \"Нет\",\n \"hide\": True\n }]\n response.set_buttons(buttons)\n #Выводим кнопочки\n user_storage['state'] = REPLY\n #Меняем состояние пользователя\n elif user_storage.get('state') == REPLY:\n if request.command.lower() == 'да':\n quest = choice(list(quest_data.keys()))\n user_storage = {\n 'quest': quest,\n 'state': WAIT,\n 'wins': user_storage['wins'],\n 'tries': user_storage ['tries']\n }\n response.set_text(format_new_question(quest))\n\n elif request.command.lower() == 'нет':\n response.set_end_session(True)\n goodbye = choice(alice_static.goodbye)\n response.set_text(goodbye)\n else:\n buttons = [{\n \"title\": \"Да\",\n \"hide\": True\n }, {\n \"title\": \"Нет\",\n \"hide\": True\n }]\n response.set_buttons(buttons)\n response.set_text('Выбери один из двух вариантов - Да или Нет')\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> class BaseCollectionSerializer(ResolweBaseSerializer): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def get_status(self, collection): """Return status of the collection based on the status of data objects. When collection contains no data objects None is returned. """ status_order = [Data.STATUS_ERROR, Data.STATUS_UPLOADING, Data. STATUS_PROCESSING, Data.STATUS_PREPARING, Data.STATUS_WAITING, Data.STATUS_RESOLVING, Data.STATUS_DONE] status_set = set(collection.data_statuses) if hasattr(collection, 'data_statuses') else collection.data.values_list('status', flat=True).distinct() if not status_set: return None for status in status_order: if status in status_set: return status logger.warning('Could not determine the status of a collection.', extra={'collection': collection.__dict__}) return None class Meta: """CollectionSerializer Meta options.""" model = Collection read_only_fields = ('created', 'descriptor_dirty', 'duplicated', 'id', 'modified', 'data_count', 'status') update_protected_fields = 'contributor', fields = read_only_fields + update_protected_fields + ('description', 'descriptor', 'descriptor_schema', 'name', 'settings', 'slug', 'tags') class CollectionSerializer(BaseCollectionSerializer): """Serializer for Collection objects.""" entity_count = serializers.SerializerMethodField(required=False) def get_entity_count(self, collection): """Return number of entities on the collection.""" return collection.entity_count if hasattr(collection, 'entity_count' ) else collection.entity_set.count() class Meta(BaseCollectionSerializer.Meta): """CollectionSerializer Meta options.""" read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + ( 'entity_count',) fields = BaseCollectionSerializer.Meta.fields + ('entity_count',) <|reserved_special_token_1|> <|reserved_special_token_0|> class BaseCollectionSerializer(ResolweBaseSerializer): <|reserved_special_token_0|> settings = ProjectableJSONField(required=False) descriptor = ProjectableJSONField(required=False) descriptor_schema = DictRelatedField(queryset=DescriptorSchema.objects. all(), serializer=DescriptorSchemaSerializer, allow_null=True, required=False) data_count = serializers.SerializerMethodField(required=False) status = serializers.SerializerMethodField(required=False) def get_data_count(self, collection): """Return number of data objects on the collection.""" return collection.data_count if hasattr(collection, 'data_count' ) else collection.data.count() def get_status(self, collection): """Return status of the collection based on the status of data objects. When collection contains no data objects None is returned. """ status_order = [Data.STATUS_ERROR, Data.STATUS_UPLOADING, Data. STATUS_PROCESSING, Data.STATUS_PREPARING, Data.STATUS_WAITING, Data.STATUS_RESOLVING, Data.STATUS_DONE] status_set = set(collection.data_statuses) if hasattr(collection, 'data_statuses') else collection.data.values_list('status', flat=True).distinct() if not status_set: return None for status in status_order: if status in status_set: return status logger.warning('Could not determine the status of a collection.', extra={'collection': collection.__dict__}) return None class Meta: """CollectionSerializer Meta options.""" model = Collection read_only_fields = ('created', 'descriptor_dirty', 'duplicated', 'id', 'modified', 'data_count', 'status') update_protected_fields = 'contributor', fields = read_only_fields + update_protected_fields + ('description', 'descriptor', 'descriptor_schema', 'name', 'settings', 'slug', 'tags') class CollectionSerializer(BaseCollectionSerializer): """Serializer for Collection objects.""" entity_count = serializers.SerializerMethodField(required=False) def get_entity_count(self, collection): """Return number of entities on the collection.""" return collection.entity_count if hasattr(collection, 'entity_count' ) else collection.entity_set.count() class Meta(BaseCollectionSerializer.Meta): """CollectionSerializer Meta options.""" read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + ( 'entity_count',) fields = BaseCollectionSerializer.Meta.fields + ('entity_count',) <|reserved_special_token_1|> <|reserved_special_token_0|> class BaseCollectionSerializer(ResolweBaseSerializer): """Base serializer for Collection objects.""" settings = ProjectableJSONField(required=False) descriptor = ProjectableJSONField(required=False) descriptor_schema = DictRelatedField(queryset=DescriptorSchema.objects. all(), serializer=DescriptorSchemaSerializer, allow_null=True, required=False) data_count = serializers.SerializerMethodField(required=False) status = serializers.SerializerMethodField(required=False) def get_data_count(self, collection): """Return number of data objects on the collection.""" return collection.data_count if hasattr(collection, 'data_count' ) else collection.data.count() def get_status(self, collection): """Return status of the collection based on the status of data objects. When collection contains no data objects None is returned. """ status_order = [Data.STATUS_ERROR, Data.STATUS_UPLOADING, Data. STATUS_PROCESSING, Data.STATUS_PREPARING, Data.STATUS_WAITING, Data.STATUS_RESOLVING, Data.STATUS_DONE] status_set = set(collection.data_statuses) if hasattr(collection, 'data_statuses') else collection.data.values_list('status', flat=True).distinct() if not status_set: return None for status in status_order: if status in status_set: return status logger.warning('Could not determine the status of a collection.', extra={'collection': collection.__dict__}) return None class Meta: """CollectionSerializer Meta options.""" model = Collection read_only_fields = ('created', 'descriptor_dirty', 'duplicated', 'id', 'modified', 'data_count', 'status') update_protected_fields = 'contributor', fields = read_only_fields + update_protected_fields + ('description', 'descriptor', 'descriptor_schema', 'name', 'settings', 'slug', 'tags') class CollectionSerializer(BaseCollectionSerializer): """Serializer for Collection objects.""" entity_count = serializers.SerializerMethodField(required=False) def get_entity_count(self, collection): """Return number of entities on the collection.""" return collection.entity_count if hasattr(collection, 'entity_count' ) else collection.entity_set.count() class Meta(BaseCollectionSerializer.Meta): """CollectionSerializer Meta options.""" read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + ( 'entity_count',) fields = BaseCollectionSerializer.Meta.fields + ('entity_count',) <|reserved_special_token_1|> <|reserved_special_token_0|> import logging from rest_framework import serializers from resolwe.flow.models import Collection, Data, DescriptorSchema from resolwe.rest.fields import ProjectableJSONField from .base import ResolweBaseSerializer from .descriptor import DescriptorSchemaSerializer from .fields import DictRelatedField logger = logging.getLogger(__name__) class BaseCollectionSerializer(ResolweBaseSerializer): """Base serializer for Collection objects.""" settings = ProjectableJSONField(required=False) descriptor = ProjectableJSONField(required=False) descriptor_schema = DictRelatedField(queryset=DescriptorSchema.objects. all(), serializer=DescriptorSchemaSerializer, allow_null=True, required=False) data_count = serializers.SerializerMethodField(required=False) status = serializers.SerializerMethodField(required=False) def get_data_count(self, collection): """Return number of data objects on the collection.""" return collection.data_count if hasattr(collection, 'data_count' ) else collection.data.count() def get_status(self, collection): """Return status of the collection based on the status of data objects. When collection contains no data objects None is returned. """ status_order = [Data.STATUS_ERROR, Data.STATUS_UPLOADING, Data. STATUS_PROCESSING, Data.STATUS_PREPARING, Data.STATUS_WAITING, Data.STATUS_RESOLVING, Data.STATUS_DONE] status_set = set(collection.data_statuses) if hasattr(collection, 'data_statuses') else collection.data.values_list('status', flat=True).distinct() if not status_set: return None for status in status_order: if status in status_set: return status logger.warning('Could not determine the status of a collection.', extra={'collection': collection.__dict__}) return None class Meta: """CollectionSerializer Meta options.""" model = Collection read_only_fields = ('created', 'descriptor_dirty', 'duplicated', 'id', 'modified', 'data_count', 'status') update_protected_fields = 'contributor', fields = read_only_fields + update_protected_fields + ('description', 'descriptor', 'descriptor_schema', 'name', 'settings', 'slug', 'tags') class CollectionSerializer(BaseCollectionSerializer): """Serializer for Collection objects.""" entity_count = serializers.SerializerMethodField(required=False) def get_entity_count(self, collection): """Return number of entities on the collection.""" return collection.entity_count if hasattr(collection, 'entity_count' ) else collection.entity_set.count() class Meta(BaseCollectionSerializer.Meta): """CollectionSerializer Meta options.""" read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + ( 'entity_count',) fields = BaseCollectionSerializer.Meta.fields + ('entity_count',) <|reserved_special_token_1|> """Resolwe collection serializer.""" import logging from rest_framework import serializers from resolwe.flow.models import Collection, Data, DescriptorSchema from resolwe.rest.fields import ProjectableJSONField from .base import ResolweBaseSerializer from .descriptor import DescriptorSchemaSerializer from .fields import DictRelatedField logger = logging.getLogger(__name__) class BaseCollectionSerializer(ResolweBaseSerializer): """Base serializer for Collection objects.""" settings = ProjectableJSONField(required=False) descriptor = ProjectableJSONField(required=False) descriptor_schema = DictRelatedField( queryset=DescriptorSchema.objects.all(), serializer=DescriptorSchemaSerializer, allow_null=True, required=False, ) data_count = serializers.SerializerMethodField(required=False) status = serializers.SerializerMethodField(required=False) def get_data_count(self, collection): """Return number of data objects on the collection.""" # Use 'data_count' attribute when available. It is created in the # BaseCollectionViewSet class. return ( collection.data_count if hasattr(collection, "data_count") else collection.data.count() ) def get_status(self, collection): """Return status of the collection based on the status of data objects. When collection contains no data objects None is returned. """ status_order = [ Data.STATUS_ERROR, Data.STATUS_UPLOADING, Data.STATUS_PROCESSING, Data.STATUS_PREPARING, Data.STATUS_WAITING, Data.STATUS_RESOLVING, Data.STATUS_DONE, ] # Use 'data_statuses' attribute when available. It is created in the # BaseCollectionViewSet class. It contains all the distinct statuses of the # data objects in the collection. status_set = ( set(collection.data_statuses) if hasattr(collection, "data_statuses") else collection.data.values_list("status", flat=True).distinct() ) if not status_set: return None for status in status_order: if status in status_set: return status logger.warning( "Could not determine the status of a collection.", extra={"collection": collection.__dict__}, ) return None class Meta: """CollectionSerializer Meta options.""" model = Collection read_only_fields = ( "created", "descriptor_dirty", "duplicated", "id", "modified", "data_count", "status", ) update_protected_fields = ("contributor",) fields = ( read_only_fields + update_protected_fields + ( "description", "descriptor", "descriptor_schema", "name", "settings", "slug", "tags", ) ) class CollectionSerializer(BaseCollectionSerializer): """Serializer for Collection objects.""" entity_count = serializers.SerializerMethodField(required=False) def get_entity_count(self, collection): """Return number of entities on the collection.""" # Use 'entity_count' attribute when available. It is created in the # BaseCollectionViewSet class. return ( collection.entity_count if hasattr(collection, "entity_count") else collection.entity_set.count() ) class Meta(BaseCollectionSerializer.Meta): """CollectionSerializer Meta options.""" read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + ( "entity_count", ) fields = BaseCollectionSerializer.Meta.fields + ("entity_count",)
flexible
{ "blob_id": "d6f8ec0fd8be0fa7019a84af47d08ab8b5b32d92", "index": 1449, "step-1": "<mask token>\n\n\nclass BaseCollectionSerializer(ResolweBaseSerializer):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def get_status(self, collection):\n \"\"\"Return status of the collection based on the status of data objects.\n\n When collection contains no data objects None is returned.\n \"\"\"\n status_order = [Data.STATUS_ERROR, Data.STATUS_UPLOADING, Data.\n STATUS_PROCESSING, Data.STATUS_PREPARING, Data.STATUS_WAITING,\n Data.STATUS_RESOLVING, Data.STATUS_DONE]\n status_set = set(collection.data_statuses) if hasattr(collection,\n 'data_statuses') else collection.data.values_list('status',\n flat=True).distinct()\n if not status_set:\n return None\n for status in status_order:\n if status in status_set:\n return status\n logger.warning('Could not determine the status of a collection.',\n extra={'collection': collection.__dict__})\n return None\n\n\n class Meta:\n \"\"\"CollectionSerializer Meta options.\"\"\"\n model = Collection\n read_only_fields = ('created', 'descriptor_dirty', 'duplicated',\n 'id', 'modified', 'data_count', 'status')\n update_protected_fields = 'contributor',\n fields = read_only_fields + update_protected_fields + ('description',\n 'descriptor', 'descriptor_schema', 'name', 'settings', 'slug',\n 'tags')\n\n\nclass CollectionSerializer(BaseCollectionSerializer):\n \"\"\"Serializer for Collection objects.\"\"\"\n entity_count = serializers.SerializerMethodField(required=False)\n\n def get_entity_count(self, collection):\n \"\"\"Return number of entities on the collection.\"\"\"\n return collection.entity_count if hasattr(collection, 'entity_count'\n ) else collection.entity_set.count()\n\n\n class Meta(BaseCollectionSerializer.Meta):\n \"\"\"CollectionSerializer Meta options.\"\"\"\n read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + (\n 'entity_count',)\n fields = BaseCollectionSerializer.Meta.fields + ('entity_count',)\n", "step-2": "<mask token>\n\n\nclass BaseCollectionSerializer(ResolweBaseSerializer):\n <mask token>\n settings = ProjectableJSONField(required=False)\n descriptor = ProjectableJSONField(required=False)\n descriptor_schema = DictRelatedField(queryset=DescriptorSchema.objects.\n all(), serializer=DescriptorSchemaSerializer, allow_null=True,\n required=False)\n data_count = serializers.SerializerMethodField(required=False)\n status = serializers.SerializerMethodField(required=False)\n\n def get_data_count(self, collection):\n \"\"\"Return number of data objects on the collection.\"\"\"\n return collection.data_count if hasattr(collection, 'data_count'\n ) else collection.data.count()\n\n def get_status(self, collection):\n \"\"\"Return status of the collection based on the status of data objects.\n\n When collection contains no data objects None is returned.\n \"\"\"\n status_order = [Data.STATUS_ERROR, Data.STATUS_UPLOADING, Data.\n STATUS_PROCESSING, Data.STATUS_PREPARING, Data.STATUS_WAITING,\n Data.STATUS_RESOLVING, Data.STATUS_DONE]\n status_set = set(collection.data_statuses) if hasattr(collection,\n 'data_statuses') else collection.data.values_list('status',\n flat=True).distinct()\n if not status_set:\n return None\n for status in status_order:\n if status in status_set:\n return status\n logger.warning('Could not determine the status of a collection.',\n extra={'collection': collection.__dict__})\n return None\n\n\n class Meta:\n \"\"\"CollectionSerializer Meta options.\"\"\"\n model = Collection\n read_only_fields = ('created', 'descriptor_dirty', 'duplicated',\n 'id', 'modified', 'data_count', 'status')\n update_protected_fields = 'contributor',\n fields = read_only_fields + update_protected_fields + ('description',\n 'descriptor', 'descriptor_schema', 'name', 'settings', 'slug',\n 'tags')\n\n\nclass CollectionSerializer(BaseCollectionSerializer):\n \"\"\"Serializer for Collection objects.\"\"\"\n entity_count = serializers.SerializerMethodField(required=False)\n\n def get_entity_count(self, collection):\n \"\"\"Return number of entities on the collection.\"\"\"\n return collection.entity_count if hasattr(collection, 'entity_count'\n ) else collection.entity_set.count()\n\n\n class Meta(BaseCollectionSerializer.Meta):\n \"\"\"CollectionSerializer Meta options.\"\"\"\n read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + (\n 'entity_count',)\n fields = BaseCollectionSerializer.Meta.fields + ('entity_count',)\n", "step-3": "<mask token>\n\n\nclass BaseCollectionSerializer(ResolweBaseSerializer):\n \"\"\"Base serializer for Collection objects.\"\"\"\n settings = ProjectableJSONField(required=False)\n descriptor = ProjectableJSONField(required=False)\n descriptor_schema = DictRelatedField(queryset=DescriptorSchema.objects.\n all(), serializer=DescriptorSchemaSerializer, allow_null=True,\n required=False)\n data_count = serializers.SerializerMethodField(required=False)\n status = serializers.SerializerMethodField(required=False)\n\n def get_data_count(self, collection):\n \"\"\"Return number of data objects on the collection.\"\"\"\n return collection.data_count if hasattr(collection, 'data_count'\n ) else collection.data.count()\n\n def get_status(self, collection):\n \"\"\"Return status of the collection based on the status of data objects.\n\n When collection contains no data objects None is returned.\n \"\"\"\n status_order = [Data.STATUS_ERROR, Data.STATUS_UPLOADING, Data.\n STATUS_PROCESSING, Data.STATUS_PREPARING, Data.STATUS_WAITING,\n Data.STATUS_RESOLVING, Data.STATUS_DONE]\n status_set = set(collection.data_statuses) if hasattr(collection,\n 'data_statuses') else collection.data.values_list('status',\n flat=True).distinct()\n if not status_set:\n return None\n for status in status_order:\n if status in status_set:\n return status\n logger.warning('Could not determine the status of a collection.',\n extra={'collection': collection.__dict__})\n return None\n\n\n class Meta:\n \"\"\"CollectionSerializer Meta options.\"\"\"\n model = Collection\n read_only_fields = ('created', 'descriptor_dirty', 'duplicated',\n 'id', 'modified', 'data_count', 'status')\n update_protected_fields = 'contributor',\n fields = read_only_fields + update_protected_fields + ('description',\n 'descriptor', 'descriptor_schema', 'name', 'settings', 'slug',\n 'tags')\n\n\nclass CollectionSerializer(BaseCollectionSerializer):\n \"\"\"Serializer for Collection objects.\"\"\"\n entity_count = serializers.SerializerMethodField(required=False)\n\n def get_entity_count(self, collection):\n \"\"\"Return number of entities on the collection.\"\"\"\n return collection.entity_count if hasattr(collection, 'entity_count'\n ) else collection.entity_set.count()\n\n\n class Meta(BaseCollectionSerializer.Meta):\n \"\"\"CollectionSerializer Meta options.\"\"\"\n read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + (\n 'entity_count',)\n fields = BaseCollectionSerializer.Meta.fields + ('entity_count',)\n", "step-4": "<mask token>\nimport logging\nfrom rest_framework import serializers\nfrom resolwe.flow.models import Collection, Data, DescriptorSchema\nfrom resolwe.rest.fields import ProjectableJSONField\nfrom .base import ResolweBaseSerializer\nfrom .descriptor import DescriptorSchemaSerializer\nfrom .fields import DictRelatedField\nlogger = logging.getLogger(__name__)\n\n\nclass BaseCollectionSerializer(ResolweBaseSerializer):\n \"\"\"Base serializer for Collection objects.\"\"\"\n settings = ProjectableJSONField(required=False)\n descriptor = ProjectableJSONField(required=False)\n descriptor_schema = DictRelatedField(queryset=DescriptorSchema.objects.\n all(), serializer=DescriptorSchemaSerializer, allow_null=True,\n required=False)\n data_count = serializers.SerializerMethodField(required=False)\n status = serializers.SerializerMethodField(required=False)\n\n def get_data_count(self, collection):\n \"\"\"Return number of data objects on the collection.\"\"\"\n return collection.data_count if hasattr(collection, 'data_count'\n ) else collection.data.count()\n\n def get_status(self, collection):\n \"\"\"Return status of the collection based on the status of data objects.\n\n When collection contains no data objects None is returned.\n \"\"\"\n status_order = [Data.STATUS_ERROR, Data.STATUS_UPLOADING, Data.\n STATUS_PROCESSING, Data.STATUS_PREPARING, Data.STATUS_WAITING,\n Data.STATUS_RESOLVING, Data.STATUS_DONE]\n status_set = set(collection.data_statuses) if hasattr(collection,\n 'data_statuses') else collection.data.values_list('status',\n flat=True).distinct()\n if not status_set:\n return None\n for status in status_order:\n if status in status_set:\n return status\n logger.warning('Could not determine the status of a collection.',\n extra={'collection': collection.__dict__})\n return None\n\n\n class Meta:\n \"\"\"CollectionSerializer Meta options.\"\"\"\n model = Collection\n read_only_fields = ('created', 'descriptor_dirty', 'duplicated',\n 'id', 'modified', 'data_count', 'status')\n update_protected_fields = 'contributor',\n fields = read_only_fields + update_protected_fields + ('description',\n 'descriptor', 'descriptor_schema', 'name', 'settings', 'slug',\n 'tags')\n\n\nclass CollectionSerializer(BaseCollectionSerializer):\n \"\"\"Serializer for Collection objects.\"\"\"\n entity_count = serializers.SerializerMethodField(required=False)\n\n def get_entity_count(self, collection):\n \"\"\"Return number of entities on the collection.\"\"\"\n return collection.entity_count if hasattr(collection, 'entity_count'\n ) else collection.entity_set.count()\n\n\n class Meta(BaseCollectionSerializer.Meta):\n \"\"\"CollectionSerializer Meta options.\"\"\"\n read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + (\n 'entity_count',)\n fields = BaseCollectionSerializer.Meta.fields + ('entity_count',)\n", "step-5": "\"\"\"Resolwe collection serializer.\"\"\"\nimport logging\n\nfrom rest_framework import serializers\n\nfrom resolwe.flow.models import Collection, Data, DescriptorSchema\nfrom resolwe.rest.fields import ProjectableJSONField\n\nfrom .base import ResolweBaseSerializer\nfrom .descriptor import DescriptorSchemaSerializer\nfrom .fields import DictRelatedField\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseCollectionSerializer(ResolweBaseSerializer):\n \"\"\"Base serializer for Collection objects.\"\"\"\n\n settings = ProjectableJSONField(required=False)\n descriptor = ProjectableJSONField(required=False)\n descriptor_schema = DictRelatedField(\n queryset=DescriptorSchema.objects.all(),\n serializer=DescriptorSchemaSerializer,\n allow_null=True,\n required=False,\n )\n data_count = serializers.SerializerMethodField(required=False)\n status = serializers.SerializerMethodField(required=False)\n\n def get_data_count(self, collection):\n \"\"\"Return number of data objects on the collection.\"\"\"\n # Use 'data_count' attribute when available. It is created in the\n # BaseCollectionViewSet class.\n return (\n collection.data_count\n if hasattr(collection, \"data_count\")\n else collection.data.count()\n )\n\n def get_status(self, collection):\n \"\"\"Return status of the collection based on the status of data objects.\n\n When collection contains no data objects None is returned.\n \"\"\"\n\n status_order = [\n Data.STATUS_ERROR,\n Data.STATUS_UPLOADING,\n Data.STATUS_PROCESSING,\n Data.STATUS_PREPARING,\n Data.STATUS_WAITING,\n Data.STATUS_RESOLVING,\n Data.STATUS_DONE,\n ]\n\n # Use 'data_statuses' attribute when available. It is created in the\n # BaseCollectionViewSet class. It contains all the distinct statuses of the\n # data objects in the collection.\n status_set = (\n set(collection.data_statuses)\n if hasattr(collection, \"data_statuses\")\n else collection.data.values_list(\"status\", flat=True).distinct()\n )\n\n if not status_set:\n return None\n\n for status in status_order:\n if status in status_set:\n return status\n\n logger.warning(\n \"Could not determine the status of a collection.\",\n extra={\"collection\": collection.__dict__},\n )\n return None\n\n class Meta:\n \"\"\"CollectionSerializer Meta options.\"\"\"\n\n model = Collection\n read_only_fields = (\n \"created\",\n \"descriptor_dirty\",\n \"duplicated\",\n \"id\",\n \"modified\",\n \"data_count\",\n \"status\",\n )\n update_protected_fields = (\"contributor\",)\n fields = (\n read_only_fields\n + update_protected_fields\n + (\n \"description\",\n \"descriptor\",\n \"descriptor_schema\",\n \"name\",\n \"settings\",\n \"slug\",\n \"tags\",\n )\n )\n\n\nclass CollectionSerializer(BaseCollectionSerializer):\n \"\"\"Serializer for Collection objects.\"\"\"\n\n entity_count = serializers.SerializerMethodField(required=False)\n\n def get_entity_count(self, collection):\n \"\"\"Return number of entities on the collection.\"\"\"\n # Use 'entity_count' attribute when available. It is created in the\n # BaseCollectionViewSet class.\n return (\n collection.entity_count\n if hasattr(collection, \"entity_count\")\n else collection.entity_set.count()\n )\n\n class Meta(BaseCollectionSerializer.Meta):\n \"\"\"CollectionSerializer Meta options.\"\"\"\n\n read_only_fields = BaseCollectionSerializer.Meta.read_only_fields + (\n \"entity_count\",\n )\n\n fields = BaseCollectionSerializer.Meta.fields + (\"entity_count\",)\n", "step-ids": [ 6, 8, 9, 11, 12 ] }
[ 6, 8, 9, 11, 12 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @pytest.mark.asyncio async def test_authenticator(aioresponse: aioresponses) ->None: with open('tests/fixtures/auth_pin_status.xml') as file: aioresponse.get('http://1.2.3.4:8080/ws/apps/CloudPINPage', body= file.read()) with open('tests/fixtures/auth_pin_status.xml') as file: aioresponse.post('http://1.2.3.4:8080/ws/apps/CloudPINPage', body= 'http:///ws/apps/CloudPINPage/run') with open('tests/fixtures/auth_empty.json') as file: aioresponse.get( 'http://1.2.3.4:8080/ws/pairing?step=0&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&type=1' , body=file.read()) with open('tests/fixtures/auth_generator_client_hello.json') as file: aioresponse.post( 'http://1.2.3.4:8080/ws/pairing?step=1&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184' , body=file.read()) with open('tests/fixtures/auth_client_ack_msg.json') as file: aioresponse.post( 'http://1.2.3.4:8080/ws/pairing?step=2&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184' , body=file.read()) aioresponse.delete('http://1.2.3.4:8080/ws/apps/CloudPINPage/run', body='') authenticator = SamsungTVEncryptedWSAsyncAuthenticator('1.2.3.4', web_session=aiohttp.ClientSession()) await authenticator.start_pairing() token = await authenticator.try_pin('0997') assert token == '545a596ab96b289c60896255e8690288' session_id = await authenticator.get_session_id_and_close() assert session_id == '1' assert len(aioresponse.requests) == 6 print(aioresponse.requests) request = aioresponse.requests['POST', URL( 'http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=1' )] assert request[0].kwargs['data' ] == '{"auth_Data":{"auth_type":"SPC","GeneratorServerHello":"010200000000000000008A000000063635343332317CAF9CBDC06B666D23EBCA615E0666FEB2B807091BF507404DDD18329CD64A91E513DC704298CCE49C4C5656C42141A696354A7145127BCD94CDD2B0D632D87E332437F86EBE5A50A1512F3F54C71B791A88ECBAF562FBABE2731F27D851A764CA114DBE2C2C965DF151CFC7401920FAA04636B356B97DBE1DA3A090004F81830000000000"}}' request = aioresponse.requests['POST', URL( 'http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=2' )] assert request[0].kwargs['data' ] == '{"auth_Data":{"auth_type":"SPC","request_id":"0","ServerAckMsg":"01030000000000000000145F38EAFF0F6A6FF062CA652CD6CBAD9AF1EC62470000000000"}}' <|reserved_special_token_1|> <|reserved_special_token_0|> import aiohttp from aioresponses import aioresponses import pytest from yarl import URL from samsungtvws.encrypted.authenticator import SamsungTVEncryptedWSAsyncAuthenticator @pytest.mark.asyncio async def test_authenticator(aioresponse: aioresponses) ->None: with open('tests/fixtures/auth_pin_status.xml') as file: aioresponse.get('http://1.2.3.4:8080/ws/apps/CloudPINPage', body= file.read()) with open('tests/fixtures/auth_pin_status.xml') as file: aioresponse.post('http://1.2.3.4:8080/ws/apps/CloudPINPage', body= 'http:///ws/apps/CloudPINPage/run') with open('tests/fixtures/auth_empty.json') as file: aioresponse.get( 'http://1.2.3.4:8080/ws/pairing?step=0&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&type=1' , body=file.read()) with open('tests/fixtures/auth_generator_client_hello.json') as file: aioresponse.post( 'http://1.2.3.4:8080/ws/pairing?step=1&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184' , body=file.read()) with open('tests/fixtures/auth_client_ack_msg.json') as file: aioresponse.post( 'http://1.2.3.4:8080/ws/pairing?step=2&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184' , body=file.read()) aioresponse.delete('http://1.2.3.4:8080/ws/apps/CloudPINPage/run', body='') authenticator = SamsungTVEncryptedWSAsyncAuthenticator('1.2.3.4', web_session=aiohttp.ClientSession()) await authenticator.start_pairing() token = await authenticator.try_pin('0997') assert token == '545a596ab96b289c60896255e8690288' session_id = await authenticator.get_session_id_and_close() assert session_id == '1' assert len(aioresponse.requests) == 6 print(aioresponse.requests) request = aioresponse.requests['POST', URL( 'http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=1' )] assert request[0].kwargs['data' ] == '{"auth_Data":{"auth_type":"SPC","GeneratorServerHello":"010200000000000000008A000000063635343332317CAF9CBDC06B666D23EBCA615E0666FEB2B807091BF507404DDD18329CD64A91E513DC704298CCE49C4C5656C42141A696354A7145127BCD94CDD2B0D632D87E332437F86EBE5A50A1512F3F54C71B791A88ECBAF562FBABE2731F27D851A764CA114DBE2C2C965DF151CFC7401920FAA04636B356B97DBE1DA3A090004F81830000000000"}}' request = aioresponse.requests['POST', URL( 'http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=2' )] assert request[0].kwargs['data' ] == '{"auth_Data":{"auth_type":"SPC","request_id":"0","ServerAckMsg":"01030000000000000000145F38EAFF0F6A6FF062CA652CD6CBAD9AF1EC62470000000000"}}' <|reserved_special_token_1|> """SamsungTV Encrypted.""" import aiohttp from aioresponses import aioresponses import pytest from yarl import URL from samsungtvws.encrypted.authenticator import SamsungTVEncryptedWSAsyncAuthenticator @pytest.mark.asyncio async def test_authenticator(aioresponse: aioresponses) -> None: with open("tests/fixtures/auth_pin_status.xml") as file: aioresponse.get("http://1.2.3.4:8080/ws/apps/CloudPINPage", body=file.read()) with open("tests/fixtures/auth_pin_status.xml") as file: aioresponse.post( "http://1.2.3.4:8080/ws/apps/CloudPINPage", body="http:///ws/apps/CloudPINPage/run", ) with open("tests/fixtures/auth_empty.json") as file: aioresponse.get( "http://1.2.3.4:8080/ws/pairing?step=0&app_id=12345" "&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&type=1", body=file.read(), ) with open("tests/fixtures/auth_generator_client_hello.json") as file: aioresponse.post( "http://1.2.3.4:8080/ws/pairing?step=1&app_id=12345" "&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184", body=file.read(), ) with open("tests/fixtures/auth_client_ack_msg.json") as file: aioresponse.post( "http://1.2.3.4:8080/ws/pairing?step=2&app_id=12345" "&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184", body=file.read(), ) aioresponse.delete("http://1.2.3.4:8080/ws/apps/CloudPINPage/run", body="") authenticator = SamsungTVEncryptedWSAsyncAuthenticator( "1.2.3.4", web_session=aiohttp.ClientSession() ) await authenticator.start_pairing() token = await authenticator.try_pin("0997") assert token == "545a596ab96b289c60896255e8690288" session_id = await authenticator.get_session_id_and_close() assert session_id == "1" assert len(aioresponse.requests) == 6 print(aioresponse.requests) request = aioresponse.requests[ ( "POST", URL( "http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=1" ), ) ] assert ( request[0].kwargs["data"] == '{"auth_Data":{"auth_type":"SPC","GeneratorServerHello":' '"010200000000000000008A000000063635343332317CAF9CBDC06B666D23EBC' "A615E0666FEB2B807091BF507404DDD18329CD64A91E513DC704298CCE49C4C5" "656C42141A696354A7145127BCD94CDD2B0D632D87E332437F86EBE5A50A1512" "F3F54C71B791A88ECBAF562FBABE2731F27D851A764CA114DBE2C2C965DF151C" 'FC7401920FAA04636B356B97DBE1DA3A090004F81830000000000"}}' ) request = aioresponse.requests[ ( "POST", URL( "http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=2" ), ) ] assert ( request[0].kwargs["data"] == '{"auth_Data":{"auth_type":"SPC","request_id":"0","ServerAckMsg":' '"01030000000000000000145F38EAFF0F6A6FF062CA652CD6CBAD9AF1EC62470000000000"}}' )
flexible
{ "blob_id": "e1448e62020f87e315d219be97d9af84607441df", "index": 9104, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@pytest.mark.asyncio\nasync def test_authenticator(aioresponse: aioresponses) ->None:\n with open('tests/fixtures/auth_pin_status.xml') as file:\n aioresponse.get('http://1.2.3.4:8080/ws/apps/CloudPINPage', body=\n file.read())\n with open('tests/fixtures/auth_pin_status.xml') as file:\n aioresponse.post('http://1.2.3.4:8080/ws/apps/CloudPINPage', body=\n 'http:///ws/apps/CloudPINPage/run')\n with open('tests/fixtures/auth_empty.json') as file:\n aioresponse.get(\n 'http://1.2.3.4:8080/ws/pairing?step=0&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&type=1'\n , body=file.read())\n with open('tests/fixtures/auth_generator_client_hello.json') as file:\n aioresponse.post(\n 'http://1.2.3.4:8080/ws/pairing?step=1&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184'\n , body=file.read())\n with open('tests/fixtures/auth_client_ack_msg.json') as file:\n aioresponse.post(\n 'http://1.2.3.4:8080/ws/pairing?step=2&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184'\n , body=file.read())\n aioresponse.delete('http://1.2.3.4:8080/ws/apps/CloudPINPage/run', body='')\n authenticator = SamsungTVEncryptedWSAsyncAuthenticator('1.2.3.4',\n web_session=aiohttp.ClientSession())\n await authenticator.start_pairing()\n token = await authenticator.try_pin('0997')\n assert token == '545a596ab96b289c60896255e8690288'\n session_id = await authenticator.get_session_id_and_close()\n assert session_id == '1'\n assert len(aioresponse.requests) == 6\n print(aioresponse.requests)\n request = aioresponse.requests['POST', URL(\n 'http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=1'\n )]\n assert request[0].kwargs['data'\n ] == '{\"auth_Data\":{\"auth_type\":\"SPC\",\"GeneratorServerHello\":\"010200000000000000008A000000063635343332317CAF9CBDC06B666D23EBCA615E0666FEB2B807091BF507404DDD18329CD64A91E513DC704298CCE49C4C5656C42141A696354A7145127BCD94CDD2B0D632D87E332437F86EBE5A50A1512F3F54C71B791A88ECBAF562FBABE2731F27D851A764CA114DBE2C2C965DF151CFC7401920FAA04636B356B97DBE1DA3A090004F81830000000000\"}}'\n request = aioresponse.requests['POST', URL(\n 'http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=2'\n )]\n assert request[0].kwargs['data'\n ] == '{\"auth_Data\":{\"auth_type\":\"SPC\",\"request_id\":\"0\",\"ServerAckMsg\":\"01030000000000000000145F38EAFF0F6A6FF062CA652CD6CBAD9AF1EC62470000000000\"}}'\n", "step-3": "<mask token>\nimport aiohttp\nfrom aioresponses import aioresponses\nimport pytest\nfrom yarl import URL\nfrom samsungtvws.encrypted.authenticator import SamsungTVEncryptedWSAsyncAuthenticator\n\n\n@pytest.mark.asyncio\nasync def test_authenticator(aioresponse: aioresponses) ->None:\n with open('tests/fixtures/auth_pin_status.xml') as file:\n aioresponse.get('http://1.2.3.4:8080/ws/apps/CloudPINPage', body=\n file.read())\n with open('tests/fixtures/auth_pin_status.xml') as file:\n aioresponse.post('http://1.2.3.4:8080/ws/apps/CloudPINPage', body=\n 'http:///ws/apps/CloudPINPage/run')\n with open('tests/fixtures/auth_empty.json') as file:\n aioresponse.get(\n 'http://1.2.3.4:8080/ws/pairing?step=0&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&type=1'\n , body=file.read())\n with open('tests/fixtures/auth_generator_client_hello.json') as file:\n aioresponse.post(\n 'http://1.2.3.4:8080/ws/pairing?step=1&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184'\n , body=file.read())\n with open('tests/fixtures/auth_client_ack_msg.json') as file:\n aioresponse.post(\n 'http://1.2.3.4:8080/ws/pairing?step=2&app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184'\n , body=file.read())\n aioresponse.delete('http://1.2.3.4:8080/ws/apps/CloudPINPage/run', body='')\n authenticator = SamsungTVEncryptedWSAsyncAuthenticator('1.2.3.4',\n web_session=aiohttp.ClientSession())\n await authenticator.start_pairing()\n token = await authenticator.try_pin('0997')\n assert token == '545a596ab96b289c60896255e8690288'\n session_id = await authenticator.get_session_id_and_close()\n assert session_id == '1'\n assert len(aioresponse.requests) == 6\n print(aioresponse.requests)\n request = aioresponse.requests['POST', URL(\n 'http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=1'\n )]\n assert request[0].kwargs['data'\n ] == '{\"auth_Data\":{\"auth_type\":\"SPC\",\"GeneratorServerHello\":\"010200000000000000008A000000063635343332317CAF9CBDC06B666D23EBCA615E0666FEB2B807091BF507404DDD18329CD64A91E513DC704298CCE49C4C5656C42141A696354A7145127BCD94CDD2B0D632D87E332437F86EBE5A50A1512F3F54C71B791A88ECBAF562FBABE2731F27D851A764CA114DBE2C2C965DF151CFC7401920FAA04636B356B97DBE1DA3A090004F81830000000000\"}}'\n request = aioresponse.requests['POST', URL(\n 'http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=2'\n )]\n assert request[0].kwargs['data'\n ] == '{\"auth_Data\":{\"auth_type\":\"SPC\",\"request_id\":\"0\",\"ServerAckMsg\":\"01030000000000000000145F38EAFF0F6A6FF062CA652CD6CBAD9AF1EC62470000000000\"}}'\n", "step-4": "\"\"\"SamsungTV Encrypted.\"\"\"\nimport aiohttp\nfrom aioresponses import aioresponses\nimport pytest\nfrom yarl import URL\n\nfrom samsungtvws.encrypted.authenticator import SamsungTVEncryptedWSAsyncAuthenticator\n\n\n@pytest.mark.asyncio\nasync def test_authenticator(aioresponse: aioresponses) -> None:\n with open(\"tests/fixtures/auth_pin_status.xml\") as file:\n aioresponse.get(\"http://1.2.3.4:8080/ws/apps/CloudPINPage\", body=file.read())\n with open(\"tests/fixtures/auth_pin_status.xml\") as file:\n aioresponse.post(\n \"http://1.2.3.4:8080/ws/apps/CloudPINPage\",\n body=\"http:///ws/apps/CloudPINPage/run\",\n )\n with open(\"tests/fixtures/auth_empty.json\") as file:\n aioresponse.get(\n \"http://1.2.3.4:8080/ws/pairing?step=0&app_id=12345\"\n \"&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&type=1\",\n body=file.read(),\n )\n with open(\"tests/fixtures/auth_generator_client_hello.json\") as file:\n aioresponse.post(\n \"http://1.2.3.4:8080/ws/pairing?step=1&app_id=12345\"\n \"&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184\",\n body=file.read(),\n )\n with open(\"tests/fixtures/auth_client_ack_msg.json\") as file:\n aioresponse.post(\n \"http://1.2.3.4:8080/ws/pairing?step=2&app_id=12345\"\n \"&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184\",\n body=file.read(),\n )\n aioresponse.delete(\"http://1.2.3.4:8080/ws/apps/CloudPINPage/run\", body=\"\")\n\n authenticator = SamsungTVEncryptedWSAsyncAuthenticator(\n \"1.2.3.4\", web_session=aiohttp.ClientSession()\n )\n await authenticator.start_pairing()\n token = await authenticator.try_pin(\"0997\")\n assert token == \"545a596ab96b289c60896255e8690288\"\n\n session_id = await authenticator.get_session_id_and_close()\n assert session_id == \"1\"\n\n assert len(aioresponse.requests) == 6\n print(aioresponse.requests)\n\n request = aioresponse.requests[\n (\n \"POST\",\n URL(\n \"http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=1\"\n ),\n )\n ]\n assert (\n request[0].kwargs[\"data\"]\n == '{\"auth_Data\":{\"auth_type\":\"SPC\",\"GeneratorServerHello\":'\n '\"010200000000000000008A000000063635343332317CAF9CBDC06B666D23EBC'\n \"A615E0666FEB2B807091BF507404DDD18329CD64A91E513DC704298CCE49C4C5\"\n \"656C42141A696354A7145127BCD94CDD2B0D632D87E332437F86EBE5A50A1512\"\n \"F3F54C71B791A88ECBAF562FBABE2731F27D851A764CA114DBE2C2C965DF151C\"\n 'FC7401920FAA04636B356B97DBE1DA3A090004F81830000000000\"}}'\n )\n request = aioresponse.requests[\n (\n \"POST\",\n URL(\n \"http://1.2.3.4:8080/ws/pairing?app_id=12345&device_id=7e509404-9d7c-46b4-8f6a-e2a9668ad184&step=2\"\n ),\n )\n ]\n assert (\n request[0].kwargs[\"data\"]\n == '{\"auth_Data\":{\"auth_type\":\"SPC\",\"request_id\":\"0\",\"ServerAckMsg\":'\n '\"01030000000000000000145F38EAFF0F6A6FF062CA652CD6CBAD9AF1EC62470000000000\"}}'\n )\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def parse_response(permission, response): return response <|reserved_special_token_1|> <|reserved_special_token_0|> def get_command(session, parsed_message): return 'stop', 'restart' def parse_response(permission, response): return response <|reserved_special_token_1|> permissions = 'restart', commands = 'restart', def get_command(session, parsed_message): return 'stop', 'restart' def parse_response(permission, response): return response <|reserved_special_token_1|> permissions = ('restart', ) commands = ('restart', ) def get_command(session, parsed_message): return 'stop', 'restart' def parse_response(permission, response): return response
flexible
{ "blob_id": "acd5cf675522c90fc9fbc96bdeb52f66835626b4", "index": 3489, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef parse_response(permission, response):\n return response\n", "step-3": "<mask token>\n\n\ndef get_command(session, parsed_message):\n return 'stop', 'restart'\n\n\ndef parse_response(permission, response):\n return response\n", "step-4": "permissions = 'restart',\ncommands = 'restart',\n\n\ndef get_command(session, parsed_message):\n return 'stop', 'restart'\n\n\ndef parse_response(permission, response):\n return response\n", "step-5": "permissions = ('restart', )\ncommands = ('restart', )\n\n\ndef get_command(session, parsed_message):\n return 'stop', 'restart'\n\n\ndef parse_response(permission, response):\n return response\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class USBHandler: <|reserved_special_token_0|> def __init__(self): self.initialized = False self.run_task = None self.waiters = {} self.queues = {} self.logger = logging.getLogger('.'.join((__name__, self.__class__. __name__))) async def initialize(self, device_path: str) ->None: assert os.path.exists(device_path) self.logger.info('Initializing USBReader.') self.logger.debug('Opening serial connection to device at %s', device_path) self.serial_reader, self.serial_writer = await open_serial_connection( url=device_path, baudrate=115200) self.initialized = True self.logger.debug('Connected to serial device at %s.', device_path) async def _run(self) ->None: while True: message = await self.serial_reader.readuntil(separator=b'\r\n') stripped_message = message.decode(encoding='ascii').rstrip('\n\r') self.logger.debug("Read '%s' from MDB board.", stripped_message) message_type = stripped_message[0] if message_type in self.waiters: self.waiters[message_type].set_result(stripped_message) del self.waiters[message_type] await asyncio.sleep(0) elif message_type in self.queues: try: self.queues[message_type].put_nowait(stripped_message) except asyncio.QueueFull: self.logger.warning( 'Queue for message type %s is full. Scheduling the put in another task.' , message_type) asyncio.create_task(self.queues[message_type].put( stripped_message)) else: self.logger.error('Unhandled message: %s', stripped_message) async def run(self) ->None: assert self.initialized self.logger.info('Starting runner.') self.run_task = asyncio.create_task(self._run()) try: await self.run_task except asyncio.CancelledError: self.logger.info('Runner cancelled.') async def send(self, message: AsciiBytes, _drain=True) ->None: assert self.initialized self.logger.info('Sending message to MDB board: %s', message) self.serial_writer.write(message) if _drain: await self.serial_writer.drain() self.logger.info('Sent message to MDB board: %s', message) <|reserved_special_token_0|> async def sendread(self, message: AsciiBytes, prefix: str) ->str: await self.send(message, _drain=False) fut = self._read_internal(prefix) self.logger.info('Waiting for a single message of type: %s', prefix) try: await self.serial_writer.drain() self.logger.info('Sent message to MDB board: %s', message) await fut except asyncio.CancelledError as e: self.logger.warning( 'Got cancelled while sending message %r or waiting on prefix %s' , message, prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info('Got message: %s', fut.result()) return fut.result() async def read(self, prefix: str) ->str: fut = self._read_internal(prefix) self.logger.info('Waiting for a single message of type: %s', prefix) try: await fut except asyncio.CancelledError as e: self.logger.warning('Got cancelled while waiting for message on %s' , prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info('Got message: %s', fut.result()) return fut.result() def listen(self, prefix: str) ->asyncio.Queue: assert len(prefix) == 1 if prefix in self.waiters or prefix in self.queues: raise RuntimeError( f'Tried to get a queue for message type {prefix} when there was already someonewaiting on it.' ) self.queues[prefix] = asyncio.Queue() self.logger.info('Polling for messages of type: %s', prefix) return self.queues[prefix] <|reserved_special_token_0|> async def shutdown(self): if not self.initialized: return self.logger.info('Shutting down.') if self.run_task: self.run_task.cancel() self.run_task = None for fut in self.waiters.values(): fut.cancel() self.serial_writer.close() await self.serial_writer.wait_closed() self.logger.info('Shutdown complete.') self.initialized = False <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def to_ascii(s: str) ->AsciiBytes: if s[-1] != '\n': s += '\n' return cast(AsciiBytes, s.encode(encoding='ascii')) class USBHandler: """Reads from and writes to the underlying MDB USB board. Users can either obtain an asyncio.Queue that the handler will push messages to using listen(), or it can ask for a one-time read using read(). For sending messages, if no reply is expected or there is a poller waiting for any response, send() can be used, otherwise sendread() will send the message and wait for a one-time reply. Having a listener and waiting for a single message at the same time is an error. See the Sniffer class for an example of both usages.""" def __init__(self): self.initialized = False self.run_task = None self.waiters = {} self.queues = {} self.logger = logging.getLogger('.'.join((__name__, self.__class__. __name__))) async def initialize(self, device_path: str) ->None: assert os.path.exists(device_path) self.logger.info('Initializing USBReader.') self.logger.debug('Opening serial connection to device at %s', device_path) self.serial_reader, self.serial_writer = await open_serial_connection( url=device_path, baudrate=115200) self.initialized = True self.logger.debug('Connected to serial device at %s.', device_path) async def _run(self) ->None: while True: message = await self.serial_reader.readuntil(separator=b'\r\n') stripped_message = message.decode(encoding='ascii').rstrip('\n\r') self.logger.debug("Read '%s' from MDB board.", stripped_message) message_type = stripped_message[0] if message_type in self.waiters: self.waiters[message_type].set_result(stripped_message) del self.waiters[message_type] await asyncio.sleep(0) elif message_type in self.queues: try: self.queues[message_type].put_nowait(stripped_message) except asyncio.QueueFull: self.logger.warning( 'Queue for message type %s is full. Scheduling the put in another task.' , message_type) asyncio.create_task(self.queues[message_type].put( stripped_message)) else: self.logger.error('Unhandled message: %s', stripped_message) async def run(self) ->None: assert self.initialized self.logger.info('Starting runner.') self.run_task = asyncio.create_task(self._run()) try: await self.run_task except asyncio.CancelledError: self.logger.info('Runner cancelled.') async def send(self, message: AsciiBytes, _drain=True) ->None: assert self.initialized self.logger.info('Sending message to MDB board: %s', message) self.serial_writer.write(message) if _drain: await self.serial_writer.drain() self.logger.info('Sent message to MDB board: %s', message) def _read_internal(self, prefix: str) ->asyncio.Future: assert len(prefix) == 1 if prefix in self.queues or prefix in self.waiters: raise RuntimeError( f'Tried to wait for message type {prefix} when there was already a queue listening to all messages' ) fut = asyncio.get_running_loop().create_future() self.waiters[prefix] = fut return fut async def sendread(self, message: AsciiBytes, prefix: str) ->str: await self.send(message, _drain=False) fut = self._read_internal(prefix) self.logger.info('Waiting for a single message of type: %s', prefix) try: await self.serial_writer.drain() self.logger.info('Sent message to MDB board: %s', message) await fut except asyncio.CancelledError as e: self.logger.warning( 'Got cancelled while sending message %r or waiting on prefix %s' , message, prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info('Got message: %s', fut.result()) return fut.result() async def read(self, prefix: str) ->str: fut = self._read_internal(prefix) self.logger.info('Waiting for a single message of type: %s', prefix) try: await fut except asyncio.CancelledError as e: self.logger.warning('Got cancelled while waiting for message on %s' , prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info('Got message: %s', fut.result()) return fut.result() def listen(self, prefix: str) ->asyncio.Queue: assert len(prefix) == 1 if prefix in self.waiters or prefix in self.queues: raise RuntimeError( f'Tried to get a queue for message type {prefix} when there was already someonewaiting on it.' ) self.queues[prefix] = asyncio.Queue() self.logger.info('Polling for messages of type: %s', prefix) return self.queues[prefix] def unlisten(self, prefix: str) ->None: """Stops pushing messages with this prefix character to a Queue.""" assert len(prefix) == 1 del self.queues[prefix] self.logger.info('No longer polling for message type: %s', prefix) async def shutdown(self): if not self.initialized: return self.logger.info('Shutting down.') if self.run_task: self.run_task.cancel() self.run_task = None for fut in self.waiters.values(): fut.cancel() self.serial_writer.close() await self.serial_writer.wait_closed() self.logger.info('Shutdown complete.') self.initialized = False <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> AsciiBytes = NewType('AsciiBytes', bytes) def to_ascii(s: str) ->AsciiBytes: if s[-1] != '\n': s += '\n' return cast(AsciiBytes, s.encode(encoding='ascii')) class USBHandler: """Reads from and writes to the underlying MDB USB board. Users can either obtain an asyncio.Queue that the handler will push messages to using listen(), or it can ask for a one-time read using read(). For sending messages, if no reply is expected or there is a poller waiting for any response, send() can be used, otherwise sendread() will send the message and wait for a one-time reply. Having a listener and waiting for a single message at the same time is an error. See the Sniffer class for an example of both usages.""" def __init__(self): self.initialized = False self.run_task = None self.waiters = {} self.queues = {} self.logger = logging.getLogger('.'.join((__name__, self.__class__. __name__))) async def initialize(self, device_path: str) ->None: assert os.path.exists(device_path) self.logger.info('Initializing USBReader.') self.logger.debug('Opening serial connection to device at %s', device_path) self.serial_reader, self.serial_writer = await open_serial_connection( url=device_path, baudrate=115200) self.initialized = True self.logger.debug('Connected to serial device at %s.', device_path) async def _run(self) ->None: while True: message = await self.serial_reader.readuntil(separator=b'\r\n') stripped_message = message.decode(encoding='ascii').rstrip('\n\r') self.logger.debug("Read '%s' from MDB board.", stripped_message) message_type = stripped_message[0] if message_type in self.waiters: self.waiters[message_type].set_result(stripped_message) del self.waiters[message_type] await asyncio.sleep(0) elif message_type in self.queues: try: self.queues[message_type].put_nowait(stripped_message) except asyncio.QueueFull: self.logger.warning( 'Queue for message type %s is full. Scheduling the put in another task.' , message_type) asyncio.create_task(self.queues[message_type].put( stripped_message)) else: self.logger.error('Unhandled message: %s', stripped_message) async def run(self) ->None: assert self.initialized self.logger.info('Starting runner.') self.run_task = asyncio.create_task(self._run()) try: await self.run_task except asyncio.CancelledError: self.logger.info('Runner cancelled.') async def send(self, message: AsciiBytes, _drain=True) ->None: assert self.initialized self.logger.info('Sending message to MDB board: %s', message) self.serial_writer.write(message) if _drain: await self.serial_writer.drain() self.logger.info('Sent message to MDB board: %s', message) def _read_internal(self, prefix: str) ->asyncio.Future: assert len(prefix) == 1 if prefix in self.queues or prefix in self.waiters: raise RuntimeError( f'Tried to wait for message type {prefix} when there was already a queue listening to all messages' ) fut = asyncio.get_running_loop().create_future() self.waiters[prefix] = fut return fut async def sendread(self, message: AsciiBytes, prefix: str) ->str: await self.send(message, _drain=False) fut = self._read_internal(prefix) self.logger.info('Waiting for a single message of type: %s', prefix) try: await self.serial_writer.drain() self.logger.info('Sent message to MDB board: %s', message) await fut except asyncio.CancelledError as e: self.logger.warning( 'Got cancelled while sending message %r or waiting on prefix %s' , message, prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info('Got message: %s', fut.result()) return fut.result() async def read(self, prefix: str) ->str: fut = self._read_internal(prefix) self.logger.info('Waiting for a single message of type: %s', prefix) try: await fut except asyncio.CancelledError as e: self.logger.warning('Got cancelled while waiting for message on %s' , prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info('Got message: %s', fut.result()) return fut.result() def listen(self, prefix: str) ->asyncio.Queue: assert len(prefix) == 1 if prefix in self.waiters or prefix in self.queues: raise RuntimeError( f'Tried to get a queue for message type {prefix} when there was already someonewaiting on it.' ) self.queues[prefix] = asyncio.Queue() self.logger.info('Polling for messages of type: %s', prefix) return self.queues[prefix] def unlisten(self, prefix: str) ->None: """Stops pushing messages with this prefix character to a Queue.""" assert len(prefix) == 1 del self.queues[prefix] self.logger.info('No longer polling for message type: %s', prefix) async def shutdown(self): if not self.initialized: return self.logger.info('Shutting down.') if self.run_task: self.run_task.cancel() self.run_task = None for fut in self.waiters.values(): fut.cancel() self.serial_writer.close() await self.serial_writer.wait_closed() self.logger.info('Shutdown complete.') self.initialized = False __all__ = USBHandler, to_ascii <|reserved_special_token_1|> import asyncio import logging import os.path from serial_asyncio import open_serial_connection from typing import NewType, cast AsciiBytes = NewType('AsciiBytes', bytes) def to_ascii(s: str) ->AsciiBytes: if s[-1] != '\n': s += '\n' return cast(AsciiBytes, s.encode(encoding='ascii')) class USBHandler: """Reads from and writes to the underlying MDB USB board. Users can either obtain an asyncio.Queue that the handler will push messages to using listen(), or it can ask for a one-time read using read(). For sending messages, if no reply is expected or there is a poller waiting for any response, send() can be used, otherwise sendread() will send the message and wait for a one-time reply. Having a listener and waiting for a single message at the same time is an error. See the Sniffer class for an example of both usages.""" def __init__(self): self.initialized = False self.run_task = None self.waiters = {} self.queues = {} self.logger = logging.getLogger('.'.join((__name__, self.__class__. __name__))) async def initialize(self, device_path: str) ->None: assert os.path.exists(device_path) self.logger.info('Initializing USBReader.') self.logger.debug('Opening serial connection to device at %s', device_path) self.serial_reader, self.serial_writer = await open_serial_connection( url=device_path, baudrate=115200) self.initialized = True self.logger.debug('Connected to serial device at %s.', device_path) async def _run(self) ->None: while True: message = await self.serial_reader.readuntil(separator=b'\r\n') stripped_message = message.decode(encoding='ascii').rstrip('\n\r') self.logger.debug("Read '%s' from MDB board.", stripped_message) message_type = stripped_message[0] if message_type in self.waiters: self.waiters[message_type].set_result(stripped_message) del self.waiters[message_type] await asyncio.sleep(0) elif message_type in self.queues: try: self.queues[message_type].put_nowait(stripped_message) except asyncio.QueueFull: self.logger.warning( 'Queue for message type %s is full. Scheduling the put in another task.' , message_type) asyncio.create_task(self.queues[message_type].put( stripped_message)) else: self.logger.error('Unhandled message: %s', stripped_message) async def run(self) ->None: assert self.initialized self.logger.info('Starting runner.') self.run_task = asyncio.create_task(self._run()) try: await self.run_task except asyncio.CancelledError: self.logger.info('Runner cancelled.') async def send(self, message: AsciiBytes, _drain=True) ->None: assert self.initialized self.logger.info('Sending message to MDB board: %s', message) self.serial_writer.write(message) if _drain: await self.serial_writer.drain() self.logger.info('Sent message to MDB board: %s', message) def _read_internal(self, prefix: str) ->asyncio.Future: assert len(prefix) == 1 if prefix in self.queues or prefix in self.waiters: raise RuntimeError( f'Tried to wait for message type {prefix} when there was already a queue listening to all messages' ) fut = asyncio.get_running_loop().create_future() self.waiters[prefix] = fut return fut async def sendread(self, message: AsciiBytes, prefix: str) ->str: await self.send(message, _drain=False) fut = self._read_internal(prefix) self.logger.info('Waiting for a single message of type: %s', prefix) try: await self.serial_writer.drain() self.logger.info('Sent message to MDB board: %s', message) await fut except asyncio.CancelledError as e: self.logger.warning( 'Got cancelled while sending message %r or waiting on prefix %s' , message, prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info('Got message: %s', fut.result()) return fut.result() async def read(self, prefix: str) ->str: fut = self._read_internal(prefix) self.logger.info('Waiting for a single message of type: %s', prefix) try: await fut except asyncio.CancelledError as e: self.logger.warning('Got cancelled while waiting for message on %s' , prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info('Got message: %s', fut.result()) return fut.result() def listen(self, prefix: str) ->asyncio.Queue: assert len(prefix) == 1 if prefix in self.waiters or prefix in self.queues: raise RuntimeError( f'Tried to get a queue for message type {prefix} when there was already someonewaiting on it.' ) self.queues[prefix] = asyncio.Queue() self.logger.info('Polling for messages of type: %s', prefix) return self.queues[prefix] def unlisten(self, prefix: str) ->None: """Stops pushing messages with this prefix character to a Queue.""" assert len(prefix) == 1 del self.queues[prefix] self.logger.info('No longer polling for message type: %s', prefix) async def shutdown(self): if not self.initialized: return self.logger.info('Shutting down.') if self.run_task: self.run_task.cancel() self.run_task = None for fut in self.waiters.values(): fut.cancel() self.serial_writer.close() await self.serial_writer.wait_closed() self.logger.info('Shutdown complete.') self.initialized = False __all__ = USBHandler, to_ascii <|reserved_special_token_1|> import asyncio import logging import os.path from serial_asyncio import open_serial_connection from typing import NewType, cast # Type annotations and converters AsciiBytes = NewType('AsciiBytes', bytes) def to_ascii(s: str) -> AsciiBytes: if s[-1] != '\n': s += '\n' return cast(AsciiBytes, s.encode(encoding='ascii')) class USBHandler: """Reads from and writes to the underlying MDB USB board. Users can either obtain an asyncio.Queue that the handler will push messages to using listen(), or it can ask for a one-time read using read(). For sending messages, if no reply is expected or there is a poller waiting for any response, send() can be used, otherwise sendread() will send the message and wait for a one-time reply. Having a listener and waiting for a single message at the same time is an error. See the Sniffer class for an example of both usages.""" def __init__(self): self.initialized = False self.run_task = None self.waiters = {} self.queues = {} self.logger = logging.getLogger('.'.join((__name__, self.__class__.__name__))) async def initialize(self, device_path: str) -> None: assert os.path.exists(device_path) self.logger.info("Initializing USBReader.") self.logger.debug("Opening serial connection to device at %s", device_path) self.serial_reader, self.serial_writer = \ await open_serial_connection(url=device_path, baudrate=115200) self.initialized = True self.logger.debug("Connected to serial device at %s.", device_path) async def _run(self) -> None: while True: message = await self.serial_reader.readuntil(separator=b'\r\n') stripped_message = message.decode(encoding='ascii').rstrip('\n\r') self.logger.debug("Read '%s' from MDB board.", stripped_message) message_type = stripped_message[0] if message_type in self.waiters: self.waiters[message_type].set_result(stripped_message) del self.waiters[message_type] # Lets the waiter run. await asyncio.sleep(0) elif message_type in self.queues: try: self.queues[message_type].put_nowait(stripped_message) except asyncio.QueueFull: self.logger.warning('Queue for message type %s is full. ' 'Scheduling the put in another task.', message_type) asyncio.create_task( self.queues[message_type].put(stripped_message)) else: self.logger.error("Unhandled message: %s", stripped_message) async def run(self) -> None: assert self.initialized self.logger.info('Starting runner.') self.run_task = asyncio.create_task(self._run()) try: await self.run_task except asyncio.CancelledError: self.logger.info('Runner cancelled.') async def send(self, message: AsciiBytes, _drain=True) -> None: assert self.initialized self.logger.info("Sending message to MDB board: %s", message) self.serial_writer.write(message) if _drain: await self.serial_writer.drain() self.logger.info("Sent message to MDB board: %s", message) def _read_internal(self, prefix: str) -> asyncio.Future: assert len(prefix) == 1 if prefix in self.queues or prefix in self.waiters: raise RuntimeError(f"Tried to wait for message type {prefix}" " when there was already a queue listening to " "all messages") fut = asyncio.get_running_loop().create_future() self.waiters[prefix] = fut return fut async def sendread(self, message: AsciiBytes, prefix: str) -> str: await self.send(message, _drain=False) fut = self._read_internal(prefix) self.logger.info("Waiting for a single message of type: %s", prefix) try: await self.serial_writer.drain() self.logger.info("Sent message to MDB board: %s", message) await fut except asyncio.CancelledError as e: self.logger.warning("Got cancelled while sending message %r or " "waiting on prefix %s", message, prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info("Got message: %s", fut.result()) return fut.result() async def read(self, prefix: str) -> str: fut = self._read_internal(prefix) self.logger.info("Waiting for a single message of type: %s", prefix) try: await fut except asyncio.CancelledError as e: self.logger.warning("Got cancelled while waiting for message on " "%s", prefix, exc_info=e) del self.waiters[prefix] raise self.logger.info("Got message: %s", fut.result()) return fut.result() def listen(self, prefix: str) -> asyncio.Queue: assert len(prefix) == 1 if prefix in self.waiters or prefix in self.queues: raise RuntimeError("Tried to get a queue for message type " f"{prefix} when there was already someone" "waiting on it.") self.queues[prefix] = asyncio.Queue() self.logger.info("Polling for messages of type: %s", prefix) return self.queues[prefix] def unlisten(self, prefix: str) -> None: """Stops pushing messages with this prefix character to a Queue.""" assert len(prefix) == 1 del self.queues[prefix] self.logger.info("No longer polling for message type: %s", prefix) async def shutdown(self): if not self.initialized: return self.logger.info("Shutting down.") if self.run_task: self.run_task.cancel() self.run_task = None for fut in self.waiters.values(): fut.cancel() self.serial_writer.close() await self.serial_writer.wait_closed() self.logger.info("Shutdown complete.") self.initialized = False __all__ = (USBHandler, to_ascii)
flexible
{ "blob_id": "50b630b762251f8646044b234ac4b82b8e4b645b", "index": 8460, "step-1": "<mask token>\n\n\nclass USBHandler:\n <mask token>\n\n def __init__(self):\n self.initialized = False\n self.run_task = None\n self.waiters = {}\n self.queues = {}\n self.logger = logging.getLogger('.'.join((__name__, self.__class__.\n __name__)))\n\n async def initialize(self, device_path: str) ->None:\n assert os.path.exists(device_path)\n self.logger.info('Initializing USBReader.')\n self.logger.debug('Opening serial connection to device at %s',\n device_path)\n self.serial_reader, self.serial_writer = await open_serial_connection(\n url=device_path, baudrate=115200)\n self.initialized = True\n self.logger.debug('Connected to serial device at %s.', device_path)\n\n async def _run(self) ->None:\n while True:\n message = await self.serial_reader.readuntil(separator=b'\\r\\n')\n stripped_message = message.decode(encoding='ascii').rstrip('\\n\\r')\n self.logger.debug(\"Read '%s' from MDB board.\", stripped_message)\n message_type = stripped_message[0]\n if message_type in self.waiters:\n self.waiters[message_type].set_result(stripped_message)\n del self.waiters[message_type]\n await asyncio.sleep(0)\n elif message_type in self.queues:\n try:\n self.queues[message_type].put_nowait(stripped_message)\n except asyncio.QueueFull:\n self.logger.warning(\n 'Queue for message type %s is full. Scheduling the put in another task.'\n , message_type)\n asyncio.create_task(self.queues[message_type].put(\n stripped_message))\n else:\n self.logger.error('Unhandled message: %s', stripped_message)\n\n async def run(self) ->None:\n assert self.initialized\n self.logger.info('Starting runner.')\n self.run_task = asyncio.create_task(self._run())\n try:\n await self.run_task\n except asyncio.CancelledError:\n self.logger.info('Runner cancelled.')\n\n async def send(self, message: AsciiBytes, _drain=True) ->None:\n assert self.initialized\n self.logger.info('Sending message to MDB board: %s', message)\n self.serial_writer.write(message)\n if _drain:\n await self.serial_writer.drain()\n self.logger.info('Sent message to MDB board: %s', message)\n <mask token>\n\n async def sendread(self, message: AsciiBytes, prefix: str) ->str:\n await self.send(message, _drain=False)\n fut = self._read_internal(prefix)\n self.logger.info('Waiting for a single message of type: %s', prefix)\n try:\n await self.serial_writer.drain()\n self.logger.info('Sent message to MDB board: %s', message)\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning(\n 'Got cancelled while sending message %r or waiting on prefix %s'\n , message, prefix, exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info('Got message: %s', fut.result())\n return fut.result()\n\n async def read(self, prefix: str) ->str:\n fut = self._read_internal(prefix)\n self.logger.info('Waiting for a single message of type: %s', prefix)\n try:\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning('Got cancelled while waiting for message on %s'\n , prefix, exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info('Got message: %s', fut.result())\n return fut.result()\n\n def listen(self, prefix: str) ->asyncio.Queue:\n assert len(prefix) == 1\n if prefix in self.waiters or prefix in self.queues:\n raise RuntimeError(\n f'Tried to get a queue for message type {prefix} when there was already someonewaiting on it.'\n )\n self.queues[prefix] = asyncio.Queue()\n self.logger.info('Polling for messages of type: %s', prefix)\n return self.queues[prefix]\n <mask token>\n\n async def shutdown(self):\n if not self.initialized:\n return\n self.logger.info('Shutting down.')\n if self.run_task:\n self.run_task.cancel()\n self.run_task = None\n for fut in self.waiters.values():\n fut.cancel()\n self.serial_writer.close()\n await self.serial_writer.wait_closed()\n self.logger.info('Shutdown complete.')\n self.initialized = False\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef to_ascii(s: str) ->AsciiBytes:\n if s[-1] != '\\n':\n s += '\\n'\n return cast(AsciiBytes, s.encode(encoding='ascii'))\n\n\nclass USBHandler:\n \"\"\"Reads from and writes to the underlying MDB USB board.\n\n Users can either obtain an asyncio.Queue that the handler will push\n messages to using listen(), or it can ask for a one-time read using read().\n For sending messages, if no reply is expected or there is a poller waiting\n for any response, send() can be used, otherwise sendread() will send the\n message and wait for a one-time reply. Having a listener and waiting for a\n single message at the same time is an error. See the Sniffer class for an\n example of both usages.\"\"\"\n\n def __init__(self):\n self.initialized = False\n self.run_task = None\n self.waiters = {}\n self.queues = {}\n self.logger = logging.getLogger('.'.join((__name__, self.__class__.\n __name__)))\n\n async def initialize(self, device_path: str) ->None:\n assert os.path.exists(device_path)\n self.logger.info('Initializing USBReader.')\n self.logger.debug('Opening serial connection to device at %s',\n device_path)\n self.serial_reader, self.serial_writer = await open_serial_connection(\n url=device_path, baudrate=115200)\n self.initialized = True\n self.logger.debug('Connected to serial device at %s.', device_path)\n\n async def _run(self) ->None:\n while True:\n message = await self.serial_reader.readuntil(separator=b'\\r\\n')\n stripped_message = message.decode(encoding='ascii').rstrip('\\n\\r')\n self.logger.debug(\"Read '%s' from MDB board.\", stripped_message)\n message_type = stripped_message[0]\n if message_type in self.waiters:\n self.waiters[message_type].set_result(stripped_message)\n del self.waiters[message_type]\n await asyncio.sleep(0)\n elif message_type in self.queues:\n try:\n self.queues[message_type].put_nowait(stripped_message)\n except asyncio.QueueFull:\n self.logger.warning(\n 'Queue for message type %s is full. Scheduling the put in another task.'\n , message_type)\n asyncio.create_task(self.queues[message_type].put(\n stripped_message))\n else:\n self.logger.error('Unhandled message: %s', stripped_message)\n\n async def run(self) ->None:\n assert self.initialized\n self.logger.info('Starting runner.')\n self.run_task = asyncio.create_task(self._run())\n try:\n await self.run_task\n except asyncio.CancelledError:\n self.logger.info('Runner cancelled.')\n\n async def send(self, message: AsciiBytes, _drain=True) ->None:\n assert self.initialized\n self.logger.info('Sending message to MDB board: %s', message)\n self.serial_writer.write(message)\n if _drain:\n await self.serial_writer.drain()\n self.logger.info('Sent message to MDB board: %s', message)\n\n def _read_internal(self, prefix: str) ->asyncio.Future:\n assert len(prefix) == 1\n if prefix in self.queues or prefix in self.waiters:\n raise RuntimeError(\n f'Tried to wait for message type {prefix} when there was already a queue listening to all messages'\n )\n fut = asyncio.get_running_loop().create_future()\n self.waiters[prefix] = fut\n return fut\n\n async def sendread(self, message: AsciiBytes, prefix: str) ->str:\n await self.send(message, _drain=False)\n fut = self._read_internal(prefix)\n self.logger.info('Waiting for a single message of type: %s', prefix)\n try:\n await self.serial_writer.drain()\n self.logger.info('Sent message to MDB board: %s', message)\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning(\n 'Got cancelled while sending message %r or waiting on prefix %s'\n , message, prefix, exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info('Got message: %s', fut.result())\n return fut.result()\n\n async def read(self, prefix: str) ->str:\n fut = self._read_internal(prefix)\n self.logger.info('Waiting for a single message of type: %s', prefix)\n try:\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning('Got cancelled while waiting for message on %s'\n , prefix, exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info('Got message: %s', fut.result())\n return fut.result()\n\n def listen(self, prefix: str) ->asyncio.Queue:\n assert len(prefix) == 1\n if prefix in self.waiters or prefix in self.queues:\n raise RuntimeError(\n f'Tried to get a queue for message type {prefix} when there was already someonewaiting on it.'\n )\n self.queues[prefix] = asyncio.Queue()\n self.logger.info('Polling for messages of type: %s', prefix)\n return self.queues[prefix]\n\n def unlisten(self, prefix: str) ->None:\n \"\"\"Stops pushing messages with this prefix character to a Queue.\"\"\"\n assert len(prefix) == 1\n del self.queues[prefix]\n self.logger.info('No longer polling for message type: %s', prefix)\n\n async def shutdown(self):\n if not self.initialized:\n return\n self.logger.info('Shutting down.')\n if self.run_task:\n self.run_task.cancel()\n self.run_task = None\n for fut in self.waiters.values():\n fut.cancel()\n self.serial_writer.close()\n await self.serial_writer.wait_closed()\n self.logger.info('Shutdown complete.')\n self.initialized = False\n\n\n<mask token>\n", "step-3": "<mask token>\nAsciiBytes = NewType('AsciiBytes', bytes)\n\n\ndef to_ascii(s: str) ->AsciiBytes:\n if s[-1] != '\\n':\n s += '\\n'\n return cast(AsciiBytes, s.encode(encoding='ascii'))\n\n\nclass USBHandler:\n \"\"\"Reads from and writes to the underlying MDB USB board.\n\n Users can either obtain an asyncio.Queue that the handler will push\n messages to using listen(), or it can ask for a one-time read using read().\n For sending messages, if no reply is expected or there is a poller waiting\n for any response, send() can be used, otherwise sendread() will send the\n message and wait for a one-time reply. Having a listener and waiting for a\n single message at the same time is an error. See the Sniffer class for an\n example of both usages.\"\"\"\n\n def __init__(self):\n self.initialized = False\n self.run_task = None\n self.waiters = {}\n self.queues = {}\n self.logger = logging.getLogger('.'.join((__name__, self.__class__.\n __name__)))\n\n async def initialize(self, device_path: str) ->None:\n assert os.path.exists(device_path)\n self.logger.info('Initializing USBReader.')\n self.logger.debug('Opening serial connection to device at %s',\n device_path)\n self.serial_reader, self.serial_writer = await open_serial_connection(\n url=device_path, baudrate=115200)\n self.initialized = True\n self.logger.debug('Connected to serial device at %s.', device_path)\n\n async def _run(self) ->None:\n while True:\n message = await self.serial_reader.readuntil(separator=b'\\r\\n')\n stripped_message = message.decode(encoding='ascii').rstrip('\\n\\r')\n self.logger.debug(\"Read '%s' from MDB board.\", stripped_message)\n message_type = stripped_message[0]\n if message_type in self.waiters:\n self.waiters[message_type].set_result(stripped_message)\n del self.waiters[message_type]\n await asyncio.sleep(0)\n elif message_type in self.queues:\n try:\n self.queues[message_type].put_nowait(stripped_message)\n except asyncio.QueueFull:\n self.logger.warning(\n 'Queue for message type %s is full. Scheduling the put in another task.'\n , message_type)\n asyncio.create_task(self.queues[message_type].put(\n stripped_message))\n else:\n self.logger.error('Unhandled message: %s', stripped_message)\n\n async def run(self) ->None:\n assert self.initialized\n self.logger.info('Starting runner.')\n self.run_task = asyncio.create_task(self._run())\n try:\n await self.run_task\n except asyncio.CancelledError:\n self.logger.info('Runner cancelled.')\n\n async def send(self, message: AsciiBytes, _drain=True) ->None:\n assert self.initialized\n self.logger.info('Sending message to MDB board: %s', message)\n self.serial_writer.write(message)\n if _drain:\n await self.serial_writer.drain()\n self.logger.info('Sent message to MDB board: %s', message)\n\n def _read_internal(self, prefix: str) ->asyncio.Future:\n assert len(prefix) == 1\n if prefix in self.queues or prefix in self.waiters:\n raise RuntimeError(\n f'Tried to wait for message type {prefix} when there was already a queue listening to all messages'\n )\n fut = asyncio.get_running_loop().create_future()\n self.waiters[prefix] = fut\n return fut\n\n async def sendread(self, message: AsciiBytes, prefix: str) ->str:\n await self.send(message, _drain=False)\n fut = self._read_internal(prefix)\n self.logger.info('Waiting for a single message of type: %s', prefix)\n try:\n await self.serial_writer.drain()\n self.logger.info('Sent message to MDB board: %s', message)\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning(\n 'Got cancelled while sending message %r or waiting on prefix %s'\n , message, prefix, exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info('Got message: %s', fut.result())\n return fut.result()\n\n async def read(self, prefix: str) ->str:\n fut = self._read_internal(prefix)\n self.logger.info('Waiting for a single message of type: %s', prefix)\n try:\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning('Got cancelled while waiting for message on %s'\n , prefix, exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info('Got message: %s', fut.result())\n return fut.result()\n\n def listen(self, prefix: str) ->asyncio.Queue:\n assert len(prefix) == 1\n if prefix in self.waiters or prefix in self.queues:\n raise RuntimeError(\n f'Tried to get a queue for message type {prefix} when there was already someonewaiting on it.'\n )\n self.queues[prefix] = asyncio.Queue()\n self.logger.info('Polling for messages of type: %s', prefix)\n return self.queues[prefix]\n\n def unlisten(self, prefix: str) ->None:\n \"\"\"Stops pushing messages with this prefix character to a Queue.\"\"\"\n assert len(prefix) == 1\n del self.queues[prefix]\n self.logger.info('No longer polling for message type: %s', prefix)\n\n async def shutdown(self):\n if not self.initialized:\n return\n self.logger.info('Shutting down.')\n if self.run_task:\n self.run_task.cancel()\n self.run_task = None\n for fut in self.waiters.values():\n fut.cancel()\n self.serial_writer.close()\n await self.serial_writer.wait_closed()\n self.logger.info('Shutdown complete.')\n self.initialized = False\n\n\n__all__ = USBHandler, to_ascii\n", "step-4": "import asyncio\nimport logging\nimport os.path\nfrom serial_asyncio import open_serial_connection\nfrom typing import NewType, cast\nAsciiBytes = NewType('AsciiBytes', bytes)\n\n\ndef to_ascii(s: str) ->AsciiBytes:\n if s[-1] != '\\n':\n s += '\\n'\n return cast(AsciiBytes, s.encode(encoding='ascii'))\n\n\nclass USBHandler:\n \"\"\"Reads from and writes to the underlying MDB USB board.\n\n Users can either obtain an asyncio.Queue that the handler will push\n messages to using listen(), or it can ask for a one-time read using read().\n For sending messages, if no reply is expected or there is a poller waiting\n for any response, send() can be used, otherwise sendread() will send the\n message and wait for a one-time reply. Having a listener and waiting for a\n single message at the same time is an error. See the Sniffer class for an\n example of both usages.\"\"\"\n\n def __init__(self):\n self.initialized = False\n self.run_task = None\n self.waiters = {}\n self.queues = {}\n self.logger = logging.getLogger('.'.join((__name__, self.__class__.\n __name__)))\n\n async def initialize(self, device_path: str) ->None:\n assert os.path.exists(device_path)\n self.logger.info('Initializing USBReader.')\n self.logger.debug('Opening serial connection to device at %s',\n device_path)\n self.serial_reader, self.serial_writer = await open_serial_connection(\n url=device_path, baudrate=115200)\n self.initialized = True\n self.logger.debug('Connected to serial device at %s.', device_path)\n\n async def _run(self) ->None:\n while True:\n message = await self.serial_reader.readuntil(separator=b'\\r\\n')\n stripped_message = message.decode(encoding='ascii').rstrip('\\n\\r')\n self.logger.debug(\"Read '%s' from MDB board.\", stripped_message)\n message_type = stripped_message[0]\n if message_type in self.waiters:\n self.waiters[message_type].set_result(stripped_message)\n del self.waiters[message_type]\n await asyncio.sleep(0)\n elif message_type in self.queues:\n try:\n self.queues[message_type].put_nowait(stripped_message)\n except asyncio.QueueFull:\n self.logger.warning(\n 'Queue for message type %s is full. Scheduling the put in another task.'\n , message_type)\n asyncio.create_task(self.queues[message_type].put(\n stripped_message))\n else:\n self.logger.error('Unhandled message: %s', stripped_message)\n\n async def run(self) ->None:\n assert self.initialized\n self.logger.info('Starting runner.')\n self.run_task = asyncio.create_task(self._run())\n try:\n await self.run_task\n except asyncio.CancelledError:\n self.logger.info('Runner cancelled.')\n\n async def send(self, message: AsciiBytes, _drain=True) ->None:\n assert self.initialized\n self.logger.info('Sending message to MDB board: %s', message)\n self.serial_writer.write(message)\n if _drain:\n await self.serial_writer.drain()\n self.logger.info('Sent message to MDB board: %s', message)\n\n def _read_internal(self, prefix: str) ->asyncio.Future:\n assert len(prefix) == 1\n if prefix in self.queues or prefix in self.waiters:\n raise RuntimeError(\n f'Tried to wait for message type {prefix} when there was already a queue listening to all messages'\n )\n fut = asyncio.get_running_loop().create_future()\n self.waiters[prefix] = fut\n return fut\n\n async def sendread(self, message: AsciiBytes, prefix: str) ->str:\n await self.send(message, _drain=False)\n fut = self._read_internal(prefix)\n self.logger.info('Waiting for a single message of type: %s', prefix)\n try:\n await self.serial_writer.drain()\n self.logger.info('Sent message to MDB board: %s', message)\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning(\n 'Got cancelled while sending message %r or waiting on prefix %s'\n , message, prefix, exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info('Got message: %s', fut.result())\n return fut.result()\n\n async def read(self, prefix: str) ->str:\n fut = self._read_internal(prefix)\n self.logger.info('Waiting for a single message of type: %s', prefix)\n try:\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning('Got cancelled while waiting for message on %s'\n , prefix, exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info('Got message: %s', fut.result())\n return fut.result()\n\n def listen(self, prefix: str) ->asyncio.Queue:\n assert len(prefix) == 1\n if prefix in self.waiters or prefix in self.queues:\n raise RuntimeError(\n f'Tried to get a queue for message type {prefix} when there was already someonewaiting on it.'\n )\n self.queues[prefix] = asyncio.Queue()\n self.logger.info('Polling for messages of type: %s', prefix)\n return self.queues[prefix]\n\n def unlisten(self, prefix: str) ->None:\n \"\"\"Stops pushing messages with this prefix character to a Queue.\"\"\"\n assert len(prefix) == 1\n del self.queues[prefix]\n self.logger.info('No longer polling for message type: %s', prefix)\n\n async def shutdown(self):\n if not self.initialized:\n return\n self.logger.info('Shutting down.')\n if self.run_task:\n self.run_task.cancel()\n self.run_task = None\n for fut in self.waiters.values():\n fut.cancel()\n self.serial_writer.close()\n await self.serial_writer.wait_closed()\n self.logger.info('Shutdown complete.')\n self.initialized = False\n\n\n__all__ = USBHandler, to_ascii\n", "step-5": "import asyncio\nimport logging\nimport os.path\nfrom serial_asyncio import open_serial_connection\nfrom typing import NewType, cast\n\n# Type annotations and converters\nAsciiBytes = NewType('AsciiBytes', bytes)\n\n\ndef to_ascii(s: str) -> AsciiBytes:\n if s[-1] != '\\n':\n s += '\\n'\n return cast(AsciiBytes, s.encode(encoding='ascii'))\n\n\nclass USBHandler:\n \"\"\"Reads from and writes to the underlying MDB USB board.\n\n Users can either obtain an asyncio.Queue that the handler will push\n messages to using listen(), or it can ask for a one-time read using read().\n For sending messages, if no reply is expected or there is a poller waiting\n for any response, send() can be used, otherwise sendread() will send the\n message and wait for a one-time reply. Having a listener and waiting for a\n single message at the same time is an error. See the Sniffer class for an\n example of both usages.\"\"\"\n\n def __init__(self):\n self.initialized = False\n self.run_task = None\n self.waiters = {}\n self.queues = {}\n self.logger = logging.getLogger('.'.join((__name__,\n self.__class__.__name__)))\n\n async def initialize(self, device_path: str) -> None:\n assert os.path.exists(device_path)\n self.logger.info(\"Initializing USBReader.\")\n self.logger.debug(\"Opening serial connection to device at %s\",\n device_path)\n self.serial_reader, self.serial_writer = \\\n await open_serial_connection(url=device_path, baudrate=115200)\n self.initialized = True\n self.logger.debug(\"Connected to serial device at %s.\", device_path)\n\n async def _run(self) -> None:\n while True:\n message = await self.serial_reader.readuntil(separator=b'\\r\\n')\n stripped_message = message.decode(encoding='ascii').rstrip('\\n\\r')\n self.logger.debug(\"Read '%s' from MDB board.\", stripped_message)\n message_type = stripped_message[0]\n if message_type in self.waiters:\n self.waiters[message_type].set_result(stripped_message)\n del self.waiters[message_type]\n # Lets the waiter run.\n await asyncio.sleep(0)\n elif message_type in self.queues:\n try:\n self.queues[message_type].put_nowait(stripped_message)\n except asyncio.QueueFull:\n self.logger.warning('Queue for message type %s is full. '\n 'Scheduling the put in another task.',\n message_type)\n asyncio.create_task(\n self.queues[message_type].put(stripped_message))\n else:\n self.logger.error(\"Unhandled message: %s\", stripped_message)\n\n async def run(self) -> None:\n assert self.initialized\n self.logger.info('Starting runner.')\n self.run_task = asyncio.create_task(self._run())\n try:\n await self.run_task\n except asyncio.CancelledError:\n self.logger.info('Runner cancelled.')\n\n async def send(self, message: AsciiBytes, _drain=True) -> None:\n assert self.initialized\n self.logger.info(\"Sending message to MDB board: %s\", message)\n self.serial_writer.write(message)\n if _drain:\n await self.serial_writer.drain()\n self.logger.info(\"Sent message to MDB board: %s\", message)\n\n def _read_internal(self, prefix: str) -> asyncio.Future:\n assert len(prefix) == 1\n if prefix in self.queues or prefix in self.waiters:\n raise RuntimeError(f\"Tried to wait for message type {prefix}\"\n \" when there was already a queue listening to \"\n \"all messages\")\n fut = asyncio.get_running_loop().create_future()\n self.waiters[prefix] = fut\n return fut\n\n async def sendread(self, message: AsciiBytes, prefix: str) -> str:\n await self.send(message, _drain=False)\n fut = self._read_internal(prefix)\n self.logger.info(\"Waiting for a single message of type: %s\", prefix)\n try:\n await self.serial_writer.drain()\n self.logger.info(\"Sent message to MDB board: %s\", message)\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning(\"Got cancelled while sending message %r or \"\n \"waiting on prefix %s\", message, prefix,\n exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info(\"Got message: %s\", fut.result())\n return fut.result()\n\n async def read(self, prefix: str) -> str:\n fut = self._read_internal(prefix)\n self.logger.info(\"Waiting for a single message of type: %s\", prefix)\n try:\n await fut\n except asyncio.CancelledError as e:\n self.logger.warning(\"Got cancelled while waiting for message on \"\n \"%s\", prefix, exc_info=e)\n del self.waiters[prefix]\n raise\n self.logger.info(\"Got message: %s\", fut.result())\n return fut.result()\n\n def listen(self, prefix: str) -> asyncio.Queue:\n assert len(prefix) == 1\n if prefix in self.waiters or prefix in self.queues:\n raise RuntimeError(\"Tried to get a queue for message type \"\n f\"{prefix} when there was already someone\"\n \"waiting on it.\")\n self.queues[prefix] = asyncio.Queue()\n self.logger.info(\"Polling for messages of type: %s\", prefix)\n return self.queues[prefix]\n\n def unlisten(self, prefix: str) -> None:\n \"\"\"Stops pushing messages with this prefix character to a Queue.\"\"\"\n assert len(prefix) == 1\n del self.queues[prefix]\n self.logger.info(\"No longer polling for message type: %s\", prefix)\n\n async def shutdown(self):\n if not self.initialized:\n return\n self.logger.info(\"Shutting down.\")\n if self.run_task:\n self.run_task.cancel()\n self.run_task = None\n for fut in self.waiters.values():\n fut.cancel()\n self.serial_writer.close()\n await self.serial_writer.wait_closed()\n self.logger.info(\"Shutdown complete.\")\n self.initialized = False\n\n\n__all__ = (USBHandler, to_ascii)\n", "step-ids": [ 3, 7, 8, 9, 10 ] }
[ 3, 7, 8, 9, 10 ]
"""Derivation of variable ``co2s``.""" import dask.array as da import iris import numpy as np import stratify from ._baseclass import DerivedVariableBase def _get_first_unmasked_data(array, axis): """Get first unmasked value of an array along an axis.""" mask = da.ma.getmaskarray(array) numerical_mask = da.where(mask, -1.0, 1.0) indices_first_positive = da.argmax(numerical_mask, axis=axis) indices = da.meshgrid( *[da.arange(array.shape[i]) for i in range(array.ndim) if i != axis], indexing='ij') indices.insert(axis, indices_first_positive) first_unmasked_data = np.array(array)[tuple(indices)] return first_unmasked_data class DerivedVariable(DerivedVariableBase): """Derivation of variable ``co2s``. Use linear interpolation/extrapolation and surface air pressure to calculate CO2 mole fraction at surface. Note ---- In some cases, ``co2`` data is masked. In these cases, the masked values correspond to values where the pressure level is higher than the surface air pressure (e.g. the 1000 hPa level for grid cells with high elevation). To obtain an unmasked ``co2s`` field, it is necessary to fill these masked values accordingly, i.e. with the lowest unmasked value for each grid cell. """ @staticmethod def required(project): """Declare the variables needed for derivation.""" required = [{'short_name': 'co2'}, {'short_name': 'ps'}] return required @staticmethod def calculate(cubes): """Compute mole fraction of CO2 at surface.""" co2_cube = cubes.extract_cube( iris.Constraint(name='mole_fraction_of_carbon_dioxide_in_air')) ps_cube = cubes.extract_cube( iris.Constraint(name='surface_air_pressure')) # Fill masked data if necessary (interpolation fails with masked data) (z_axis,) = co2_cube.coord_dims(co2_cube.coord(axis='Z', dim_coords=True)) mask = da.ma.getmaskarray(co2_cube.core_data()) if mask.any(): first_unmasked_data = _get_first_unmasked_data( co2_cube.core_data(), axis=z_axis) dim_map = [dim for dim in range(co2_cube.ndim) if dim != z_axis] first_unmasked_data = iris.util.broadcast_to_shape( first_unmasked_data, co2_cube.shape, dim_map) co2_cube.data = da.where(mask, first_unmasked_data, co2_cube.core_data()) # Interpolation (not supported for dask arrays) air_pressure_coord = co2_cube.coord('air_pressure') original_levels = iris.util.broadcast_to_shape( air_pressure_coord.points, co2_cube.shape, co2_cube.coord_dims(air_pressure_coord)) target_levels = np.expand_dims(ps_cube.data, axis=z_axis) co2s_data = stratify.interpolate( target_levels, original_levels, co2_cube.data, axis=z_axis, interpolation='linear', extrapolation='linear', ) co2s_data = np.squeeze(co2s_data, axis=z_axis) # Construct co2s cube indices = [slice(None)] * co2_cube.ndim indices[z_axis] = 0 co2s_cube = co2_cube[tuple(indices)] co2s_cube.data = co2s_data if co2s_cube.coords('air_pressure'): co2s_cube.remove_coord('air_pressure') ps_coord = iris.coords.AuxCoord(ps_cube.data, var_name='plev', standard_name='air_pressure', long_name='pressure', units=ps_cube.units) co2s_cube.add_aux_coord(ps_coord, np.arange(co2s_cube.ndim)) co2s_cube.convert_units('1e-6') return co2s_cube
normal
{ "blob_id": "7c9b68b2d32d8e435f332d4412ea1ba899607ec4", "index": 9395, "step-1": "<mask token>\n\n\nclass DerivedVariable(DerivedVariableBase):\n <mask token>\n\n @staticmethod\n def required(project):\n \"\"\"Declare the variables needed for derivation.\"\"\"\n required = [{'short_name': 'co2'}, {'short_name': 'ps'}]\n return required\n\n @staticmethod\n def calculate(cubes):\n \"\"\"Compute mole fraction of CO2 at surface.\"\"\"\n co2_cube = cubes.extract_cube(iris.Constraint(name=\n 'mole_fraction_of_carbon_dioxide_in_air'))\n ps_cube = cubes.extract_cube(iris.Constraint(name=\n 'surface_air_pressure'))\n z_axis, = co2_cube.coord_dims(co2_cube.coord(axis='Z', dim_coords=True)\n )\n mask = da.ma.getmaskarray(co2_cube.core_data())\n if mask.any():\n first_unmasked_data = _get_first_unmasked_data(co2_cube.\n core_data(), axis=z_axis)\n dim_map = [dim for dim in range(co2_cube.ndim) if dim != z_axis]\n first_unmasked_data = iris.util.broadcast_to_shape(\n first_unmasked_data, co2_cube.shape, dim_map)\n co2_cube.data = da.where(mask, first_unmasked_data, co2_cube.\n core_data())\n air_pressure_coord = co2_cube.coord('air_pressure')\n original_levels = iris.util.broadcast_to_shape(air_pressure_coord.\n points, co2_cube.shape, co2_cube.coord_dims(air_pressure_coord))\n target_levels = np.expand_dims(ps_cube.data, axis=z_axis)\n co2s_data = stratify.interpolate(target_levels, original_levels,\n co2_cube.data, axis=z_axis, interpolation='linear',\n extrapolation='linear')\n co2s_data = np.squeeze(co2s_data, axis=z_axis)\n indices = [slice(None)] * co2_cube.ndim\n indices[z_axis] = 0\n co2s_cube = co2_cube[tuple(indices)]\n co2s_cube.data = co2s_data\n if co2s_cube.coords('air_pressure'):\n co2s_cube.remove_coord('air_pressure')\n ps_coord = iris.coords.AuxCoord(ps_cube.data, var_name='plev',\n standard_name='air_pressure', long_name='pressure', units=\n ps_cube.units)\n co2s_cube.add_aux_coord(ps_coord, np.arange(co2s_cube.ndim))\n co2s_cube.convert_units('1e-6')\n return co2s_cube\n", "step-2": "<mask token>\n\n\nclass DerivedVariable(DerivedVariableBase):\n \"\"\"Derivation of variable ``co2s``.\n\n Use linear interpolation/extrapolation and surface air pressure to\n calculate CO2 mole fraction at surface.\n\n Note\n ----\n In some cases, ``co2`` data is masked. In these cases, the masked values\n correspond to values where the pressure level is higher than the surface\n air pressure (e.g. the 1000 hPa level for grid cells with high elevation).\n To obtain an unmasked ``co2s`` field, it is necessary to fill these masked\n values accordingly, i.e. with the lowest unmasked value for each grid cell.\n\n \"\"\"\n\n @staticmethod\n def required(project):\n \"\"\"Declare the variables needed for derivation.\"\"\"\n required = [{'short_name': 'co2'}, {'short_name': 'ps'}]\n return required\n\n @staticmethod\n def calculate(cubes):\n \"\"\"Compute mole fraction of CO2 at surface.\"\"\"\n co2_cube = cubes.extract_cube(iris.Constraint(name=\n 'mole_fraction_of_carbon_dioxide_in_air'))\n ps_cube = cubes.extract_cube(iris.Constraint(name=\n 'surface_air_pressure'))\n z_axis, = co2_cube.coord_dims(co2_cube.coord(axis='Z', dim_coords=True)\n )\n mask = da.ma.getmaskarray(co2_cube.core_data())\n if mask.any():\n first_unmasked_data = _get_first_unmasked_data(co2_cube.\n core_data(), axis=z_axis)\n dim_map = [dim for dim in range(co2_cube.ndim) if dim != z_axis]\n first_unmasked_data = iris.util.broadcast_to_shape(\n first_unmasked_data, co2_cube.shape, dim_map)\n co2_cube.data = da.where(mask, first_unmasked_data, co2_cube.\n core_data())\n air_pressure_coord = co2_cube.coord('air_pressure')\n original_levels = iris.util.broadcast_to_shape(air_pressure_coord.\n points, co2_cube.shape, co2_cube.coord_dims(air_pressure_coord))\n target_levels = np.expand_dims(ps_cube.data, axis=z_axis)\n co2s_data = stratify.interpolate(target_levels, original_levels,\n co2_cube.data, axis=z_axis, interpolation='linear',\n extrapolation='linear')\n co2s_data = np.squeeze(co2s_data, axis=z_axis)\n indices = [slice(None)] * co2_cube.ndim\n indices[z_axis] = 0\n co2s_cube = co2_cube[tuple(indices)]\n co2s_cube.data = co2s_data\n if co2s_cube.coords('air_pressure'):\n co2s_cube.remove_coord('air_pressure')\n ps_coord = iris.coords.AuxCoord(ps_cube.data, var_name='plev',\n standard_name='air_pressure', long_name='pressure', units=\n ps_cube.units)\n co2s_cube.add_aux_coord(ps_coord, np.arange(co2s_cube.ndim))\n co2s_cube.convert_units('1e-6')\n return co2s_cube\n", "step-3": "<mask token>\n\n\ndef _get_first_unmasked_data(array, axis):\n \"\"\"Get first unmasked value of an array along an axis.\"\"\"\n mask = da.ma.getmaskarray(array)\n numerical_mask = da.where(mask, -1.0, 1.0)\n indices_first_positive = da.argmax(numerical_mask, axis=axis)\n indices = da.meshgrid(*[da.arange(array.shape[i]) for i in range(array.\n ndim) if i != axis], indexing='ij')\n indices.insert(axis, indices_first_positive)\n first_unmasked_data = np.array(array)[tuple(indices)]\n return first_unmasked_data\n\n\nclass DerivedVariable(DerivedVariableBase):\n \"\"\"Derivation of variable ``co2s``.\n\n Use linear interpolation/extrapolation and surface air pressure to\n calculate CO2 mole fraction at surface.\n\n Note\n ----\n In some cases, ``co2`` data is masked. In these cases, the masked values\n correspond to values where the pressure level is higher than the surface\n air pressure (e.g. the 1000 hPa level for grid cells with high elevation).\n To obtain an unmasked ``co2s`` field, it is necessary to fill these masked\n values accordingly, i.e. with the lowest unmasked value for each grid cell.\n\n \"\"\"\n\n @staticmethod\n def required(project):\n \"\"\"Declare the variables needed for derivation.\"\"\"\n required = [{'short_name': 'co2'}, {'short_name': 'ps'}]\n return required\n\n @staticmethod\n def calculate(cubes):\n \"\"\"Compute mole fraction of CO2 at surface.\"\"\"\n co2_cube = cubes.extract_cube(iris.Constraint(name=\n 'mole_fraction_of_carbon_dioxide_in_air'))\n ps_cube = cubes.extract_cube(iris.Constraint(name=\n 'surface_air_pressure'))\n z_axis, = co2_cube.coord_dims(co2_cube.coord(axis='Z', dim_coords=True)\n )\n mask = da.ma.getmaskarray(co2_cube.core_data())\n if mask.any():\n first_unmasked_data = _get_first_unmasked_data(co2_cube.\n core_data(), axis=z_axis)\n dim_map = [dim for dim in range(co2_cube.ndim) if dim != z_axis]\n first_unmasked_data = iris.util.broadcast_to_shape(\n first_unmasked_data, co2_cube.shape, dim_map)\n co2_cube.data = da.where(mask, first_unmasked_data, co2_cube.\n core_data())\n air_pressure_coord = co2_cube.coord('air_pressure')\n original_levels = iris.util.broadcast_to_shape(air_pressure_coord.\n points, co2_cube.shape, co2_cube.coord_dims(air_pressure_coord))\n target_levels = np.expand_dims(ps_cube.data, axis=z_axis)\n co2s_data = stratify.interpolate(target_levels, original_levels,\n co2_cube.data, axis=z_axis, interpolation='linear',\n extrapolation='linear')\n co2s_data = np.squeeze(co2s_data, axis=z_axis)\n indices = [slice(None)] * co2_cube.ndim\n indices[z_axis] = 0\n co2s_cube = co2_cube[tuple(indices)]\n co2s_cube.data = co2s_data\n if co2s_cube.coords('air_pressure'):\n co2s_cube.remove_coord('air_pressure')\n ps_coord = iris.coords.AuxCoord(ps_cube.data, var_name='plev',\n standard_name='air_pressure', long_name='pressure', units=\n ps_cube.units)\n co2s_cube.add_aux_coord(ps_coord, np.arange(co2s_cube.ndim))\n co2s_cube.convert_units('1e-6')\n return co2s_cube\n", "step-4": "<mask token>\nimport dask.array as da\nimport iris\nimport numpy as np\nimport stratify\nfrom ._baseclass import DerivedVariableBase\n\n\ndef _get_first_unmasked_data(array, axis):\n \"\"\"Get first unmasked value of an array along an axis.\"\"\"\n mask = da.ma.getmaskarray(array)\n numerical_mask = da.where(mask, -1.0, 1.0)\n indices_first_positive = da.argmax(numerical_mask, axis=axis)\n indices = da.meshgrid(*[da.arange(array.shape[i]) for i in range(array.\n ndim) if i != axis], indexing='ij')\n indices.insert(axis, indices_first_positive)\n first_unmasked_data = np.array(array)[tuple(indices)]\n return first_unmasked_data\n\n\nclass DerivedVariable(DerivedVariableBase):\n \"\"\"Derivation of variable ``co2s``.\n\n Use linear interpolation/extrapolation and surface air pressure to\n calculate CO2 mole fraction at surface.\n\n Note\n ----\n In some cases, ``co2`` data is masked. In these cases, the masked values\n correspond to values where the pressure level is higher than the surface\n air pressure (e.g. the 1000 hPa level for grid cells with high elevation).\n To obtain an unmasked ``co2s`` field, it is necessary to fill these masked\n values accordingly, i.e. with the lowest unmasked value for each grid cell.\n\n \"\"\"\n\n @staticmethod\n def required(project):\n \"\"\"Declare the variables needed for derivation.\"\"\"\n required = [{'short_name': 'co2'}, {'short_name': 'ps'}]\n return required\n\n @staticmethod\n def calculate(cubes):\n \"\"\"Compute mole fraction of CO2 at surface.\"\"\"\n co2_cube = cubes.extract_cube(iris.Constraint(name=\n 'mole_fraction_of_carbon_dioxide_in_air'))\n ps_cube = cubes.extract_cube(iris.Constraint(name=\n 'surface_air_pressure'))\n z_axis, = co2_cube.coord_dims(co2_cube.coord(axis='Z', dim_coords=True)\n )\n mask = da.ma.getmaskarray(co2_cube.core_data())\n if mask.any():\n first_unmasked_data = _get_first_unmasked_data(co2_cube.\n core_data(), axis=z_axis)\n dim_map = [dim for dim in range(co2_cube.ndim) if dim != z_axis]\n first_unmasked_data = iris.util.broadcast_to_shape(\n first_unmasked_data, co2_cube.shape, dim_map)\n co2_cube.data = da.where(mask, first_unmasked_data, co2_cube.\n core_data())\n air_pressure_coord = co2_cube.coord('air_pressure')\n original_levels = iris.util.broadcast_to_shape(air_pressure_coord.\n points, co2_cube.shape, co2_cube.coord_dims(air_pressure_coord))\n target_levels = np.expand_dims(ps_cube.data, axis=z_axis)\n co2s_data = stratify.interpolate(target_levels, original_levels,\n co2_cube.data, axis=z_axis, interpolation='linear',\n extrapolation='linear')\n co2s_data = np.squeeze(co2s_data, axis=z_axis)\n indices = [slice(None)] * co2_cube.ndim\n indices[z_axis] = 0\n co2s_cube = co2_cube[tuple(indices)]\n co2s_cube.data = co2s_data\n if co2s_cube.coords('air_pressure'):\n co2s_cube.remove_coord('air_pressure')\n ps_coord = iris.coords.AuxCoord(ps_cube.data, var_name='plev',\n standard_name='air_pressure', long_name='pressure', units=\n ps_cube.units)\n co2s_cube.add_aux_coord(ps_coord, np.arange(co2s_cube.ndim))\n co2s_cube.convert_units('1e-6')\n return co2s_cube\n", "step-5": "\"\"\"Derivation of variable ``co2s``.\"\"\"\nimport dask.array as da\nimport iris\nimport numpy as np\nimport stratify\n\nfrom ._baseclass import DerivedVariableBase\n\n\ndef _get_first_unmasked_data(array, axis):\n \"\"\"Get first unmasked value of an array along an axis.\"\"\"\n mask = da.ma.getmaskarray(array)\n numerical_mask = da.where(mask, -1.0, 1.0)\n indices_first_positive = da.argmax(numerical_mask, axis=axis)\n indices = da.meshgrid(\n *[da.arange(array.shape[i]) for i in range(array.ndim) if i != axis],\n indexing='ij')\n indices.insert(axis, indices_first_positive)\n first_unmasked_data = np.array(array)[tuple(indices)]\n return first_unmasked_data\n\n\nclass DerivedVariable(DerivedVariableBase):\n \"\"\"Derivation of variable ``co2s``.\n\n Use linear interpolation/extrapolation and surface air pressure to\n calculate CO2 mole fraction at surface.\n\n Note\n ----\n In some cases, ``co2`` data is masked. In these cases, the masked values\n correspond to values where the pressure level is higher than the surface\n air pressure (e.g. the 1000 hPa level for grid cells with high elevation).\n To obtain an unmasked ``co2s`` field, it is necessary to fill these masked\n values accordingly, i.e. with the lowest unmasked value for each grid cell.\n\n \"\"\"\n\n @staticmethod\n def required(project):\n \"\"\"Declare the variables needed for derivation.\"\"\"\n required = [{'short_name': 'co2'}, {'short_name': 'ps'}]\n return required\n\n @staticmethod\n def calculate(cubes):\n \"\"\"Compute mole fraction of CO2 at surface.\"\"\"\n co2_cube = cubes.extract_cube(\n iris.Constraint(name='mole_fraction_of_carbon_dioxide_in_air'))\n ps_cube = cubes.extract_cube(\n iris.Constraint(name='surface_air_pressure'))\n\n # Fill masked data if necessary (interpolation fails with masked data)\n (z_axis,) = co2_cube.coord_dims(co2_cube.coord(axis='Z',\n dim_coords=True))\n mask = da.ma.getmaskarray(co2_cube.core_data())\n if mask.any():\n first_unmasked_data = _get_first_unmasked_data(\n co2_cube.core_data(), axis=z_axis)\n dim_map = [dim for dim in range(co2_cube.ndim) if dim != z_axis]\n first_unmasked_data = iris.util.broadcast_to_shape(\n first_unmasked_data, co2_cube.shape, dim_map)\n co2_cube.data = da.where(mask, first_unmasked_data,\n co2_cube.core_data())\n\n # Interpolation (not supported for dask arrays)\n air_pressure_coord = co2_cube.coord('air_pressure')\n original_levels = iris.util.broadcast_to_shape(\n air_pressure_coord.points, co2_cube.shape,\n co2_cube.coord_dims(air_pressure_coord))\n target_levels = np.expand_dims(ps_cube.data, axis=z_axis)\n co2s_data = stratify.interpolate(\n target_levels,\n original_levels,\n co2_cube.data,\n axis=z_axis,\n interpolation='linear',\n extrapolation='linear',\n )\n co2s_data = np.squeeze(co2s_data, axis=z_axis)\n\n # Construct co2s cube\n indices = [slice(None)] * co2_cube.ndim\n indices[z_axis] = 0\n co2s_cube = co2_cube[tuple(indices)]\n co2s_cube.data = co2s_data\n if co2s_cube.coords('air_pressure'):\n co2s_cube.remove_coord('air_pressure')\n ps_coord = iris.coords.AuxCoord(ps_cube.data,\n var_name='plev',\n standard_name='air_pressure',\n long_name='pressure',\n units=ps_cube.units)\n co2s_cube.add_aux_coord(ps_coord, np.arange(co2s_cube.ndim))\n co2s_cube.convert_units('1e-6')\n return co2s_cube\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> class Solution: <|reserved_special_token_0|> class Solution: def isPowerOfTwo(self, n: int) ->bool: return n > 0 and n & n - 1 == 0 class Solution: def isPowerOfTwo(self, n: int) ->bool: return n > 0 and math.log10(n) / math.log10(2) % 1 == 0 class Solution: def divide(self, dividend: int, divisor: int) ->int: """ a / b = c keep subtracting b, a faster way is to -2*b, -4*b, -1024*b if a > 2 * b => c should be bigger than 2 (1<<1) if a > 4 * b => c should be bigger than 4 (1<<2) if a > 1024 * b => c should be bigger than 1024 (1<<10) a might == 1024*b + 4*b + 2*b c = (1024+4+2) 2 * b == b << 1 1024 * b == b << 10 """ sig = (dividend < 0) == (divisor < 0) a, b, res = abs(dividend), abs(divisor), 0 while a >= b: shift = 0 while a >= b << shift + 1: print(a, res) shift += 1 res += 1 << shift a -= b << shift return min(res if sig else -res, (1 << 31) - 1) class Solution: def myPow(self, x: float, n: int) ->float: if n == 0: return 1 if n < 0: n = -n x = 1 / x if n & 1 == 0: return self.myPow(x * x, n >> 1) else: return x * self.myPow(x * x, n >> 1) class Solution: def mySqrt(self, x: int) ->int: l = 1 r = x while l <= r: mid = (l + r) // 2 if mid * mid == x: return mid elif mid * mid > x: r = mid - 1 else: l = mid + 1 return r <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_gcd(a, b): if b == 0: return a print(a, b) return get_gcd(b, a % b) <|reserved_special_token_0|> def divisor1(num): count = 0 for i in range(1, num + 1): if num % i == 0: count += 1 return count class Solution: def countPrimes(self, n: int) ->int: if n < 3: return 0 primes = [True] * n primes[0] = primes[1] = False for i in range(int(n ** 0.5) + 1): if primes[i]: for j in range(i + i, n, i): primes[j] = False return sum(primes) def find_primer(n): if n <= 3: return n > 1 if n % 6 != 1 and n % 6 != 5: return False for i in range(5, int(n ** 0.5) + 1, 6): if n % i == 0 or n % (i + 2) == 0: return False return True <|reserved_special_token_0|> class Solution: def isPowerOfFour(self, n: int) ->bool: if n <= 0: return False return n & n - 1 == 0 and n & 2863311530 == 0 class Solution: def isPowerOfTwo(self, n: int) ->bool: return n > 0 and n & n - 1 == 0 class Solution: def isPowerOfTwo(self, n: int) ->bool: return n > 0 and math.log10(n) / math.log10(2) % 1 == 0 class Solution: def divide(self, dividend: int, divisor: int) ->int: """ a / b = c keep subtracting b, a faster way is to -2*b, -4*b, -1024*b if a > 2 * b => c should be bigger than 2 (1<<1) if a > 4 * b => c should be bigger than 4 (1<<2) if a > 1024 * b => c should be bigger than 1024 (1<<10) a might == 1024*b + 4*b + 2*b c = (1024+4+2) 2 * b == b << 1 1024 * b == b << 10 """ sig = (dividend < 0) == (divisor < 0) a, b, res = abs(dividend), abs(divisor), 0 while a >= b: shift = 0 while a >= b << shift + 1: print(a, res) shift += 1 res += 1 << shift a -= b << shift return min(res if sig else -res, (1 << 31) - 1) class Solution: def myPow(self, x: float, n: int) ->float: if n == 0: return 1 if n < 0: n = -n x = 1 / x if n & 1 == 0: return self.myPow(x * x, n >> 1) else: return x * self.myPow(x * x, n >> 1) class Solution: def mySqrt(self, x: int) ->int: l = 1 r = x while l <= r: mid = (l + r) // 2 if mid * mid == x: return mid elif mid * mid > x: r = mid - 1 else: l = mid + 1 return r <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_gcd(a, b): if b == 0: return a print(a, b) return get_gcd(b, a % b) <|reserved_special_token_0|> def divisor1(num): count = 0 for i in range(1, num + 1): if num % i == 0: count += 1 return count class Solution: def countPrimes(self, n: int) ->int: if n < 3: return 0 primes = [True] * n primes[0] = primes[1] = False for i in range(int(n ** 0.5) + 1): if primes[i]: for j in range(i + i, n, i): primes[j] = False return sum(primes) def find_primer(n): if n <= 3: return n > 1 if n % 6 != 1 and n % 6 != 5: return False for i in range(5, int(n ** 0.5) + 1, 6): if n % i == 0 or n % (i + 2) == 0: return False return True def divisor2(num): count = 0 sqrt = int(num ** 0.5) for x in range(1, sqrt + 1): if num % x == 0: count += 2 print(x, num // x) return count - (sqrt ** 2 == num) class Solution: def isPowerOfFour(self, n: int) ->bool: if n <= 0: return False return n & n - 1 == 0 and n & 2863311530 == 0 class Solution: def isPowerOfTwo(self, n: int) ->bool: return n > 0 and n & n - 1 == 0 class Solution: def isPowerOfTwo(self, n: int) ->bool: return n > 0 and math.log10(n) / math.log10(2) % 1 == 0 class Solution: def divide(self, dividend: int, divisor: int) ->int: """ a / b = c keep subtracting b, a faster way is to -2*b, -4*b, -1024*b if a > 2 * b => c should be bigger than 2 (1<<1) if a > 4 * b => c should be bigger than 4 (1<<2) if a > 1024 * b => c should be bigger than 1024 (1<<10) a might == 1024*b + 4*b + 2*b c = (1024+4+2) 2 * b == b << 1 1024 * b == b << 10 """ sig = (dividend < 0) == (divisor < 0) a, b, res = abs(dividend), abs(divisor), 0 while a >= b: shift = 0 while a >= b << shift + 1: print(a, res) shift += 1 res += 1 << shift a -= b << shift return min(res if sig else -res, (1 << 31) - 1) class Solution: def myPow(self, x: float, n: int) ->float: if n == 0: return 1 if n < 0: n = -n x = 1 / x if n & 1 == 0: return self.myPow(x * x, n >> 1) else: return x * self.myPow(x * x, n >> 1) class Solution: def mySqrt(self, x: int) ->int: l = 1 r = x while l <= r: mid = (l + r) // 2 if mid * mid == x: return mid elif mid * mid > x: r = mid - 1 else: l = mid + 1 return r def root(x, n): if x == 0: return 0 low = 0 hi = max(1, x) root = (low + hi) / 2.0 while root - low >= 0.001: if root ** n > x: hi = root elif root ** n < x: low = root else: break root = (low + hi) / 2.0 return root <|reserved_special_token_1|> import math def get_gcd(a, b): if b == 0: return a print(a, b) return get_gcd(b, a % b) get_gcd(48, 30) def divisor1(num): count = 0 for i in range(1, num + 1): if num % i == 0: count += 1 return count class Solution: def countPrimes(self, n: int) ->int: if n < 3: return 0 primes = [True] * n primes[0] = primes[1] = False for i in range(int(n ** 0.5) + 1): if primes[i]: for j in range(i + i, n, i): primes[j] = False return sum(primes) def find_primer(n): if n <= 3: return n > 1 if n % 6 != 1 and n % 6 != 5: return False for i in range(5, int(n ** 0.5) + 1, 6): if n % i == 0 or n % (i + 2) == 0: return False return True def divisor2(num): count = 0 sqrt = int(num ** 0.5) for x in range(1, sqrt + 1): if num % x == 0: count += 2 print(x, num // x) return count - (sqrt ** 2 == num) class Solution: def isPowerOfFour(self, n: int) ->bool: if n <= 0: return False return n & n - 1 == 0 and n & 2863311530 == 0 class Solution: def isPowerOfTwo(self, n: int) ->bool: return n > 0 and n & n - 1 == 0 class Solution: def isPowerOfTwo(self, n: int) ->bool: return n > 0 and math.log10(n) / math.log10(2) % 1 == 0 class Solution: def divide(self, dividend: int, divisor: int) ->int: """ a / b = c keep subtracting b, a faster way is to -2*b, -4*b, -1024*b if a > 2 * b => c should be bigger than 2 (1<<1) if a > 4 * b => c should be bigger than 4 (1<<2) if a > 1024 * b => c should be bigger than 1024 (1<<10) a might == 1024*b + 4*b + 2*b c = (1024+4+2) 2 * b == b << 1 1024 * b == b << 10 """ sig = (dividend < 0) == (divisor < 0) a, b, res = abs(dividend), abs(divisor), 0 while a >= b: shift = 0 while a >= b << shift + 1: print(a, res) shift += 1 res += 1 << shift a -= b << shift return min(res if sig else -res, (1 << 31) - 1) class Solution: def myPow(self, x: float, n: int) ->float: if n == 0: return 1 if n < 0: n = -n x = 1 / x if n & 1 == 0: return self.myPow(x * x, n >> 1) else: return x * self.myPow(x * x, n >> 1) class Solution: def mySqrt(self, x: int) ->int: l = 1 r = x while l <= r: mid = (l + r) // 2 if mid * mid == x: return mid elif mid * mid > x: r = mid - 1 else: l = mid + 1 return r def root(x, n): if x == 0: return 0 low = 0 hi = max(1, x) root = (low + hi) / 2.0 while root - low >= 0.001: if root ** n > x: hi = root elif root ** n < x: low = root else: break root = (low + hi) / 2.0 return root <|reserved_special_token_1|> #!/usr/bin/env python3 # coding: utf-8 # Time complexity: O() # Space complexity: O() import math # 最大公约数 Greatest common divisor def get_gcd(a, b): if b == 0: return a print(a, b) return get_gcd(b, a % b) get_gcd(48, 30) # 计算约数个数 # 时间复杂度 O(n) def divisor1(num): count = 0 for i in range(1, num + 1): if num % i == 0: count += 1 return count # count prime, class Solution: def countPrimes(self, n: int) -> int: if n < 3: return 0 primes = [True] * n primes[0] = primes[1] = False for i in range(int(n ** 0.5) + 1): if primes[i]: for j in range(i + i, n, i): # delete all its multiples primes[j] = False return sum(primes) # Use upper limit of (n**0.5)+1, because: # (a) the smallest factor of a non-prime number will not be > sqrt(n). # Ex. non-prime = 100, # 5*20 # 10*10, # 20*5 # !! we have seen 5 before. # 判断prime,因为所有prime都是6n+1或者6n-1,同时我们只需要计算到sqrt(n)就可以 def find_primer(n): if n <= 3: return n > 1 if n%6 != 1 and n%6 != 5: return False for i in range(5, int(n**0.5)+1, 6): if n%i == 0 or n %(i+2) == 0: return False return True # 计算约数个数 # 时间复杂度 O( sqrt(n) ) def divisor2(num): count = 0 sqrt = int(num ** 0.5) for x in range(1, sqrt + 1): if num % x == 0: count += 2 print(x, num // x) return count - (sqrt ** 2 == num) # power of 4 class Solution: def isPowerOfFour(self, n: int) -> bool: if n <= 0: return False return n & (n - 1) == 0 and n & 0xAAAAAAAA == 0 # power of 2 class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and n & (n - 1) == 0 # power of 2 class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and (math.log10(n) / math.log10(2)) % 1 == 0 # devide class Solution: def divide(self, dividend: int, divisor: int) -> int: """ a / b = c keep subtracting b, a faster way is to -2*b, -4*b, -1024*b if a > 2 * b => c should be bigger than 2 (1<<1) if a > 4 * b => c should be bigger than 4 (1<<2) if a > 1024 * b => c should be bigger than 1024 (1<<10) a might == 1024*b + 4*b + 2*b c = (1024+4+2) 2 * b == b << 1 1024 * b == b << 10 """ sig = (dividend < 0) == (divisor < 0) a, b, res = abs(dividend), abs(divisor), 0 while a >= b: shift = 0 while a >= b << (shift + 1): print(a, res) shift += 1 res += 1 << shift a -= b << shift return min(res if sig else -res, (1 << 31) - 1) # power class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 1 if n < 0: n = -n x = 1 / x if n & 1 == 0: return self.myPow(x * x, n >> 1) else: return x * self.myPow(x * x, n >> 1) # sqrt class Solution: def mySqrt(self, x: int) -> int: l = 1 r = x while l <= r: # print(l,r) mid = (l + r) // 2 if mid * mid == x: return mid elif mid * mid > x: r = mid - 1 else: l = mid + 1 return r # root of number, x is the number and n is the root def root(x, n): if x == 0: return 0 low = 0 hi = max(1, x) root = (low+hi) / 2.0 while root - low >= 0.001: if root**n > x: hi = root elif root**n < x: low = root else: break root = (low+hi) / 2.0 return root
flexible
{ "blob_id": "32066db8b43bc70c564cce5a33f50921285b3627", "index": 6477, "step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n\n\nclass Solution:\n\n def isPowerOfTwo(self, n: int) ->bool:\n return n > 0 and n & n - 1 == 0\n\n\nclass Solution:\n\n def isPowerOfTwo(self, n: int) ->bool:\n return n > 0 and math.log10(n) / math.log10(2) % 1 == 0\n\n\nclass Solution:\n\n def divide(self, dividend: int, divisor: int) ->int:\n \"\"\"\n a / b = c\n \n keep subtracting b, a faster way is to -2*b, -4*b, -1024*b\n\n if a > 2 * b => c should be bigger than 2 (1<<1)\n if a > 4 * b => c should be bigger than 4 (1<<2)\n if a > 1024 * b => c should be bigger than 1024 (1<<10)\n\n a might == 1024*b + 4*b + 2*b\n c = (1024+4+2)\n\n 2 * b == b << 1\n 1024 * b == b << 10\n \n \"\"\"\n sig = (dividend < 0) == (divisor < 0)\n a, b, res = abs(dividend), abs(divisor), 0\n while a >= b:\n shift = 0\n while a >= b << shift + 1:\n print(a, res)\n shift += 1\n res += 1 << shift\n a -= b << shift\n return min(res if sig else -res, (1 << 31) - 1)\n\n\nclass Solution:\n\n def myPow(self, x: float, n: int) ->float:\n if n == 0:\n return 1\n if n < 0:\n n = -n\n x = 1 / x\n if n & 1 == 0:\n return self.myPow(x * x, n >> 1)\n else:\n return x * self.myPow(x * x, n >> 1)\n\n\nclass Solution:\n\n def mySqrt(self, x: int) ->int:\n l = 1\n r = x\n while l <= r:\n mid = (l + r) // 2\n if mid * mid == x:\n return mid\n elif mid * mid > x:\n r = mid - 1\n else:\n l = mid + 1\n return r\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_gcd(a, b):\n if b == 0:\n return a\n print(a, b)\n return get_gcd(b, a % b)\n\n\n<mask token>\n\n\ndef divisor1(num):\n count = 0\n for i in range(1, num + 1):\n if num % i == 0:\n count += 1\n return count\n\n\nclass Solution:\n\n def countPrimes(self, n: int) ->int:\n if n < 3:\n return 0\n primes = [True] * n\n primes[0] = primes[1] = False\n for i in range(int(n ** 0.5) + 1):\n if primes[i]:\n for j in range(i + i, n, i):\n primes[j] = False\n return sum(primes)\n\n\ndef find_primer(n):\n if n <= 3:\n return n > 1\n if n % 6 != 1 and n % 6 != 5:\n return False\n for i in range(5, int(n ** 0.5) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\n\n<mask token>\n\n\nclass Solution:\n\n def isPowerOfFour(self, n: int) ->bool:\n if n <= 0:\n return False\n return n & n - 1 == 0 and n & 2863311530 == 0\n\n\nclass Solution:\n\n def isPowerOfTwo(self, n: int) ->bool:\n return n > 0 and n & n - 1 == 0\n\n\nclass Solution:\n\n def isPowerOfTwo(self, n: int) ->bool:\n return n > 0 and math.log10(n) / math.log10(2) % 1 == 0\n\n\nclass Solution:\n\n def divide(self, dividend: int, divisor: int) ->int:\n \"\"\"\n a / b = c\n \n keep subtracting b, a faster way is to -2*b, -4*b, -1024*b\n\n if a > 2 * b => c should be bigger than 2 (1<<1)\n if a > 4 * b => c should be bigger than 4 (1<<2)\n if a > 1024 * b => c should be bigger than 1024 (1<<10)\n\n a might == 1024*b + 4*b + 2*b\n c = (1024+4+2)\n\n 2 * b == b << 1\n 1024 * b == b << 10\n \n \"\"\"\n sig = (dividend < 0) == (divisor < 0)\n a, b, res = abs(dividend), abs(divisor), 0\n while a >= b:\n shift = 0\n while a >= b << shift + 1:\n print(a, res)\n shift += 1\n res += 1 << shift\n a -= b << shift\n return min(res if sig else -res, (1 << 31) - 1)\n\n\nclass Solution:\n\n def myPow(self, x: float, n: int) ->float:\n if n == 0:\n return 1\n if n < 0:\n n = -n\n x = 1 / x\n if n & 1 == 0:\n return self.myPow(x * x, n >> 1)\n else:\n return x * self.myPow(x * x, n >> 1)\n\n\nclass Solution:\n\n def mySqrt(self, x: int) ->int:\n l = 1\n r = x\n while l <= r:\n mid = (l + r) // 2\n if mid * mid == x:\n return mid\n elif mid * mid > x:\n r = mid - 1\n else:\n l = mid + 1\n return r\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_gcd(a, b):\n if b == 0:\n return a\n print(a, b)\n return get_gcd(b, a % b)\n\n\n<mask token>\n\n\ndef divisor1(num):\n count = 0\n for i in range(1, num + 1):\n if num % i == 0:\n count += 1\n return count\n\n\nclass Solution:\n\n def countPrimes(self, n: int) ->int:\n if n < 3:\n return 0\n primes = [True] * n\n primes[0] = primes[1] = False\n for i in range(int(n ** 0.5) + 1):\n if primes[i]:\n for j in range(i + i, n, i):\n primes[j] = False\n return sum(primes)\n\n\ndef find_primer(n):\n if n <= 3:\n return n > 1\n if n % 6 != 1 and n % 6 != 5:\n return False\n for i in range(5, int(n ** 0.5) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\n\ndef divisor2(num):\n count = 0\n sqrt = int(num ** 0.5)\n for x in range(1, sqrt + 1):\n if num % x == 0:\n count += 2\n print(x, num // x)\n return count - (sqrt ** 2 == num)\n\n\nclass Solution:\n\n def isPowerOfFour(self, n: int) ->bool:\n if n <= 0:\n return False\n return n & n - 1 == 0 and n & 2863311530 == 0\n\n\nclass Solution:\n\n def isPowerOfTwo(self, n: int) ->bool:\n return n > 0 and n & n - 1 == 0\n\n\nclass Solution:\n\n def isPowerOfTwo(self, n: int) ->bool:\n return n > 0 and math.log10(n) / math.log10(2) % 1 == 0\n\n\nclass Solution:\n\n def divide(self, dividend: int, divisor: int) ->int:\n \"\"\"\n a / b = c\n \n keep subtracting b, a faster way is to -2*b, -4*b, -1024*b\n\n if a > 2 * b => c should be bigger than 2 (1<<1)\n if a > 4 * b => c should be bigger than 4 (1<<2)\n if a > 1024 * b => c should be bigger than 1024 (1<<10)\n\n a might == 1024*b + 4*b + 2*b\n c = (1024+4+2)\n\n 2 * b == b << 1\n 1024 * b == b << 10\n \n \"\"\"\n sig = (dividend < 0) == (divisor < 0)\n a, b, res = abs(dividend), abs(divisor), 0\n while a >= b:\n shift = 0\n while a >= b << shift + 1:\n print(a, res)\n shift += 1\n res += 1 << shift\n a -= b << shift\n return min(res if sig else -res, (1 << 31) - 1)\n\n\nclass Solution:\n\n def myPow(self, x: float, n: int) ->float:\n if n == 0:\n return 1\n if n < 0:\n n = -n\n x = 1 / x\n if n & 1 == 0:\n return self.myPow(x * x, n >> 1)\n else:\n return x * self.myPow(x * x, n >> 1)\n\n\nclass Solution:\n\n def mySqrt(self, x: int) ->int:\n l = 1\n r = x\n while l <= r:\n mid = (l + r) // 2\n if mid * mid == x:\n return mid\n elif mid * mid > x:\n r = mid - 1\n else:\n l = mid + 1\n return r\n\n\ndef root(x, n):\n if x == 0:\n return 0\n low = 0\n hi = max(1, x)\n root = (low + hi) / 2.0\n while root - low >= 0.001:\n if root ** n > x:\n hi = root\n elif root ** n < x:\n low = root\n else:\n break\n root = (low + hi) / 2.0\n return root\n", "step-4": "import math\n\n\ndef get_gcd(a, b):\n if b == 0:\n return a\n print(a, b)\n return get_gcd(b, a % b)\n\n\nget_gcd(48, 30)\n\n\ndef divisor1(num):\n count = 0\n for i in range(1, num + 1):\n if num % i == 0:\n count += 1\n return count\n\n\nclass Solution:\n\n def countPrimes(self, n: int) ->int:\n if n < 3:\n return 0\n primes = [True] * n\n primes[0] = primes[1] = False\n for i in range(int(n ** 0.5) + 1):\n if primes[i]:\n for j in range(i + i, n, i):\n primes[j] = False\n return sum(primes)\n\n\ndef find_primer(n):\n if n <= 3:\n return n > 1\n if n % 6 != 1 and n % 6 != 5:\n return False\n for i in range(5, int(n ** 0.5) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\n\ndef divisor2(num):\n count = 0\n sqrt = int(num ** 0.5)\n for x in range(1, sqrt + 1):\n if num % x == 0:\n count += 2\n print(x, num // x)\n return count - (sqrt ** 2 == num)\n\n\nclass Solution:\n\n def isPowerOfFour(self, n: int) ->bool:\n if n <= 0:\n return False\n return n & n - 1 == 0 and n & 2863311530 == 0\n\n\nclass Solution:\n\n def isPowerOfTwo(self, n: int) ->bool:\n return n > 0 and n & n - 1 == 0\n\n\nclass Solution:\n\n def isPowerOfTwo(self, n: int) ->bool:\n return n > 0 and math.log10(n) / math.log10(2) % 1 == 0\n\n\nclass Solution:\n\n def divide(self, dividend: int, divisor: int) ->int:\n \"\"\"\n a / b = c\n \n keep subtracting b, a faster way is to -2*b, -4*b, -1024*b\n\n if a > 2 * b => c should be bigger than 2 (1<<1)\n if a > 4 * b => c should be bigger than 4 (1<<2)\n if a > 1024 * b => c should be bigger than 1024 (1<<10)\n\n a might == 1024*b + 4*b + 2*b\n c = (1024+4+2)\n\n 2 * b == b << 1\n 1024 * b == b << 10\n \n \"\"\"\n sig = (dividend < 0) == (divisor < 0)\n a, b, res = abs(dividend), abs(divisor), 0\n while a >= b:\n shift = 0\n while a >= b << shift + 1:\n print(a, res)\n shift += 1\n res += 1 << shift\n a -= b << shift\n return min(res if sig else -res, (1 << 31) - 1)\n\n\nclass Solution:\n\n def myPow(self, x: float, n: int) ->float:\n if n == 0:\n return 1\n if n < 0:\n n = -n\n x = 1 / x\n if n & 1 == 0:\n return self.myPow(x * x, n >> 1)\n else:\n return x * self.myPow(x * x, n >> 1)\n\n\nclass Solution:\n\n def mySqrt(self, x: int) ->int:\n l = 1\n r = x\n while l <= r:\n mid = (l + r) // 2\n if mid * mid == x:\n return mid\n elif mid * mid > x:\n r = mid - 1\n else:\n l = mid + 1\n return r\n\n\ndef root(x, n):\n if x == 0:\n return 0\n low = 0\n hi = max(1, x)\n root = (low + hi) / 2.0\n while root - low >= 0.001:\n if root ** n > x:\n hi = root\n elif root ** n < x:\n low = root\n else:\n break\n root = (low + hi) / 2.0\n return root\n", "step-5": "#!/usr/bin/env python3\n# coding: utf-8\n\n# Time complexity: O()\n# Space complexity: O()\n\nimport math\n\n# 最大公约数 Greatest common divisor\ndef get_gcd(a, b):\n if b == 0:\n return a\n print(a, b)\n return get_gcd(b, a % b)\n\nget_gcd(48, 30)\n\n# 计算约数个数\n# 时间复杂度 O(n)\ndef divisor1(num):\n count = 0\n for i in range(1, num + 1):\n if num % i == 0:\n count += 1\n\n return count\n\n\n# count prime, \nclass Solution:\n def countPrimes(self, n: int) -> int:\n if n < 3:\n return 0\n primes = [True] * n\n primes[0] = primes[1] = False\n for i in range(int(n ** 0.5) + 1):\n if primes[i]:\n for j in range(i + i, n, i): # delete all its multiples\n primes[j] = False\n return sum(primes)\n\n\n# Use upper limit of (n**0.5)+1, because:\n# (a) the smallest factor of a non-prime number will not be > sqrt(n).\n# Ex. non-prime = 100,\n# 5*20\n# 10*10,\n# 20*5 # !! we have seen 5 before.\n\n\n\n# 判断prime,因为所有prime都是6n+1或者6n-1,同时我们只需要计算到sqrt(n)就可以\ndef find_primer(n):\n if n <= 3:\n return n > 1\n if n%6 != 1 and n%6 != 5:\n return False\n for i in range(5, int(n**0.5)+1, 6):\n if n%i == 0 or n %(i+2) == 0:\n return False\n return True\n\n\n# 计算约数个数\n# 时间复杂度 O( sqrt(n) )\ndef divisor2(num):\n count = 0\n sqrt = int(num ** 0.5)\n for x in range(1, sqrt + 1):\n if num % x == 0:\n count += 2\n print(x, num // x)\n return count - (sqrt ** 2 == num)\n\n\n# power of 4\nclass Solution:\n def isPowerOfFour(self, n: int) -> bool:\n if n <= 0:\n return False\n return n & (n - 1) == 0 and n & 0xAAAAAAAA == 0\n\n\n# power of 2\nclass Solution:\n def isPowerOfTwo(self, n: int) -> bool:\n return n > 0 and n & (n - 1) == 0\n\n\n# power of 2\nclass Solution:\n def isPowerOfTwo(self, n: int) -> bool:\n return n > 0 and (math.log10(n) / math.log10(2)) % 1 == 0\n\n\n# devide\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n \"\"\"\n a / b = c\n \n keep subtracting b, a faster way is to -2*b, -4*b, -1024*b\n\n if a > 2 * b => c should be bigger than 2 (1<<1)\n if a > 4 * b => c should be bigger than 4 (1<<2)\n if a > 1024 * b => c should be bigger than 1024 (1<<10)\n\n a might == 1024*b + 4*b + 2*b\n c = (1024+4+2)\n\n 2 * b == b << 1\n 1024 * b == b << 10\n \n \"\"\"\n sig = (dividend < 0) == (divisor < 0)\n a, b, res = abs(dividend), abs(divisor), 0\n while a >= b:\n shift = 0\n while a >= b << (shift + 1):\n print(a, res)\n shift += 1\n res += 1 << shift\n a -= b << shift\n return min(res if sig else -res, (1 << 31) - 1)\n\n\n# power\nclass Solution:\n def myPow(self, x: float, n: int) -> float:\n if n == 0:\n return 1\n if n < 0:\n n = -n\n x = 1 / x\n if n & 1 == 0:\n return self.myPow(x * x, n >> 1)\n else:\n return x * self.myPow(x * x, n >> 1)\n\n# sqrt\nclass Solution:\n def mySqrt(self, x: int) -> int:\n l = 1\n r = x\n while l <= r:\n # print(l,r)\n mid = (l + r) // 2\n if mid * mid == x:\n return mid\n elif mid * mid > x:\n r = mid - 1\n else:\n l = mid + 1\n\n return r\n\n\n# root of number, x is the number and n is the root\ndef root(x, n):\n if x == 0:\n return 0\n \n low = 0\n hi = max(1, x)\n root = (low+hi) / 2.0\n \n while root - low >= 0.001:\n if root**n > x:\n hi = root\n elif root**n < x:\n low = root\n else:\n break\n root = (low+hi) / 2.0\n \n return root", "step-ids": [ 11, 17, 19, 21, 22 ] }
[ 11, 17, 19, 21, 22 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> ap.add_argument('-D', '--dir', required=False, help='Directory to sort') <|reserved_special_token_0|> if args['dir'] == None: DIR = os.getcwd() elif os.path.exists(args['dir']): DIR = args['dir'] for file in os.listdir(DIR): if not os.path.isdir(os.path.join(DIR, file)): name, ext = os.path.splitext(file) ext = ext[::-1][:-1][::-1] if os.path.exists(os.path.join(DIR, ext.upper())): shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext. upper(), file)) else: os.mkdir(os.path.join(DIR, ext.upper())) shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext. upper(), file)) <|reserved_special_token_1|> <|reserved_special_token_0|> ap = argparse.ArgumentParser() ap.add_argument('-D', '--dir', required=False, help='Directory to sort') args = vars(ap.parse_args()) if args['dir'] == None: DIR = os.getcwd() elif os.path.exists(args['dir']): DIR = args['dir'] for file in os.listdir(DIR): if not os.path.isdir(os.path.join(DIR, file)): name, ext = os.path.splitext(file) ext = ext[::-1][:-1][::-1] if os.path.exists(os.path.join(DIR, ext.upper())): shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext. upper(), file)) else: os.mkdir(os.path.join(DIR, ext.upper())) shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext. upper(), file)) <|reserved_special_token_1|> import os import shutil import argparse ap = argparse.ArgumentParser() ap.add_argument('-D', '--dir', required=False, help='Directory to sort') args = vars(ap.parse_args()) if args['dir'] == None: DIR = os.getcwd() elif os.path.exists(args['dir']): DIR = args['dir'] for file in os.listdir(DIR): if not os.path.isdir(os.path.join(DIR, file)): name, ext = os.path.splitext(file) ext = ext[::-1][:-1][::-1] if os.path.exists(os.path.join(DIR, ext.upper())): shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext. upper(), file)) else: os.mkdir(os.path.join(DIR, ext.upper())) shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext. upper(), file))
flexible
{ "blob_id": "93737e4c409d0efb1ae2263cb60d4b03d9aad0d8", "index": 247, "step-1": "<mask token>\n", "step-2": "<mask token>\nap.add_argument('-D', '--dir', required=False, help='Directory to sort')\n<mask token>\nif args['dir'] == None:\n DIR = os.getcwd()\nelif os.path.exists(args['dir']):\n DIR = args['dir']\nfor file in os.listdir(DIR):\n if not os.path.isdir(os.path.join(DIR, file)):\n name, ext = os.path.splitext(file)\n ext = ext[::-1][:-1][::-1]\n if os.path.exists(os.path.join(DIR, ext.upper())):\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n else:\n os.mkdir(os.path.join(DIR, ext.upper()))\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n", "step-3": "<mask token>\nap = argparse.ArgumentParser()\nap.add_argument('-D', '--dir', required=False, help='Directory to sort')\nargs = vars(ap.parse_args())\nif args['dir'] == None:\n DIR = os.getcwd()\nelif os.path.exists(args['dir']):\n DIR = args['dir']\nfor file in os.listdir(DIR):\n if not os.path.isdir(os.path.join(DIR, file)):\n name, ext = os.path.splitext(file)\n ext = ext[::-1][:-1][::-1]\n if os.path.exists(os.path.join(DIR, ext.upper())):\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n else:\n os.mkdir(os.path.join(DIR, ext.upper()))\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n", "step-4": "import os\nimport shutil\nimport argparse\nap = argparse.ArgumentParser()\nap.add_argument('-D', '--dir', required=False, help='Directory to sort')\nargs = vars(ap.parse_args())\nif args['dir'] == None:\n DIR = os.getcwd()\nelif os.path.exists(args['dir']):\n DIR = args['dir']\nfor file in os.listdir(DIR):\n if not os.path.isdir(os.path.join(DIR, file)):\n name, ext = os.path.splitext(file)\n ext = ext[::-1][:-1][::-1]\n if os.path.exists(os.path.join(DIR, ext.upper())):\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n else:\n os.mkdir(os.path.join(DIR, ext.upper()))\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> def isSubsetSum(set, n, sum): subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)] for i in range(n + 1): subset[i][0] = True for i in range(1, sum + 1): subset[0][i] = False for i in range(1, n + 1): for j in range(1, sum + 1): if j < set[i - 1]: subset[i][j] = subset[i - 1][j] if j >= set[i - 1]: subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1] ] return subset[n][sum] <|reserved_special_token_0|> <|reserved_special_token_1|> def isSubsetSum(set, n, sum): subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)] for i in range(n + 1): subset[i][0] = True for i in range(1, sum + 1): subset[0][i] = False for i in range(1, n + 1): for j in range(1, sum + 1): if j < set[i - 1]: subset[i][j] = subset[i - 1][j] if j >= set[i - 1]: subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1] ] return subset[n][sum] <|reserved_special_token_0|> for i in range(t): n, k = map(int, input().split()) lst = list(map(int, input().strip().split(' ')))[:n] if isSubsetSum(lst, n, k) == True: print('YES') else: print('NO') <|reserved_special_token_1|> def isSubsetSum(set, n, sum): subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)] for i in range(n + 1): subset[i][0] = True for i in range(1, sum + 1): subset[0][i] = False for i in range(1, n + 1): for j in range(1, sum + 1): if j < set[i - 1]: subset[i][j] = subset[i - 1][j] if j >= set[i - 1]: subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1] ] return subset[n][sum] t = int(input()) for i in range(t): n, k = map(int, input().split()) lst = list(map(int, input().strip().split(' ')))[:n] if isSubsetSum(lst, n, k) == True: print('YES') else: print('NO') <|reserved_special_token_1|> def isSubsetSum(set, n, sum): subset =([[False for i in range(sum + 1)] for i in range(n + 1)]) for i in range(n + 1): subset[i][0] = True for i in range(1, sum + 1): subset[0][i]= False for i in range(1, n + 1): for j in range(1, sum + 1): if j<set[i-1]: subset[i][j] = subset[i-1][j] if j>= set[i-1]: subset[i][j] = (subset[i-1][j] or subset[i - 1][j-set[i-1]]) return subset[n][sum] t=int(input()) for i in range(t): n,k=map(int,input().split()) lst=list(map(int,input().strip().split(' ')))[:n] if (isSubsetSum(lst, n, k) == True): print("YES") else: print("NO")
flexible
{ "blob_id": "830e7e84eebd6a4adb411cc95c9e9c8ff7bdac30", "index": 778, "step-1": "<mask token>\n", "step-2": "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n subset[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if j < set[i - 1]:\n subset[i][j] = subset[i - 1][j]\n if j >= set[i - 1]:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1]\n ]\n return subset[n][sum]\n\n\n<mask token>\n", "step-3": "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n subset[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if j < set[i - 1]:\n subset[i][j] = subset[i - 1][j]\n if j >= set[i - 1]:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1]\n ]\n return subset[n][sum]\n\n\n<mask token>\nfor i in range(t):\n n, k = map(int, input().split())\n lst = list(map(int, input().strip().split(' ')))[:n]\n if isSubsetSum(lst, n, k) == True:\n print('YES')\n else:\n print('NO')\n", "step-4": "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n subset[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if j < set[i - 1]:\n subset[i][j] = subset[i - 1][j]\n if j >= set[i - 1]:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1]\n ]\n return subset[n][sum]\n\n\nt = int(input())\nfor i in range(t):\n n, k = map(int, input().split())\n lst = list(map(int, input().strip().split(' ')))[:n]\n if isSubsetSum(lst, n, k) == True:\n print('YES')\n else:\n print('NO')\n", "step-5": "def isSubsetSum(set, n, sum): \n subset =([[False for i in range(sum + 1)] for i in range(n + 1)]) \n for i in range(n + 1): \n subset[i][0] = True\n for i in range(1, sum + 1): \n subset[0][i]= False\n for i in range(1, n + 1): \n for j in range(1, sum + 1): \n if j<set[i-1]: \n subset[i][j] = subset[i-1][j] \n if j>= set[i-1]: \n subset[i][j] = (subset[i-1][j] or subset[i - 1][j-set[i-1]]) \n return subset[n][sum] \nt=int(input())\nfor i in range(t):\n n,k=map(int,input().split())\n lst=list(map(int,input().strip().split(' ')))[:n]\n if (isSubsetSum(lst, n, k) == True): \n print(\"YES\") \n else: \n print(\"NO\") \n \n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import unittest from app.party import Party from app.guest import Guest from app.shoppingList import ShoppingList def test_aPartywithNoGuestsShouldHaveNoPartyGuests(): party = Party() assert 0 == party.numberOfGuests() def test_aPartywithOneGuestShouldHaveOnePartyGuest(): party = Party() lisa = Guest("Lisa", 'female') party.attendedBy(lisa) assert 1 == party.numberOfGuests() def test_aPartywithThreeGuestsShouldHaveThreeGuests(): party = Party() lisa = Guest("Lisa", 'female') rob = Guest("Rob", 'male') susan = Guest("susan", 'female') party.attendedBy(lisa) party.attendedBy(rob) party.attendedBy(susan) assert 3 == party.numberOfGuests() def test_aGuestShouldBeAbleToLeaveAParty(): party = Party() lisa = Guest("Lisa", 'female') rob = Guest("Rob", 'male') susan = Guest("susan", 'female') party.attendedBy(lisa) party.attendedBy(rob) party.attendedBy(susan) party.leftBy(rob) assert 2 == party.numberOfGuests() def test_aPartyShouldHaveALocation(): party = Party() party.setLocation("my House") assert "my House" == party.getLocation() def test_aGuestShouldRevealHerName(): guest1 = Guest("Lisa", "female") assert "Lisa" == guest1.hasName() def test_weShouldKnowWhoIsAtTheParty(): party = Party() lisa = Guest("Lisa", 'female') rob = Guest("Rob", 'male') susan = Guest("susan", 'female') party.attendedBy(lisa) party.attendedBy(rob) party.attendedBy(susan) assert ["Lisa", "Rob", "susan"] == party.getAttendees() def test_weShouldBeAbleToCreateAnEmptyShoppingList(): shoppingList = ShoppingList() assert shoppingList.getItems() == [] def test_weShouldBeAbleToAddItemsToShoppingList(): shoppingList = ShoppingList() shoppingList.add("milk") assert shoppingList.getItems() == ["milk"] def test_createShoppingListBasedOnParty(): shoppingList = ShoppingList() party = Party() lisa = Guest("Lisa", 'female') rob = Guest("Rob", 'male') susan = Guest("susan", 'female') party.attendedBy(lisa) party.attendedBy(rob) party.attendedBy(susan) shoppingList.baseOn(party) assert shoppingList.getItems() == ["wine for 4", "food for 4"]
normal
{ "blob_id": "a8df6b575afbf6db415e0676a796623f2a9b7a70", "index": 8416, "step-1": "<mask token>\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n party = Party()\n lisa = Guest('Lisa', 'female')\n party.attendedBy(lisa)\n assert 1 == party.numberOfGuests()\n\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert 3 == party.numberOfGuests()\n\n\n<mask token>\n\n\ndef test_aPartyShouldHaveALocation():\n party = Party()\n party.setLocation('my House')\n assert 'my House' == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n guest1 = Guest('Lisa', 'female')\n assert 'Lisa' == guest1.hasName()\n\n\n<mask token>\n\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n shoppingList = ShoppingList()\n shoppingList.add('milk')\n assert shoppingList.getItems() == ['milk']\n\n\ndef test_createShoppingListBasedOnParty():\n shoppingList = ShoppingList()\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n shoppingList.baseOn(party)\n assert shoppingList.getItems() == ['wine for 4', 'food for 4']\n", "step-2": "<mask token>\n\n\ndef test_aPartywithNoGuestsShouldHaveNoPartyGuests():\n party = Party()\n assert 0 == party.numberOfGuests()\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n party = Party()\n lisa = Guest('Lisa', 'female')\n party.attendedBy(lisa)\n assert 1 == party.numberOfGuests()\n\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert 3 == party.numberOfGuests()\n\n\ndef test_aGuestShouldBeAbleToLeaveAParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n party.leftBy(rob)\n assert 2 == party.numberOfGuests()\n\n\ndef test_aPartyShouldHaveALocation():\n party = Party()\n party.setLocation('my House')\n assert 'my House' == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n guest1 = Guest('Lisa', 'female')\n assert 'Lisa' == guest1.hasName()\n\n\n<mask token>\n\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n shoppingList = ShoppingList()\n shoppingList.add('milk')\n assert shoppingList.getItems() == ['milk']\n\n\ndef test_createShoppingListBasedOnParty():\n shoppingList = ShoppingList()\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n shoppingList.baseOn(party)\n assert shoppingList.getItems() == ['wine for 4', 'food for 4']\n", "step-3": "<mask token>\n\n\ndef test_aPartywithNoGuestsShouldHaveNoPartyGuests():\n party = Party()\n assert 0 == party.numberOfGuests()\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n party = Party()\n lisa = Guest('Lisa', 'female')\n party.attendedBy(lisa)\n assert 1 == party.numberOfGuests()\n\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert 3 == party.numberOfGuests()\n\n\ndef test_aGuestShouldBeAbleToLeaveAParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n party.leftBy(rob)\n assert 2 == party.numberOfGuests()\n\n\ndef test_aPartyShouldHaveALocation():\n party = Party()\n party.setLocation('my House')\n assert 'my House' == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n guest1 = Guest('Lisa', 'female')\n assert 'Lisa' == guest1.hasName()\n\n\ndef test_weShouldKnowWhoIsAtTheParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert ['Lisa', 'Rob', 'susan'] == party.getAttendees()\n\n\n<mask token>\n\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n shoppingList = ShoppingList()\n shoppingList.add('milk')\n assert shoppingList.getItems() == ['milk']\n\n\ndef test_createShoppingListBasedOnParty():\n shoppingList = ShoppingList()\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n shoppingList.baseOn(party)\n assert shoppingList.getItems() == ['wine for 4', 'food for 4']\n", "step-4": "<mask token>\n\n\ndef test_aPartywithNoGuestsShouldHaveNoPartyGuests():\n party = Party()\n assert 0 == party.numberOfGuests()\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n party = Party()\n lisa = Guest('Lisa', 'female')\n party.attendedBy(lisa)\n assert 1 == party.numberOfGuests()\n\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert 3 == party.numberOfGuests()\n\n\ndef test_aGuestShouldBeAbleToLeaveAParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n party.leftBy(rob)\n assert 2 == party.numberOfGuests()\n\n\ndef test_aPartyShouldHaveALocation():\n party = Party()\n party.setLocation('my House')\n assert 'my House' == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n guest1 = Guest('Lisa', 'female')\n assert 'Lisa' == guest1.hasName()\n\n\ndef test_weShouldKnowWhoIsAtTheParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert ['Lisa', 'Rob', 'susan'] == party.getAttendees()\n\n\ndef test_weShouldBeAbleToCreateAnEmptyShoppingList():\n shoppingList = ShoppingList()\n assert shoppingList.getItems() == []\n\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n shoppingList = ShoppingList()\n shoppingList.add('milk')\n assert shoppingList.getItems() == ['milk']\n\n\ndef test_createShoppingListBasedOnParty():\n shoppingList = ShoppingList()\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n shoppingList.baseOn(party)\n assert shoppingList.getItems() == ['wine for 4', 'food for 4']\n", "step-5": "import unittest\nfrom app.party import Party\nfrom app.guest import Guest\nfrom app.shoppingList import ShoppingList\n\ndef test_aPartywithNoGuestsShouldHaveNoPartyGuests():\n\tparty = Party()\n\tassert 0 == party.numberOfGuests()\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\tparty.attendedBy(lisa)\n\tassert 1 == party.numberOfGuests()\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\trob = Guest(\"Rob\", 'male')\n\tsusan = Guest(\"susan\", 'female')\n\tparty.attendedBy(lisa)\n\tparty.attendedBy(rob)\n\tparty.attendedBy(susan)\n\tassert 3 == party.numberOfGuests()\n\ndef test_aGuestShouldBeAbleToLeaveAParty():\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\trob = Guest(\"Rob\", 'male')\n\tsusan = Guest(\"susan\", 'female')\n\tparty.attendedBy(lisa)\n\tparty.attendedBy(rob)\n\tparty.attendedBy(susan)\n\tparty.leftBy(rob)\n\tassert 2 == party.numberOfGuests()\n\ndef test_aPartyShouldHaveALocation():\n\tparty = Party()\n\tparty.setLocation(\"my House\")\n\tassert \"my House\" == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n\tguest1 = Guest(\"Lisa\", \"female\")\n\tassert \"Lisa\" == guest1.hasName()\n\ndef test_weShouldKnowWhoIsAtTheParty():\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\trob = Guest(\"Rob\", 'male')\n\tsusan = Guest(\"susan\", 'female')\n\tparty.attendedBy(lisa)\n\tparty.attendedBy(rob)\n\tparty.attendedBy(susan)\n\tassert [\"Lisa\", \"Rob\", \"susan\"] == party.getAttendees()\n\n\ndef test_weShouldBeAbleToCreateAnEmptyShoppingList():\n\tshoppingList = ShoppingList()\n\tassert shoppingList.getItems() == []\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n\tshoppingList = ShoppingList()\n\tshoppingList.add(\"milk\")\n\tassert shoppingList.getItems() == [\"milk\"]\n\n\ndef test_createShoppingListBasedOnParty():\n\tshoppingList = ShoppingList()\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\trob = Guest(\"Rob\", 'male')\n\tsusan = Guest(\"susan\", 'female')\n\tparty.attendedBy(lisa)\n\tparty.attendedBy(rob)\n\tparty.attendedBy(susan)\n\tshoppingList.baseOn(party)\n\tassert shoppingList.getItems() == [\"wine for 4\", \"food for 4\"]\n\n\n", "step-ids": [ 6, 8, 9, 10, 12 ] }
[ 6, 8, 9, 10, 12 ]
#======================================================================= __version__ = '''0.0.01''' __sub_version__ = '''20130714221105''' __copyright__ = '''(c) Alex A. Naanou 2011''' #----------------------------------------------------------------------- import os import sha import md5 import base64 import time import pyexiv2 as metadata #----------------------------------------------------------------------- # XXX need a strategy to check if two files that have the same GID are # identical, and if so, need to destinguish them in the GID... # might be a good idea to add a file hash # XXX not yet sure if this is unique enough to avoid conflicts if one # photographer has enough cameras... # XXX also might be wise to add a photographer ID into here... ##!!! add gid info section to identify the options used to greate a gid, e.g. EXIF date vs. ctime, etc. ##!!! do a general revision and remove leacy... def image_gid(path, date=None, format='%(artist)s-%(date)s-%(name)s', date_format='%Y%m%d-%H%M%S', default_artist='Unknown', use_ctime=False, hash_func=lambda s: sha.sha(s).hexdigest()): ''' Calculate image GID. Main gid criteria: - unique - calculable from the item (preferably any sub-item) - human-readable Default format: <artist>-<datetime>-<filename> Example: Alex_A.Naanou-20110627-195706-DSC_1234 If hash_func is not None, then the function will be used to generate a hex hash from the above string. Supported fields: %(artist)s - Exif.Image.Artist field, stripped and spaces replaced with underscores. If no artist info is set this will be set to default_artist. %(date)s - Exif.Photo.DateTimeOriginal formated to date_format argument. %(name)s - file name. NOTE: date and time are the date and time the image was made ('Exif.Image.DateTime') NOTE: need EXIF data to generate a GID ''' # get the filename... data = { 'name': os.path.splitext(os.path.split(path)[-1])[0], } ##!!! this might fail... i = metadata.ImageMetadata('%s' % path) try: i.read() except IOError: # can't read exif... i = None # check if we need a date in the id... if '%(date)s' in format: if date is not None: data['date'] = time.strftime(date_format, time.gmtime(date)) elif use_ctime or i is None: date = os.path.getctime(path) data['date'] = time.strftime(date_format, time.gmtime(date)) else: date = i['Exif.Photo.DateTimeOriginal'].value data['date'] = date.strftime(date_format) # check if we need an artist... if '%(artist)s' in format: data['artist'] = default_artist if i is not None: try: # set the artist if in EXIF... a = i['Exif.Image.Artist'].value.strip().replace(' ', '_') if a != '': data['artist'] = a except KeyError: pass if hash_func is not None: return hash_func(format % data) return format % data #--------------------------------------------------handle_commandline--- def handle_commandline(): from optparse import OptionParser parser = OptionParser() ##!!! need to define the path so that it shoes up in -h parser.add_option('-t', '--text', dest='format', action='store_const', const='text', default='sha', help='output GUID in base64 format.') parser.add_option('-b', '--base64', dest='format', action='store_const', const='base64', default='sha', help='output GUID in text format.') parser.add_option('-s', '--sha', dest='format', action='store_const', const='sha', default='sha', help='output GUID in sha format.') options, args = parser.parse_args() if len(args) != 1: parser.print_usage() else: IN_PATH = args[0] IN_PATH = IN_PATH.replace('\\', '/') if options.format == 'text': print image_gid(IN_PATH, hash_func=None) elif options.format == 'base64': # also remove the trailing \n... print image_gid(IN_PATH, hash_func=lambda s: base64.encodestring(s).strip()) else: print image_gid(IN_PATH) #----------------------------------------------------------------------- if __name__ == '__main__': handle_commandline() #======================================================================= # vim:set ts=4 sw=4 nowrap :
normal
{ "blob_id": "d03f87b7dfa8fe2c63500effda1bea5e41f17ffc", "index": 3787, "step-1": "#=======================================================================\r\n\r\n__version__ = '''0.0.01'''\r\n__sub_version__ = '''20130714221105'''\r\n__copyright__ = '''(c) Alex A. Naanou 2011'''\r\n\r\n\r\n#-----------------------------------------------------------------------\r\n\r\nimport os\r\nimport sha\r\nimport md5\r\nimport base64\r\nimport time\r\n\r\nimport pyexiv2 as metadata\r\n\r\n\r\n#-----------------------------------------------------------------------\r\n\r\n# XXX need a strategy to check if two files that have the same GID are\r\n# \t identical, and if so, need to destinguish them in the GID...\r\n# \t might be a good idea to add a file hash\r\n# XXX not yet sure if this is unique enough to avoid conflicts if one\r\n# \t photographer has enough cameras...\r\n# XXX also might be wise to add a photographer ID into here...\r\n##!!! add gid info section to identify the options used to greate a gid, e.g. EXIF date vs. ctime, etc.\r\n##!!! do a general revision and remove leacy...\r\ndef image_gid(path, date=None, \r\n\t\tformat='%(artist)s-%(date)s-%(name)s', \r\n\t\tdate_format='%Y%m%d-%H%M%S', \r\n\t\tdefault_artist='Unknown',\r\n\t\tuse_ctime=False,\r\n\t\thash_func=lambda s: sha.sha(s).hexdigest()):\r\n\t'''\r\n\tCalculate image GID.\r\n\r\n\tMain gid criteria:\r\n\t \t- unique\r\n\t \t- calculable from the item (preferably any sub-item)\r\n\t \t- human-readable\r\n\r\n\tDefault format:\r\n\t\t<artist>-<datetime>-<filename>\r\n\r\n\tExample:\r\n\t\tAlex_A.Naanou-20110627-195706-DSC_1234\t\r\n\r\n\tIf hash_func is not None, then the function will be used to generate \r\n\ta hex hash from the above string.\r\n\r\n\tSupported fields:\r\n\t\t%(artist)s\t- Exif.Image.Artist field, stripped and spaces replaced\r\n\t\t\t\t\t with underscores.\r\n\t\t\t\t\t If no artist info is set this will be set to default_artist.\r\n\t\t%(date)s\t- Exif.Photo.DateTimeOriginal formated to date_format argument.\r\n\t\t%(name)s\t- file name.\r\n\r\n\tNOTE: date and time are the date and time the image was made ('Exif.Image.DateTime')\r\n\tNOTE: need EXIF data to generate a GID\r\n\t'''\r\n\t# get the filename...\r\n\tdata = {\r\n\t\t'name': os.path.splitext(os.path.split(path)[-1])[0],\r\n\t}\r\n\t##!!! this might fail...\r\n\ti = metadata.ImageMetadata('%s' % path)\r\n\ttry:\r\n\t\ti.read()\r\n\texcept IOError:\r\n\t\t# can't read exif...\r\n\t\ti = None\r\n\t# check if we need a date in the id...\r\n\tif '%(date)s' in format:\r\n\t\tif date is not None:\r\n\t\t\tdata['date'] = time.strftime(date_format, time.gmtime(date))\r\n\t\telif use_ctime or i is None:\r\n\t\t\tdate = os.path.getctime(path)\r\n\t\t\tdata['date'] = time.strftime(date_format, time.gmtime(date))\r\n\t\telse:\r\n\t\t\tdate = i['Exif.Photo.DateTimeOriginal'].value\r\n\t\t\tdata['date'] = date.strftime(date_format)\r\n\t# check if we need an artist...\r\n\tif '%(artist)s' in format:\r\n\t\tdata['artist'] = default_artist\r\n\t\tif i is not None:\r\n\t\t\ttry:\r\n\t\t\t\t# set the artist if in EXIF...\r\n\t\t\t\ta = i['Exif.Image.Artist'].value.strip().replace(' ', '_')\r\n\t\t\t\tif a != '':\r\n\t\t\t\t\tdata['artist'] = a\r\n\t\t\texcept KeyError:\r\n\t\t\t\tpass\r\n\t\r\n\tif hash_func is not None:\r\n\t\treturn hash_func(format % data)\r\n\treturn format % data\r\n\r\n\r\n\r\n#--------------------------------------------------handle_commandline---\r\ndef handle_commandline():\r\n\tfrom optparse import OptionParser\r\n\r\n\tparser = OptionParser()\r\n\r\n\t##!!! need to define the path so that it shoes up in -h\r\n\r\n\tparser.add_option('-t', '--text',\r\n\t\t\t\t\t\tdest='format',\r\n\t\t\t\t\t\taction='store_const',\r\n\t\t\t\t\t\tconst='text',\r\n\t\t\t\t\t\tdefault='sha',\r\n\t\t\t\t\t\thelp='output GUID in base64 format.')\r\n\tparser.add_option('-b', '--base64',\r\n\t\t\t\t\t\tdest='format',\r\n\t\t\t\t\t\taction='store_const',\r\n\t\t\t\t\t\tconst='base64',\r\n\t\t\t\t\t\tdefault='sha',\r\n\t\t\t\t\t\thelp='output GUID in text format.')\r\n\tparser.add_option('-s', '--sha',\r\n\t\t\t\t\t\tdest='format',\r\n\t\t\t\t\t\taction='store_const',\r\n\t\t\t\t\t\tconst='sha',\r\n\t\t\t\t\t\tdefault='sha',\r\n\t\t\t\t\t\thelp='output GUID in sha format.')\r\n\r\n\toptions, args = parser.parse_args()\r\n\r\n\tif len(args) != 1:\r\n\t\tparser.print_usage()\r\n\telse:\r\n\t\tIN_PATH = args[0]\r\n\t\tIN_PATH = IN_PATH.replace('\\\\', '/')\r\n\r\n\t\tif options.format == 'text':\r\n\t\t\tprint image_gid(IN_PATH, hash_func=None)\r\n\t\telif options.format == 'base64':\r\n\t\t\t# also remove the trailing \\n...\r\n\t\t\tprint image_gid(IN_PATH, hash_func=lambda s: base64.encodestring(s).strip())\r\n\t\telse:\r\n\t\t\tprint image_gid(IN_PATH)\r\n\r\n\r\n#-----------------------------------------------------------------------\r\nif __name__ == '__main__':\r\n\thandle_commandline()\r\n\r\n\r\n\r\n#=======================================================================\r\n# vim:set ts=4 sw=4 nowrap :\r\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import rdflib import csv from time import sleep gtypes = {} dtypes = {} atypes = {} g = rdflib.Graph() g.parse("http://geographicknowledge.de/vocab/CoreConceptData.rdf#") g.parse("./ontology.ttl", format="ttl") sleep(.5) results = g.query(""" prefix skos: <http://www.w3.org/2004/02/skos/core#> prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#> prefix dcat: <https://www.w3.org/TR/vocab-dcat#> prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> select ?dataset ?type where { ?dataset a dcat:Dataset , ?type . filter ( ?type in ( ccd:PointDataSet, ccd:RegionDataSet, ccd:VectorTessellation, ccd:LineDataSet ) ) } """) for result in results: uri, geometry_type = result gtypes[str(uri)] = str(geometry_type).split('#')[1] results = g.query(""" prefix skos: <http://www.w3.org/2004/02/skos/core#> prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#> prefix dcat: <https://www.w3.org/TR/vocab-dcat#> prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> select ?dataset ?type where { ?dataset a dcat:Dataset , ?type . ?type rdfs:subClassOf+ ccd:CoreConceptDataSet . } """) for result in results: uri, dtype = result dtypes[str(uri)] = str(dtype).split('#')[1] results = g.query(""" prefix skos: <http://www.w3.org/2004/02/skos/core#> prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#> prefix ada: <http://geographicknowledge.de/vocab/AnalysisData.rdf> prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> select ?dataset ?label ?type where { ?attribute ada:ofDataSet ?dataset ; skos:exactMatch ?concept ; rdfs:label ?label . optional { ?concept a ?type . ?type rdfs:subClassOf+ ccd:Attribute . } } group by ?dataset ?label ?type """) for result in results: dataset, label, atype = result key = (str(dataset), str(label)) if atype is None and key not in atypes: atypes[key] = "" elif atype is not None: atypes[key] = str(atype).split('#')[1] test_gtypes = {} test_dtypes = {} test_atypes = {} with open("./datasets/annotations_datasets.csv", 'r') as fin: reader = csv.reader(fin) next(reader) for row in reader: test_gtypes[row[0]] = row[1] test_dtypes[row[0]] = row[2] with open("./datasets/annotations_attributes.csv", 'r') as fin: reader = csv.reader(fin) next(reader) for row in reader: test_atypes[(row[0],row[1])] = row[2] tp = 0 total = 0 fn = len(test_gtypes) for k, v in gtypes.items(): if k not in test_gtypes: # skip some extra test datasets continue total += 1 if test_gtypes[k] == v: tp += 1 fn -= 1 p = tp / total r = tp / (tp + fn) f = 2 * ((p * r) / (p + r)) print("Geometry type scores:") print(f"P: {p} , R: {r} , F: {f}") tp = 0 total = 0 fn = len(test_dtypes) for k, v in dtypes.items(): if k not in test_dtypes: continue total += 1 if test_dtypes[k] == v: tp += 1 fn -= 1 p = tp / total r = tp / (tp + fn) f = 2 * ((p * r) / (p + r)) print("Dataset type scores:") print(f"P: {p} , R: {r} , F: {f}") filter_nontypes = True if filter_nontypes: test_atypes = {k: v for k, v in test_atypes.items() if v != ""} atypes = {k: v for k, v in atypes.items() if v != ""} tp = 0 total = 0 fn = len(list(filter(lambda x: x != "", test_atypes.values()))) for k, v in atypes.items(): if k not in test_atypes: continue if v != "": total += 1 if test_atypes[k] == v: tp += 1 fn -= 1 elif v == "BooleanA" and test_atypes[k] == "NominalA": # boolean is "more" correct tp += 1 fn -= 1 else: print(k, v, test_atypes[k]) p = tp / total r = tp / (tp + fn) f = 2 * ((p * r) / (p + r)) print("Attribute type scores:") print(f"P: {p} , R: {r} , F: {f}")
normal
{ "blob_id": "eb1fbe2de3c8548175eb3c8720353e466e3b68c7", "index": 7336, "step-1": "<mask token>\n", "step-2": "<mask token>\ng.parse('http://geographicknowledge.de/vocab/CoreConceptData.rdf#')\ng.parse('./ontology.ttl', format='ttl')\nsleep(0.5)\n<mask token>\nfor result in results:\n uri, geometry_type = result\n gtypes[str(uri)] = str(geometry_type).split('#')[1]\n<mask token>\nfor result in results:\n uri, dtype = result\n dtypes[str(uri)] = str(dtype).split('#')[1]\n<mask token>\nfor result in results:\n dataset, label, atype = result\n key = str(dataset), str(label)\n if atype is None and key not in atypes:\n atypes[key] = ''\n elif atype is not None:\n atypes[key] = str(atype).split('#')[1]\n<mask token>\nwith open('./datasets/annotations_datasets.csv', 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n test_gtypes[row[0]] = row[1]\n test_dtypes[row[0]] = row[2]\nwith open('./datasets/annotations_attributes.csv', 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n test_atypes[row[0], row[1]] = row[2]\n<mask token>\nfor k, v in gtypes.items():\n if k not in test_gtypes:\n continue\n total += 1\n if test_gtypes[k] == v:\n tp += 1\n fn -= 1\n<mask token>\nprint('Geometry type scores:')\nprint(f'P: {p} , R: {r} , F: {f}')\n<mask token>\nfor k, v in dtypes.items():\n if k not in test_dtypes:\n continue\n total += 1\n if test_dtypes[k] == v:\n tp += 1\n fn -= 1\n<mask token>\nprint('Dataset type scores:')\nprint(f'P: {p} , R: {r} , F: {f}')\n<mask token>\nif filter_nontypes:\n test_atypes = {k: v for k, v in test_atypes.items() if v != ''}\n atypes = {k: v for k, v in atypes.items() if v != ''}\n<mask token>\nfor k, v in atypes.items():\n if k not in test_atypes:\n continue\n if v != '':\n total += 1\n if test_atypes[k] == v:\n tp += 1\n fn -= 1\n elif v == 'BooleanA' and test_atypes[k] == 'NominalA':\n tp += 1\n fn -= 1\n else:\n print(k, v, test_atypes[k])\n<mask token>\nprint('Attribute type scores:')\nprint(f'P: {p} , R: {r} , F: {f}')\n", "step-3": "<mask token>\ngtypes = {}\ndtypes = {}\natypes = {}\ng = rdflib.Graph()\ng.parse('http://geographicknowledge.de/vocab/CoreConceptData.rdf#')\ng.parse('./ontology.ttl', format='ttl')\nsleep(0.5)\nresults = g.query(\n \"\"\"\n prefix skos: <http://www.w3.org/2004/02/skos/core#>\n prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#>\n prefix dcat: <https://www.w3.org/TR/vocab-dcat#>\n prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\n select ?dataset ?type\n where {\n ?dataset a dcat:Dataset , ?type .\n\n filter (\n ?type in ( ccd:PointDataSet, ccd:RegionDataSet, ccd:VectorTessellation, ccd:LineDataSet )\n )\n }\n\"\"\"\n )\nfor result in results:\n uri, geometry_type = result\n gtypes[str(uri)] = str(geometry_type).split('#')[1]\nresults = g.query(\n \"\"\"\n prefix skos: <http://www.w3.org/2004/02/skos/core#>\n prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#>\n prefix dcat: <https://www.w3.org/TR/vocab-dcat#>\n prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\n select ?dataset ?type\n where {\n ?dataset a dcat:Dataset , ?type .\n ?type rdfs:subClassOf+ ccd:CoreConceptDataSet .\n }\n\"\"\"\n )\nfor result in results:\n uri, dtype = result\n dtypes[str(uri)] = str(dtype).split('#')[1]\nresults = g.query(\n \"\"\"\n prefix skos: <http://www.w3.org/2004/02/skos/core#>\n prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#>\n prefix ada: <http://geographicknowledge.de/vocab/AnalysisData.rdf>\n prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\n select ?dataset ?label ?type\n where {\n ?attribute ada:ofDataSet ?dataset ;\n skos:exactMatch ?concept ;\n rdfs:label ?label .\n\n optional {\n ?concept a ?type .\n ?type rdfs:subClassOf+ ccd:Attribute .\n }\n }\n group by ?dataset ?label ?type\n\"\"\"\n )\nfor result in results:\n dataset, label, atype = result\n key = str(dataset), str(label)\n if atype is None and key not in atypes:\n atypes[key] = ''\n elif atype is not None:\n atypes[key] = str(atype).split('#')[1]\ntest_gtypes = {}\ntest_dtypes = {}\ntest_atypes = {}\nwith open('./datasets/annotations_datasets.csv', 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n test_gtypes[row[0]] = row[1]\n test_dtypes[row[0]] = row[2]\nwith open('./datasets/annotations_attributes.csv', 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n test_atypes[row[0], row[1]] = row[2]\ntp = 0\ntotal = 0\nfn = len(test_gtypes)\nfor k, v in gtypes.items():\n if k not in test_gtypes:\n continue\n total += 1\n if test_gtypes[k] == v:\n tp += 1\n fn -= 1\np = tp / total\nr = tp / (tp + fn)\nf = 2 * (p * r / (p + r))\nprint('Geometry type scores:')\nprint(f'P: {p} , R: {r} , F: {f}')\ntp = 0\ntotal = 0\nfn = len(test_dtypes)\nfor k, v in dtypes.items():\n if k not in test_dtypes:\n continue\n total += 1\n if test_dtypes[k] == v:\n tp += 1\n fn -= 1\np = tp / total\nr = tp / (tp + fn)\nf = 2 * (p * r / (p + r))\nprint('Dataset type scores:')\nprint(f'P: {p} , R: {r} , F: {f}')\nfilter_nontypes = True\nif filter_nontypes:\n test_atypes = {k: v for k, v in test_atypes.items() if v != ''}\n atypes = {k: v for k, v in atypes.items() if v != ''}\ntp = 0\ntotal = 0\nfn = len(list(filter(lambda x: x != '', test_atypes.values())))\nfor k, v in atypes.items():\n if k not in test_atypes:\n continue\n if v != '':\n total += 1\n if test_atypes[k] == v:\n tp += 1\n fn -= 1\n elif v == 'BooleanA' and test_atypes[k] == 'NominalA':\n tp += 1\n fn -= 1\n else:\n print(k, v, test_atypes[k])\np = tp / total\nr = tp / (tp + fn)\nf = 2 * (p * r / (p + r))\nprint('Attribute type scores:')\nprint(f'P: {p} , R: {r} , F: {f}')\n", "step-4": "import rdflib\nimport csv\nfrom time import sleep\ngtypes = {}\ndtypes = {}\natypes = {}\ng = rdflib.Graph()\ng.parse('http://geographicknowledge.de/vocab/CoreConceptData.rdf#')\ng.parse('./ontology.ttl', format='ttl')\nsleep(0.5)\nresults = g.query(\n \"\"\"\n prefix skos: <http://www.w3.org/2004/02/skos/core#>\n prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#>\n prefix dcat: <https://www.w3.org/TR/vocab-dcat#>\n prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\n select ?dataset ?type\n where {\n ?dataset a dcat:Dataset , ?type .\n\n filter (\n ?type in ( ccd:PointDataSet, ccd:RegionDataSet, ccd:VectorTessellation, ccd:LineDataSet )\n )\n }\n\"\"\"\n )\nfor result in results:\n uri, geometry_type = result\n gtypes[str(uri)] = str(geometry_type).split('#')[1]\nresults = g.query(\n \"\"\"\n prefix skos: <http://www.w3.org/2004/02/skos/core#>\n prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#>\n prefix dcat: <https://www.w3.org/TR/vocab-dcat#>\n prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\n select ?dataset ?type\n where {\n ?dataset a dcat:Dataset , ?type .\n ?type rdfs:subClassOf+ ccd:CoreConceptDataSet .\n }\n\"\"\"\n )\nfor result in results:\n uri, dtype = result\n dtypes[str(uri)] = str(dtype).split('#')[1]\nresults = g.query(\n \"\"\"\n prefix skos: <http://www.w3.org/2004/02/skos/core#>\n prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#>\n prefix ada: <http://geographicknowledge.de/vocab/AnalysisData.rdf>\n prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\n select ?dataset ?label ?type\n where {\n ?attribute ada:ofDataSet ?dataset ;\n skos:exactMatch ?concept ;\n rdfs:label ?label .\n\n optional {\n ?concept a ?type .\n ?type rdfs:subClassOf+ ccd:Attribute .\n }\n }\n group by ?dataset ?label ?type\n\"\"\"\n )\nfor result in results:\n dataset, label, atype = result\n key = str(dataset), str(label)\n if atype is None and key not in atypes:\n atypes[key] = ''\n elif atype is not None:\n atypes[key] = str(atype).split('#')[1]\ntest_gtypes = {}\ntest_dtypes = {}\ntest_atypes = {}\nwith open('./datasets/annotations_datasets.csv', 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n test_gtypes[row[0]] = row[1]\n test_dtypes[row[0]] = row[2]\nwith open('./datasets/annotations_attributes.csv', 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n test_atypes[row[0], row[1]] = row[2]\ntp = 0\ntotal = 0\nfn = len(test_gtypes)\nfor k, v in gtypes.items():\n if k not in test_gtypes:\n continue\n total += 1\n if test_gtypes[k] == v:\n tp += 1\n fn -= 1\np = tp / total\nr = tp / (tp + fn)\nf = 2 * (p * r / (p + r))\nprint('Geometry type scores:')\nprint(f'P: {p} , R: {r} , F: {f}')\ntp = 0\ntotal = 0\nfn = len(test_dtypes)\nfor k, v in dtypes.items():\n if k not in test_dtypes:\n continue\n total += 1\n if test_dtypes[k] == v:\n tp += 1\n fn -= 1\np = tp / total\nr = tp / (tp + fn)\nf = 2 * (p * r / (p + r))\nprint('Dataset type scores:')\nprint(f'P: {p} , R: {r} , F: {f}')\nfilter_nontypes = True\nif filter_nontypes:\n test_atypes = {k: v for k, v in test_atypes.items() if v != ''}\n atypes = {k: v for k, v in atypes.items() if v != ''}\ntp = 0\ntotal = 0\nfn = len(list(filter(lambda x: x != '', test_atypes.values())))\nfor k, v in atypes.items():\n if k not in test_atypes:\n continue\n if v != '':\n total += 1\n if test_atypes[k] == v:\n tp += 1\n fn -= 1\n elif v == 'BooleanA' and test_atypes[k] == 'NominalA':\n tp += 1\n fn -= 1\n else:\n print(k, v, test_atypes[k])\np = tp / total\nr = tp / (tp + fn)\nf = 2 * (p * r / (p + r))\nprint('Attribute type scores:')\nprint(f'P: {p} , R: {r} , F: {f}')\n", "step-5": "import rdflib\nimport csv\n\nfrom time import sleep\n\ngtypes = {}\ndtypes = {}\natypes = {}\n\ng = rdflib.Graph()\ng.parse(\"http://geographicknowledge.de/vocab/CoreConceptData.rdf#\")\ng.parse(\"./ontology.ttl\", format=\"ttl\")\n\nsleep(.5)\n\nresults = g.query(\"\"\"\n prefix skos: <http://www.w3.org/2004/02/skos/core#>\n prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#>\n prefix dcat: <https://www.w3.org/TR/vocab-dcat#>\n prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\n select ?dataset ?type\n where {\n ?dataset a dcat:Dataset , ?type .\n\n filter (\n ?type in ( ccd:PointDataSet, ccd:RegionDataSet, ccd:VectorTessellation, ccd:LineDataSet )\n )\n }\n\"\"\")\n\nfor result in results:\n uri, geometry_type = result\n gtypes[str(uri)] = str(geometry_type).split('#')[1]\n\nresults = g.query(\"\"\"\n prefix skos: <http://www.w3.org/2004/02/skos/core#>\n prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#>\n prefix dcat: <https://www.w3.org/TR/vocab-dcat#>\n prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\n select ?dataset ?type\n where {\n ?dataset a dcat:Dataset , ?type .\n ?type rdfs:subClassOf+ ccd:CoreConceptDataSet .\n }\n\"\"\")\n\nfor result in results:\n uri, dtype = result\n dtypes[str(uri)] = str(dtype).split('#')[1]\n\n\nresults = g.query(\"\"\"\n prefix skos: <http://www.w3.org/2004/02/skos/core#>\n prefix ccd: <http://geographicknowledge.de/vocab/CoreConceptData.rdf#>\n prefix ada: <http://geographicknowledge.de/vocab/AnalysisData.rdf>\n prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\n select ?dataset ?label ?type\n where {\n ?attribute ada:ofDataSet ?dataset ;\n skos:exactMatch ?concept ;\n rdfs:label ?label .\n\n optional {\n ?concept a ?type .\n ?type rdfs:subClassOf+ ccd:Attribute .\n }\n }\n group by ?dataset ?label ?type\n\"\"\")\n\nfor result in results:\n dataset, label, atype = result\n key = (str(dataset), str(label))\n if atype is None and key not in atypes:\n atypes[key] = \"\"\n elif atype is not None:\n atypes[key] = str(atype).split('#')[1]\n\n\ntest_gtypes = {}\ntest_dtypes = {}\ntest_atypes = {}\n\nwith open(\"./datasets/annotations_datasets.csv\", 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n test_gtypes[row[0]] = row[1]\n test_dtypes[row[0]] = row[2]\n\nwith open(\"./datasets/annotations_attributes.csv\", 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n test_atypes[(row[0],row[1])] = row[2]\n\ntp = 0\ntotal = 0\nfn = len(test_gtypes)\nfor k, v in gtypes.items():\n if k not in test_gtypes: # skip some extra test datasets\n continue\n total += 1\n\n if test_gtypes[k] == v:\n tp += 1\n fn -= 1\n\np = tp / total\nr = tp / (tp + fn)\nf = 2 * ((p * r) / (p + r))\n\nprint(\"Geometry type scores:\")\nprint(f\"P: {p} , R: {r} , F: {f}\")\n\n\ntp = 0\ntotal = 0\nfn = len(test_dtypes)\nfor k, v in dtypes.items():\n if k not in test_dtypes:\n continue\n total += 1\n\n if test_dtypes[k] == v:\n tp += 1\n fn -= 1\n\np = tp / total\nr = tp / (tp + fn)\nf = 2 * ((p * r) / (p + r))\n\nprint(\"Dataset type scores:\")\nprint(f\"P: {p} , R: {r} , F: {f}\")\n\n\nfilter_nontypes = True\nif filter_nontypes:\n test_atypes = {k: v for k, v in test_atypes.items() if v != \"\"}\n atypes = {k: v for k, v in atypes.items() if v != \"\"}\n\ntp = 0\ntotal = 0\nfn = len(list(filter(lambda x: x != \"\", test_atypes.values())))\nfor k, v in atypes.items():\n if k not in test_atypes:\n continue\n\n if v != \"\":\n total += 1\n\n if test_atypes[k] == v:\n tp += 1\n fn -= 1\n elif v == \"BooleanA\" and test_atypes[k] == \"NominalA\": # boolean is \"more\" correct\n tp += 1\n fn -= 1\n else:\n print(k, v, test_atypes[k])\n\np = tp / total\nr = tp / (tp + fn)\nf = 2 * ((p * r) / (p + r))\n\nprint(\"Attribute type scores:\")\nprint(f\"P: {p} , R: {r} , F: {f}\")\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
__path__.append( '/cvmfs/cms.cern.ch/slc6_amd64_gcc481/cms/cmssw-patch/CMSSW_7_0_6_patch3/python/ggAnalysis' )
normal
{ "blob_id": "0345c3c2049c972370cd7bde5a6e0a1dfa5dfe66", "index": 3719, "step-1": "<mask token>\n", "step-2": "__path__.append(\n '/cvmfs/cms.cern.ch/slc6_amd64_gcc481/cms/cmssw-patch/CMSSW_7_0_6_patch3/python/ggAnalysis'\n )\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
import logging import os import time from datetime import datetime from pathlib import Path from configargparse import ArgumentParser from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.x509.oid import ExtensionOID from cryptography.x509.extensions import ExtensionNotFound from prettylog import basic_config from prometheus_client import start_http_server from prometheus_client.core import GaugeMetricFamily, REGISTRY parser = ArgumentParser( default_config_files=[os.path.join("/etc/ssl-exporter.conf")], auto_env_var_prefix="APP_", ) parser.add_argument("--host-address", type=str, default="0.0.0.0") parser.add_argument("--port", type=int, default="9001") parser.add_argument("--cert-paths", nargs="+", type=Path) parser.add_argument("--log-level", type=str, default="INFO") parser.add_argument("--log-format", type=str, default="color") arguments = parser.parse_args() log = logging.getLogger() class SslExporter(object): gauges = {} def __init__(self, cert_paths): self.cert_paths = cert_paths def collect(self): self.gauges["ssl_valid_days"] = GaugeMetricFamily( "ssl_valid_days", "Ssl cert valid days", value=None, labels=["domain", "file_name", "serial_number"], ) for path in self.cert_paths: if not path.exists(): log.error("File %r does not exists", path) exit(1) self.get_metrics(path) for name, data in self.gauges.items(): yield data def get_metrics(self, path: Path): with path.open("rb") as f: try: cert = x509.load_pem_x509_certificate( f.read(), default_backend() ) except ValueError: log.exception("Cannot read certificate - %r", path) return [] file_name = path.name log.debug("File name of cert - %r", file_name) not_valid_after = cert.not_valid_after log.debug("Ssl not valid after date - %r", str(not_valid_after)) left = not_valid_after - datetime.utcnow() log.debug("Ssl cert valid days - %r", left.days) log.debug("Ssl cert serial number - %r", cert.serial_number) try: ext = cert.extensions.get_extension_for_oid( ExtensionOID.SUBJECT_ALTERNATIVE_NAME ) dns_names_list = ext.value.get_values_for_type(x509.DNSName) except ExtensionNotFound: dns_names_list = ["noname"] log.debug("DNS names of cert - %r", dns_names_list) for domain in dns_names_list: self.gauges["ssl_valid_days"].add_metric( [domain, file_name, str(cert.serial_number)], int(left.days) ) def main(): basic_config( level=arguments.log_level.upper(), buffered=False, log_format=arguments.log_format, ) start_http_server(addr=arguments.host_address, port=arguments.port) collector = SslExporter(arguments.cert_paths) REGISTRY.register(collector) while True: time.sleep(1) if __name__ == "__main__": main()
normal
{ "blob_id": "83be35b79dcaa34f9273281976ebb71e81c58cdd", "index": 8673, "step-1": "<mask token>\n\n\nclass SslExporter(object):\n gauges = {}\n\n def __init__(self, cert_paths):\n self.cert_paths = cert_paths\n\n def collect(self):\n self.gauges['ssl_valid_days'] = GaugeMetricFamily('ssl_valid_days',\n 'Ssl cert valid days', value=None, labels=['domain',\n 'file_name', 'serial_number'])\n for path in self.cert_paths:\n if not path.exists():\n log.error('File %r does not exists', path)\n exit(1)\n self.get_metrics(path)\n for name, data in self.gauges.items():\n yield data\n\n def get_metrics(self, path: Path):\n with path.open('rb') as f:\n try:\n cert = x509.load_pem_x509_certificate(f.read(),\n default_backend())\n except ValueError:\n log.exception('Cannot read certificate - %r', path)\n return []\n file_name = path.name\n log.debug('File name of cert - %r', file_name)\n not_valid_after = cert.not_valid_after\n log.debug('Ssl not valid after date - %r', str(not_valid_after))\n left = not_valid_after - datetime.utcnow()\n log.debug('Ssl cert valid days - %r', left.days)\n log.debug('Ssl cert serial number - %r', cert.serial_number)\n try:\n ext = cert.extensions.get_extension_for_oid(ExtensionOID.\n SUBJECT_ALTERNATIVE_NAME)\n dns_names_list = ext.value.get_values_for_type(x509.DNSName)\n except ExtensionNotFound:\n dns_names_list = ['noname']\n log.debug('DNS names of cert - %r', dns_names_list)\n for domain in dns_names_list:\n self.gauges['ssl_valid_days'].add_metric([domain, file_name,\n str(cert.serial_number)], int(left.days))\n\n\ndef main():\n basic_config(level=arguments.log_level.upper(), buffered=False,\n log_format=arguments.log_format)\n start_http_server(addr=arguments.host_address, port=arguments.port)\n collector = SslExporter(arguments.cert_paths)\n REGISTRY.register(collector)\n while True:\n time.sleep(1)\n\n\n<mask token>\n", "step-2": "<mask token>\nparser.add_argument('--host-address', type=str, default='0.0.0.0')\nparser.add_argument('--port', type=int, default='9001')\nparser.add_argument('--cert-paths', nargs='+', type=Path)\nparser.add_argument('--log-level', type=str, default='INFO')\nparser.add_argument('--log-format', type=str, default='color')\n<mask token>\n\n\nclass SslExporter(object):\n gauges = {}\n\n def __init__(self, cert_paths):\n self.cert_paths = cert_paths\n\n def collect(self):\n self.gauges['ssl_valid_days'] = GaugeMetricFamily('ssl_valid_days',\n 'Ssl cert valid days', value=None, labels=['domain',\n 'file_name', 'serial_number'])\n for path in self.cert_paths:\n if not path.exists():\n log.error('File %r does not exists', path)\n exit(1)\n self.get_metrics(path)\n for name, data in self.gauges.items():\n yield data\n\n def get_metrics(self, path: Path):\n with path.open('rb') as f:\n try:\n cert = x509.load_pem_x509_certificate(f.read(),\n default_backend())\n except ValueError:\n log.exception('Cannot read certificate - %r', path)\n return []\n file_name = path.name\n log.debug('File name of cert - %r', file_name)\n not_valid_after = cert.not_valid_after\n log.debug('Ssl not valid after date - %r', str(not_valid_after))\n left = not_valid_after - datetime.utcnow()\n log.debug('Ssl cert valid days - %r', left.days)\n log.debug('Ssl cert serial number - %r', cert.serial_number)\n try:\n ext = cert.extensions.get_extension_for_oid(ExtensionOID.\n SUBJECT_ALTERNATIVE_NAME)\n dns_names_list = ext.value.get_values_for_type(x509.DNSName)\n except ExtensionNotFound:\n dns_names_list = ['noname']\n log.debug('DNS names of cert - %r', dns_names_list)\n for domain in dns_names_list:\n self.gauges['ssl_valid_days'].add_metric([domain, file_name,\n str(cert.serial_number)], int(left.days))\n\n\ndef main():\n basic_config(level=arguments.log_level.upper(), buffered=False,\n log_format=arguments.log_format)\n start_http_server(addr=arguments.host_address, port=arguments.port)\n collector = SslExporter(arguments.cert_paths)\n REGISTRY.register(collector)\n while True:\n time.sleep(1)\n\n\nif __name__ == '__main__':\n main()\n", "step-3": "<mask token>\nparser = ArgumentParser(default_config_files=[os.path.join(\n '/etc/ssl-exporter.conf')], auto_env_var_prefix='APP_')\nparser.add_argument('--host-address', type=str, default='0.0.0.0')\nparser.add_argument('--port', type=int, default='9001')\nparser.add_argument('--cert-paths', nargs='+', type=Path)\nparser.add_argument('--log-level', type=str, default='INFO')\nparser.add_argument('--log-format', type=str, default='color')\narguments = parser.parse_args()\nlog = logging.getLogger()\n\n\nclass SslExporter(object):\n gauges = {}\n\n def __init__(self, cert_paths):\n self.cert_paths = cert_paths\n\n def collect(self):\n self.gauges['ssl_valid_days'] = GaugeMetricFamily('ssl_valid_days',\n 'Ssl cert valid days', value=None, labels=['domain',\n 'file_name', 'serial_number'])\n for path in self.cert_paths:\n if not path.exists():\n log.error('File %r does not exists', path)\n exit(1)\n self.get_metrics(path)\n for name, data in self.gauges.items():\n yield data\n\n def get_metrics(self, path: Path):\n with path.open('rb') as f:\n try:\n cert = x509.load_pem_x509_certificate(f.read(),\n default_backend())\n except ValueError:\n log.exception('Cannot read certificate - %r', path)\n return []\n file_name = path.name\n log.debug('File name of cert - %r', file_name)\n not_valid_after = cert.not_valid_after\n log.debug('Ssl not valid after date - %r', str(not_valid_after))\n left = not_valid_after - datetime.utcnow()\n log.debug('Ssl cert valid days - %r', left.days)\n log.debug('Ssl cert serial number - %r', cert.serial_number)\n try:\n ext = cert.extensions.get_extension_for_oid(ExtensionOID.\n SUBJECT_ALTERNATIVE_NAME)\n dns_names_list = ext.value.get_values_for_type(x509.DNSName)\n except ExtensionNotFound:\n dns_names_list = ['noname']\n log.debug('DNS names of cert - %r', dns_names_list)\n for domain in dns_names_list:\n self.gauges['ssl_valid_days'].add_metric([domain, file_name,\n str(cert.serial_number)], int(left.days))\n\n\ndef main():\n basic_config(level=arguments.log_level.upper(), buffered=False,\n log_format=arguments.log_format)\n start_http_server(addr=arguments.host_address, port=arguments.port)\n collector = SslExporter(arguments.cert_paths)\n REGISTRY.register(collector)\n while True:\n time.sleep(1)\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import logging\nimport os\nimport time\nfrom datetime import datetime\nfrom pathlib import Path\nfrom configargparse import ArgumentParser\nfrom cryptography import x509\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.x509.oid import ExtensionOID\nfrom cryptography.x509.extensions import ExtensionNotFound\nfrom prettylog import basic_config\nfrom prometheus_client import start_http_server\nfrom prometheus_client.core import GaugeMetricFamily, REGISTRY\nparser = ArgumentParser(default_config_files=[os.path.join(\n '/etc/ssl-exporter.conf')], auto_env_var_prefix='APP_')\nparser.add_argument('--host-address', type=str, default='0.0.0.0')\nparser.add_argument('--port', type=int, default='9001')\nparser.add_argument('--cert-paths', nargs='+', type=Path)\nparser.add_argument('--log-level', type=str, default='INFO')\nparser.add_argument('--log-format', type=str, default='color')\narguments = parser.parse_args()\nlog = logging.getLogger()\n\n\nclass SslExporter(object):\n gauges = {}\n\n def __init__(self, cert_paths):\n self.cert_paths = cert_paths\n\n def collect(self):\n self.gauges['ssl_valid_days'] = GaugeMetricFamily('ssl_valid_days',\n 'Ssl cert valid days', value=None, labels=['domain',\n 'file_name', 'serial_number'])\n for path in self.cert_paths:\n if not path.exists():\n log.error('File %r does not exists', path)\n exit(1)\n self.get_metrics(path)\n for name, data in self.gauges.items():\n yield data\n\n def get_metrics(self, path: Path):\n with path.open('rb') as f:\n try:\n cert = x509.load_pem_x509_certificate(f.read(),\n default_backend())\n except ValueError:\n log.exception('Cannot read certificate - %r', path)\n return []\n file_name = path.name\n log.debug('File name of cert - %r', file_name)\n not_valid_after = cert.not_valid_after\n log.debug('Ssl not valid after date - %r', str(not_valid_after))\n left = not_valid_after - datetime.utcnow()\n log.debug('Ssl cert valid days - %r', left.days)\n log.debug('Ssl cert serial number - %r', cert.serial_number)\n try:\n ext = cert.extensions.get_extension_for_oid(ExtensionOID.\n SUBJECT_ALTERNATIVE_NAME)\n dns_names_list = ext.value.get_values_for_type(x509.DNSName)\n except ExtensionNotFound:\n dns_names_list = ['noname']\n log.debug('DNS names of cert - %r', dns_names_list)\n for domain in dns_names_list:\n self.gauges['ssl_valid_days'].add_metric([domain, file_name,\n str(cert.serial_number)], int(left.days))\n\n\ndef main():\n basic_config(level=arguments.log_level.upper(), buffered=False,\n log_format=arguments.log_format)\n start_http_server(addr=arguments.host_address, port=arguments.port)\n collector = SslExporter(arguments.cert_paths)\n REGISTRY.register(collector)\n while True:\n time.sleep(1)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import logging\nimport os\nimport time\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom configargparse import ArgumentParser\nfrom cryptography import x509\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.x509.oid import ExtensionOID\nfrom cryptography.x509.extensions import ExtensionNotFound\nfrom prettylog import basic_config\nfrom prometheus_client import start_http_server\nfrom prometheus_client.core import GaugeMetricFamily, REGISTRY\n\nparser = ArgumentParser(\n default_config_files=[os.path.join(\"/etc/ssl-exporter.conf\")],\n auto_env_var_prefix=\"APP_\",\n)\n\nparser.add_argument(\"--host-address\", type=str, default=\"0.0.0.0\")\nparser.add_argument(\"--port\", type=int, default=\"9001\")\nparser.add_argument(\"--cert-paths\", nargs=\"+\", type=Path)\nparser.add_argument(\"--log-level\", type=str, default=\"INFO\")\nparser.add_argument(\"--log-format\", type=str, default=\"color\")\n\narguments = parser.parse_args()\n\nlog = logging.getLogger()\n\n\nclass SslExporter(object):\n gauges = {}\n\n def __init__(self, cert_paths):\n self.cert_paths = cert_paths\n\n def collect(self):\n\n self.gauges[\"ssl_valid_days\"] = GaugeMetricFamily(\n \"ssl_valid_days\",\n \"Ssl cert valid days\",\n value=None,\n labels=[\"domain\", \"file_name\", \"serial_number\"],\n )\n\n for path in self.cert_paths:\n if not path.exists():\n log.error(\"File %r does not exists\", path)\n exit(1)\n self.get_metrics(path)\n\n for name, data in self.gauges.items():\n yield data\n\n def get_metrics(self, path: Path):\n with path.open(\"rb\") as f:\n try:\n cert = x509.load_pem_x509_certificate(\n f.read(), default_backend()\n )\n except ValueError:\n log.exception(\"Cannot read certificate - %r\", path)\n return []\n file_name = path.name\n log.debug(\"File name of cert - %r\", file_name)\n\n not_valid_after = cert.not_valid_after\n log.debug(\"Ssl not valid after date - %r\", str(not_valid_after))\n\n left = not_valid_after - datetime.utcnow()\n log.debug(\"Ssl cert valid days - %r\", left.days)\n\n log.debug(\"Ssl cert serial number - %r\", cert.serial_number)\n\n try:\n ext = cert.extensions.get_extension_for_oid(\n ExtensionOID.SUBJECT_ALTERNATIVE_NAME\n )\n dns_names_list = ext.value.get_values_for_type(x509.DNSName)\n except ExtensionNotFound:\n dns_names_list = [\"noname\"]\n\n log.debug(\"DNS names of cert - %r\", dns_names_list)\n\n for domain in dns_names_list:\n self.gauges[\"ssl_valid_days\"].add_metric(\n [domain, file_name, str(cert.serial_number)], int(left.days)\n )\n\n\ndef main():\n basic_config(\n level=arguments.log_level.upper(),\n buffered=False,\n log_format=arguments.log_format,\n )\n\n start_http_server(addr=arguments.host_address, port=arguments.port)\n collector = SslExporter(arguments.cert_paths)\n REGISTRY.register(collector)\n while True:\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n main()\n", "step-ids": [ 6, 7, 8, 9, 10 ] }
[ 6, 7, 8, 9, 10 ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void findSubNode(Node root) { } public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] strings = br.readLine().split(" "); int n = Integer.parseInt(strings[0]); int root = Integer.parseInt(strings[1]); Node head1 = new Node(root); int[][] arr1 = new int[100 + 1][2]; for (int i = 0; i < n; i++) { strings = br.readLine().split(" "); arr1[Integer.parseInt(strings[0])][0] = Integer.parseInt(strings[1]); arr1[Integer.parseInt(strings[0])][1] = Integer.parseInt(strings[2]); } int t = Integer.parseInt(br.readLine()); if (arr1[t][0] == 0 && arr1[t][1] == 0){ System.out.println(0); } else if(arr1[t][0] != 0){ System.out.println(arr1[t][0] ); }else { System.out.println(arr1[t][1] ); } // createTree(head1, arr1); } public static void createTree(Node head, int[][] arr) { if (head == null) { return; } if (arr[head.value][0] != 0) { head.left = new Node(arr[head.value][0]); createTree(head.left, arr); } if (arr[head.value][1] != 0) { head.right = new Node(arr[head.value][1]); createTree(head.right, arr); } } }
normal
{ "blob_id": "6d0a945c9eaf6564a327928880df1f0aeed2e5d0", "index": 9649, "step-1": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class Main {\n\n public static void findSubNode(Node root) {\n\n }\n\n public static void main(String args[]) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n String[] strings = br.readLine().split(\" \");\n int n = Integer.parseInt(strings[0]);\n int root = Integer.parseInt(strings[1]);\n Node head1 = new Node(root);\n int[][] arr1 = new int[100 + 1][2];\n for (int i = 0; i < n; i++) {\n strings = br.readLine().split(\" \");\n arr1[Integer.parseInt(strings[0])][0] = Integer.parseInt(strings[1]);\n arr1[Integer.parseInt(strings[0])][1] = Integer.parseInt(strings[2]);\n }\n int t = Integer.parseInt(br.readLine());\n if (arr1[t][0] == 0 && arr1[t][1] == 0){\n System.out.println(0);\n } else if(arr1[t][0] != 0){\n System.out.println(arr1[t][0] );\n }else {\n System.out.println(arr1[t][1] );\n }\n// createTree(head1, arr1);\n }\n\n public static void createTree(Node head, int[][] arr) {\n if (head == null) {\n return;\n }\n if (arr[head.value][0] != 0) {\n head.left = new Node(arr[head.value][0]);\n createTree(head.left, arr);\n }\n if (arr[head.value][1] != 0) {\n head.right = new Node(arr[head.value][1]);\n createTree(head.right, arr);\n }\n }\n}\n\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def bigquery(datafile, dataset=os.environ['BQDATASET'], project=os.environ[ 'GCPPROJECT'], schema=[{'name': 'conversation', 'type': 'STRING'}, { 'name': 'id', 'type': 'INTEGER'}, {'name': 'from', 'type': 'STRING'}, { 'name': 'text', 'type': 'STRING'}, {'name': 'wordcount', 'type': 'INTEGER'}, {'name': 'reply_to_message_id', 'type': 'INTEGER'}, {'name': 'photo', 'type': 'STRING'}, {'name': 'wait_time', 'type': 'FLOAT'}]): log.info('creating bigquery dataset') src = data_generator(datafile) chatinfo = create_dataframe(src) ts = chatinfo.to_gbq('{}'.format(dataset), project_id='{}'.format( project), if_exists='replace', table_schema=schema) if ts: return True else: return False <|reserved_special_token_1|> import os from logzero import logger as log from extract import data_generator from transform import create_dataframe def bigquery(datafile, dataset=os.environ['BQDATASET'], project=os.environ[ 'GCPPROJECT'], schema=[{'name': 'conversation', 'type': 'STRING'}, { 'name': 'id', 'type': 'INTEGER'}, {'name': 'from', 'type': 'STRING'}, { 'name': 'text', 'type': 'STRING'}, {'name': 'wordcount', 'type': 'INTEGER'}, {'name': 'reply_to_message_id', 'type': 'INTEGER'}, {'name': 'photo', 'type': 'STRING'}, {'name': 'wait_time', 'type': 'FLOAT'}]): log.info('creating bigquery dataset') src = data_generator(datafile) chatinfo = create_dataframe(src) ts = chatinfo.to_gbq('{}'.format(dataset), project_id='{}'.format( project), if_exists='replace', table_schema=schema) if ts: return True else: return False <|reserved_special_token_1|> import os from logzero import logger as log from extract import data_generator from transform import create_dataframe def bigquery( datafile, dataset=os.environ["BQDATASET"], project=os.environ["GCPPROJECT"], schema=[ {"name": "conversation", "type": "STRING"}, {"name": "id", "type": "INTEGER"}, {"name": "from", "type": "STRING"}, {"name": "text", "type": "STRING"}, {"name": "wordcount", "type": "INTEGER"}, {"name": "reply_to_message_id", "type": "INTEGER"}, {"name": "photo", "type": "STRING"}, {"name": "wait_time", "type": "FLOAT"}, ], ): log.info("creating bigquery dataset") src = data_generator(datafile) chatinfo = create_dataframe(src) ts = chatinfo.to_gbq( "{}".format(dataset), project_id="{}".format(project), if_exists="replace", table_schema=schema, ) if ts: return True else: return False
flexible
{ "blob_id": "d6046217308745b85455aed78734700b9622782c", "index": 7559, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef bigquery(datafile, dataset=os.environ['BQDATASET'], project=os.environ[\n 'GCPPROJECT'], schema=[{'name': 'conversation', 'type': 'STRING'}, {\n 'name': 'id', 'type': 'INTEGER'}, {'name': 'from', 'type': 'STRING'}, {\n 'name': 'text', 'type': 'STRING'}, {'name': 'wordcount', 'type':\n 'INTEGER'}, {'name': 'reply_to_message_id', 'type': 'INTEGER'}, {'name':\n 'photo', 'type': 'STRING'}, {'name': 'wait_time', 'type': 'FLOAT'}]):\n log.info('creating bigquery dataset')\n src = data_generator(datafile)\n chatinfo = create_dataframe(src)\n ts = chatinfo.to_gbq('{}'.format(dataset), project_id='{}'.format(\n project), if_exists='replace', table_schema=schema)\n if ts:\n return True\n else:\n return False\n", "step-3": "import os\nfrom logzero import logger as log\nfrom extract import data_generator\nfrom transform import create_dataframe\n\n\ndef bigquery(datafile, dataset=os.environ['BQDATASET'], project=os.environ[\n 'GCPPROJECT'], schema=[{'name': 'conversation', 'type': 'STRING'}, {\n 'name': 'id', 'type': 'INTEGER'}, {'name': 'from', 'type': 'STRING'}, {\n 'name': 'text', 'type': 'STRING'}, {'name': 'wordcount', 'type':\n 'INTEGER'}, {'name': 'reply_to_message_id', 'type': 'INTEGER'}, {'name':\n 'photo', 'type': 'STRING'}, {'name': 'wait_time', 'type': 'FLOAT'}]):\n log.info('creating bigquery dataset')\n src = data_generator(datafile)\n chatinfo = create_dataframe(src)\n ts = chatinfo.to_gbq('{}'.format(dataset), project_id='{}'.format(\n project), if_exists='replace', table_schema=schema)\n if ts:\n return True\n else:\n return False\n", "step-4": "import os\nfrom logzero import logger as log\nfrom extract import data_generator\n\nfrom transform import create_dataframe\n\n\ndef bigquery(\n datafile,\n dataset=os.environ[\"BQDATASET\"],\n project=os.environ[\"GCPPROJECT\"],\n schema=[\n {\"name\": \"conversation\", \"type\": \"STRING\"},\n {\"name\": \"id\", \"type\": \"INTEGER\"},\n {\"name\": \"from\", \"type\": \"STRING\"},\n {\"name\": \"text\", \"type\": \"STRING\"},\n {\"name\": \"wordcount\", \"type\": \"INTEGER\"},\n {\"name\": \"reply_to_message_id\", \"type\": \"INTEGER\"},\n {\"name\": \"photo\", \"type\": \"STRING\"},\n {\"name\": \"wait_time\", \"type\": \"FLOAT\"},\n ],\n):\n\n log.info(\"creating bigquery dataset\")\n src = data_generator(datafile)\n chatinfo = create_dataframe(src)\n ts = chatinfo.to_gbq(\n \"{}\".format(dataset),\n project_id=\"{}\".format(project),\n if_exists=\"replace\",\n table_schema=schema,\n )\n if ts:\n return True\n else:\n return False\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import numpy as np import cv2 from PIL import Image import pytesseract as tess #Function to check the area range and width-height ratio def ratio(area, width,height): ratio = float(width)/float(height) if ratio < 1: ratio = 1/ ratio if (area<1063.62 or area> 73862.5) or (ratio<3 or ratio> 6): return False return True #Average of image matrix def max_White(plates): avg= np.mean(plates) if(avg >= 115): return True else: return False
normal
{ "blob_id": "ab610af97d2b31575ea496b8fddda693353da8eb", "index": 2870, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef ratio(area, width, height):\n ratio = float(width) / float(height)\n if ratio < 1:\n ratio = 1 / ratio\n if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):\n return False\n return True\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef ratio(area, width, height):\n ratio = float(width) / float(height)\n if ratio < 1:\n ratio = 1 / ratio\n if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):\n return False\n return True\n\n\ndef max_White(plates):\n avg = np.mean(plates)\n if avg >= 115:\n return True\n else:\n return False\n", "step-4": "import numpy as np\nimport cv2\nfrom PIL import Image\nimport pytesseract as tess\n\n\ndef ratio(area, width, height):\n ratio = float(width) / float(height)\n if ratio < 1:\n ratio = 1 / ratio\n if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):\n return False\n return True\n\n\ndef max_White(plates):\n avg = np.mean(plates)\n if avg >= 115:\n return True\n else:\n return False\n", "step-5": "import numpy as np \nimport cv2\nfrom PIL import Image\nimport pytesseract as tess \n\n\n\n#Function to check the area range and width-height ratio\n\ndef ratio(area, width,height):\n\tratio = float(width)/float(height)\n\tif ratio < 1:\n\t\tratio = 1/ ratio\n\tif (area<1063.62 or area> 73862.5) or (ratio<3 or ratio> 6):\n\t\treturn False\n\treturn True\n\n#Average of image matrix\n\ndef max_White(plates):\n\n\tavg= np.mean(plates)\n\tif(avg >= 115):\n\t\treturn True\n\telse:\n\t\treturn False\n\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TestSTCHANGE: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TestSTCHANGE: def setup_method(self, method): self.driver = webdriver.Chrome() self.vars = {} def teardown_method(self, method): self.driver.quit() def test_sTCHANGE(self): self.driver.get('http://10.51.30.52:8090/main/desktop-login.html') self.driver.set_window_size(976, 696) self.driver.find_element(By.ID, 'idInputUsername').click() self.driver.find_element(By.ID, 'idInputUsername').send_keys( 'SUPERVISOR') self.driver.find_element(By.ID, 'login-panel').click() self.driver.find_element(By.ID, 'idInputPassword').click() self.driver.find_element(By.ID, 'idInputPassword').send_keys('**') self.driver.find_element(By.ID, 'submit.button').click() self.driver.find_element(By.ID, 'BVMAPS').click() self.driver.find_element(By.CSS_SELECTOR, '#UI_BADGES_GRID\\.gridView\\.row\\#22_Tcell\\#0 > div > div' ).click() self.driver.find_element(By.ID, 'badge.html.ribbon.properties').click() self.driver.find_element(By.ID, '__selection_4').click() element = self.driver.find_element(By.CSS_SELECTOR, '#\\__pan_4 > .listItemNormal:nth-child(2)') actions = ActionChains(self.driver) actions.move_to_element(element).click_and_hold().perform() element = self.driver.find_element(By.ID, '__selection_5') actions = ActionChains(self.driver) actions.move_to_element(element).release().perform() self.driver.find_element(By.CSS_SELECTOR, '#PROPERTIES_CONTROLS td:nth-child(2) .middlePart').click() self.driver.find_element(By.ID, 'badge.html.ribbon.properties.apply' ).click() self.driver.find_element(By.CSS_SELECTOR, 'body > img').click() self.driver.find_element(By.CSS_SELECTOR, 'a > img').click() self.driver.find_element(By.ID, 'main.html.btn_logout').click() <|reserved_special_token_1|> import pytest import time import json from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class TestSTCHANGE: def setup_method(self, method): self.driver = webdriver.Chrome() self.vars = {} def teardown_method(self, method): self.driver.quit() def test_sTCHANGE(self): self.driver.get('http://10.51.30.52:8090/main/desktop-login.html') self.driver.set_window_size(976, 696) self.driver.find_element(By.ID, 'idInputUsername').click() self.driver.find_element(By.ID, 'idInputUsername').send_keys( 'SUPERVISOR') self.driver.find_element(By.ID, 'login-panel').click() self.driver.find_element(By.ID, 'idInputPassword').click() self.driver.find_element(By.ID, 'idInputPassword').send_keys('**') self.driver.find_element(By.ID, 'submit.button').click() self.driver.find_element(By.ID, 'BVMAPS').click() self.driver.find_element(By.CSS_SELECTOR, '#UI_BADGES_GRID\\.gridView\\.row\\#22_Tcell\\#0 > div > div' ).click() self.driver.find_element(By.ID, 'badge.html.ribbon.properties').click() self.driver.find_element(By.ID, '__selection_4').click() element = self.driver.find_element(By.CSS_SELECTOR, '#\\__pan_4 > .listItemNormal:nth-child(2)') actions = ActionChains(self.driver) actions.move_to_element(element).click_and_hold().perform() element = self.driver.find_element(By.ID, '__selection_5') actions = ActionChains(self.driver) actions.move_to_element(element).release().perform() self.driver.find_element(By.CSS_SELECTOR, '#PROPERTIES_CONTROLS td:nth-child(2) .middlePart').click() self.driver.find_element(By.ID, 'badge.html.ribbon.properties.apply' ).click() self.driver.find_element(By.CSS_SELECTOR, 'body > img').click() self.driver.find_element(By.CSS_SELECTOR, 'a > img').click() self.driver.find_element(By.ID, 'main.html.btn_logout').click() <|reserved_special_token_1|> # Generated by Selenium IDE import pytest import time import json from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class TestSTCHANGE(): def setup_method(self, method): self.driver = webdriver.Chrome() self.vars = {} def teardown_method(self, method): self.driver.quit() def test_sTCHANGE(self): # Test name: ST CHANGE # Step # | name | target | value # 1 | open | /main/desktop-login.html | self.driver.get("http://10.51.30.52:8090/main/desktop-login.html") # 2 | setWindowSize | 976x696 | self.driver.set_window_size(976, 696) # 3 | click | id=idInputUsername | self.driver.find_element(By.ID, "idInputUsername").click() # 4 | type | id=idInputUsername | SUPERVISOR self.driver.find_element(By.ID, "idInputUsername").send_keys("SUPERVISOR") # 5 | click | id=login-panel | self.driver.find_element(By.ID, "login-panel").click() # 6 | click | id=idInputPassword | self.driver.find_element(By.ID, "idInputPassword").click() # 7 | type | id=idInputPassword | ** self.driver.find_element(By.ID, "idInputPassword").send_keys("**") # 8 | click | id=submit.button | self.driver.find_element(By.ID, "submit.button").click() # 9 | click | id=BVMAPS | self.driver.find_element(By.ID, "BVMAPS").click() # 10 | click | css=#UI_BADGES_GRID\.gridView\.row\#22_Tcell\#0 > div > div | self.driver.find_element(By.CSS_SELECTOR, "#UI_BADGES_GRID\\.gridView\\.row\\#22_Tcell\\#0 > div > div").click() # 11 | click | id=badge.html.ribbon.properties | self.driver.find_element(By.ID, "badge.html.ribbon.properties").click() # 12 | click | id=__selection_4 | self.driver.find_element(By.ID, "__selection_4").click() # 13 | mouseDown | css=#\__pan_4 > .listItemNormal:nth-child(2) | element = self.driver.find_element(By.CSS_SELECTOR, "#\\__pan_4 > .listItemNormal:nth-child(2)") actions = ActionChains(self.driver) actions.move_to_element(element).click_and_hold().perform() # 14 | mouseUp | id=__selection_5 | element = self.driver.find_element(By.ID, "__selection_5") actions = ActionChains(self.driver) actions.move_to_element(element).release().perform() # 15 | click | css=#PROPERTIES_CONTROLS td:nth-child(2) .middlePart | self.driver.find_element(By.CSS_SELECTOR, "#PROPERTIES_CONTROLS td:nth-child(2) .middlePart").click() # 16 | click | id=badge.html.ribbon.properties.apply | self.driver.find_element(By.ID, "badge.html.ribbon.properties.apply").click() # 17 | click | css=body > img | self.driver.find_element(By.CSS_SELECTOR, "body > img").click() # 18 | click | css=a > img | self.driver.find_element(By.CSS_SELECTOR, "a > img").click() # 19 | click | id=main.html.btn_logout | self.driver.find_element(By.ID, "main.html.btn_logout").click()
flexible
{ "blob_id": "87f8cc65cf7d0ea932de79a6daf5b29ad387ec6f", "index": 7103, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass TestSTCHANGE:\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TestSTCHANGE:\n\n def setup_method(self, method):\n self.driver = webdriver.Chrome()\n self.vars = {}\n\n def teardown_method(self, method):\n self.driver.quit()\n\n def test_sTCHANGE(self):\n self.driver.get('http://10.51.30.52:8090/main/desktop-login.html')\n self.driver.set_window_size(976, 696)\n self.driver.find_element(By.ID, 'idInputUsername').click()\n self.driver.find_element(By.ID, 'idInputUsername').send_keys(\n 'SUPERVISOR')\n self.driver.find_element(By.ID, 'login-panel').click()\n self.driver.find_element(By.ID, 'idInputPassword').click()\n self.driver.find_element(By.ID, 'idInputPassword').send_keys('**')\n self.driver.find_element(By.ID, 'submit.button').click()\n self.driver.find_element(By.ID, 'BVMAPS').click()\n self.driver.find_element(By.CSS_SELECTOR,\n '#UI_BADGES_GRID\\\\.gridView\\\\.row\\\\#22_Tcell\\\\#0 > div > div'\n ).click()\n self.driver.find_element(By.ID, 'badge.html.ribbon.properties').click()\n self.driver.find_element(By.ID, '__selection_4').click()\n element = self.driver.find_element(By.CSS_SELECTOR,\n '#\\\\__pan_4 > .listItemNormal:nth-child(2)')\n actions = ActionChains(self.driver)\n actions.move_to_element(element).click_and_hold().perform()\n element = self.driver.find_element(By.ID, '__selection_5')\n actions = ActionChains(self.driver)\n actions.move_to_element(element).release().perform()\n self.driver.find_element(By.CSS_SELECTOR,\n '#PROPERTIES_CONTROLS td:nth-child(2) .middlePart').click()\n self.driver.find_element(By.ID, 'badge.html.ribbon.properties.apply'\n ).click()\n self.driver.find_element(By.CSS_SELECTOR, 'body > img').click()\n self.driver.find_element(By.CSS_SELECTOR, 'a > img').click()\n self.driver.find_element(By.ID, 'main.html.btn_logout').click()\n", "step-4": "import pytest\nimport time\nimport json\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\n\nclass TestSTCHANGE:\n\n def setup_method(self, method):\n self.driver = webdriver.Chrome()\n self.vars = {}\n\n def teardown_method(self, method):\n self.driver.quit()\n\n def test_sTCHANGE(self):\n self.driver.get('http://10.51.30.52:8090/main/desktop-login.html')\n self.driver.set_window_size(976, 696)\n self.driver.find_element(By.ID, 'idInputUsername').click()\n self.driver.find_element(By.ID, 'idInputUsername').send_keys(\n 'SUPERVISOR')\n self.driver.find_element(By.ID, 'login-panel').click()\n self.driver.find_element(By.ID, 'idInputPassword').click()\n self.driver.find_element(By.ID, 'idInputPassword').send_keys('**')\n self.driver.find_element(By.ID, 'submit.button').click()\n self.driver.find_element(By.ID, 'BVMAPS').click()\n self.driver.find_element(By.CSS_SELECTOR,\n '#UI_BADGES_GRID\\\\.gridView\\\\.row\\\\#22_Tcell\\\\#0 > div > div'\n ).click()\n self.driver.find_element(By.ID, 'badge.html.ribbon.properties').click()\n self.driver.find_element(By.ID, '__selection_4').click()\n element = self.driver.find_element(By.CSS_SELECTOR,\n '#\\\\__pan_4 > .listItemNormal:nth-child(2)')\n actions = ActionChains(self.driver)\n actions.move_to_element(element).click_and_hold().perform()\n element = self.driver.find_element(By.ID, '__selection_5')\n actions = ActionChains(self.driver)\n actions.move_to_element(element).release().perform()\n self.driver.find_element(By.CSS_SELECTOR,\n '#PROPERTIES_CONTROLS td:nth-child(2) .middlePart').click()\n self.driver.find_element(By.ID, 'badge.html.ribbon.properties.apply'\n ).click()\n self.driver.find_element(By.CSS_SELECTOR, 'body > img').click()\n self.driver.find_element(By.CSS_SELECTOR, 'a > img').click()\n self.driver.find_element(By.ID, 'main.html.btn_logout').click()\n", "step-5": "# Generated by Selenium IDE\nimport pytest\nimport time\nimport json\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\n\nclass TestSTCHANGE():\n def setup_method(self, method):\n self.driver = webdriver.Chrome()\n self.vars = {}\n\n def teardown_method(self, method):\n self.driver.quit()\n\n def test_sTCHANGE(self):\n # Test name: ST CHANGE\n # Step # | name | target | value\n # 1 | open | /main/desktop-login.html |\n self.driver.get(\"http://10.51.30.52:8090/main/desktop-login.html\")\n # 2 | setWindowSize | 976x696 |\n self.driver.set_window_size(976, 696)\n # 3 | click | id=idInputUsername |\n self.driver.find_element(By.ID, \"idInputUsername\").click()\n # 4 | type | id=idInputUsername | SUPERVISOR\n self.driver.find_element(By.ID, \"idInputUsername\").send_keys(\"SUPERVISOR\")\n # 5 | click | id=login-panel |\n self.driver.find_element(By.ID, \"login-panel\").click()\n # 6 | click | id=idInputPassword |\n self.driver.find_element(By.ID, \"idInputPassword\").click()\n # 7 | type | id=idInputPassword | **\n self.driver.find_element(By.ID, \"idInputPassword\").send_keys(\"**\")\n # 8 | click | id=submit.button |\n self.driver.find_element(By.ID, \"submit.button\").click()\n # 9 | click | id=BVMAPS |\n self.driver.find_element(By.ID, \"BVMAPS\").click()\n # 10 | click | css=#UI_BADGES_GRID\\.gridView\\.row\\#22_Tcell\\#0 > div > div |\n self.driver.find_element(By.CSS_SELECTOR, \"#UI_BADGES_GRID\\\\.gridView\\\\.row\\\\#22_Tcell\\\\#0 > div > div\").click()\n # 11 | click | id=badge.html.ribbon.properties |\n self.driver.find_element(By.ID, \"badge.html.ribbon.properties\").click()\n # 12 | click | id=__selection_4 |\n self.driver.find_element(By.ID, \"__selection_4\").click()\n # 13 | mouseDown | css=#\\__pan_4 > .listItemNormal:nth-child(2) |\n element = self.driver.find_element(By.CSS_SELECTOR, \"#\\\\__pan_4 > .listItemNormal:nth-child(2)\")\n actions = ActionChains(self.driver)\n actions.move_to_element(element).click_and_hold().perform()\n # 14 | mouseUp | id=__selection_5 |\n element = self.driver.find_element(By.ID, \"__selection_5\")\n actions = ActionChains(self.driver)\n actions.move_to_element(element).release().perform()\n # 15 | click | css=#PROPERTIES_CONTROLS td:nth-child(2) .middlePart |\n self.driver.find_element(By.CSS_SELECTOR, \"#PROPERTIES_CONTROLS td:nth-child(2) .middlePart\").click()\n # 16 | click | id=badge.html.ribbon.properties.apply |\n self.driver.find_element(By.ID, \"badge.html.ribbon.properties.apply\").click()\n # 17 | click | css=body > img |\n self.driver.find_element(By.CSS_SELECTOR, \"body > img\").click()\n # 18 | click | css=a > img |\n self.driver.find_element(By.CSS_SELECTOR, \"a > img\").click()\n # 19 | click | id=main.html.btn_logout |\n self.driver.find_element(By.ID, \"main.html.btn_logout\").click()\n", "step-ids": [ 0, 1, 4, 5, 6 ] }
[ 0, 1, 4, 5, 6 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def fetchsquare(request, id): try: therm = Therm.objects.get(id=id) except Therm.DoesNotExist: raise Http404('This item does not exist') return render(request, 'thermometer/fetchsquare.html', {'therm': therm}) <|reserved_special_token_1|> <|reserved_special_token_0|> def index(request): therms = Therm.objects.all() return render(request, 'thermometer/index.html', {'therms': therms}) def fetchsquare(request, id): try: therm = Therm.objects.get(id=id) except Therm.DoesNotExist: raise Http404('This item does not exist') return render(request, 'thermometer/fetchsquare.html', {'therm': therm}) <|reserved_special_token_1|> from django.shortcuts import render from django.http import Http404 from thermometer.models import Therm def index(request): therms = Therm.objects.all() return render(request, 'thermometer/index.html', {'therms': therms}) def fetchsquare(request, id): try: therm = Therm.objects.get(id=id) except Therm.DoesNotExist: raise Http404('This item does not exist') return render(request, 'thermometer/fetchsquare.html', {'therm': therm}) <|reserved_special_token_1|> from django.shortcuts import render from django.http import Http404 from thermometer.models import Therm def index(request): therms = Therm.objects.all() return render(request, 'thermometer/index.html', { 'therms': therms, }) def fetchsquare(request, id): try: therm = Therm.objects.get(id=id) except Therm.DoesNotExist: raise Http404('This item does not exist') return render(request, 'thermometer/fetchsquare.html', { 'therm': therm, })
flexible
{ "blob_id": "504d4afc4b3e708d43110a2d85676fb745f1aba8", "index": 9874, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef fetchsquare(request, id):\n try:\n therm = Therm.objects.get(id=id)\n except Therm.DoesNotExist:\n raise Http404('This item does not exist')\n return render(request, 'thermometer/fetchsquare.html', {'therm': therm})\n", "step-3": "<mask token>\n\n\ndef index(request):\n therms = Therm.objects.all()\n return render(request, 'thermometer/index.html', {'therms': therms})\n\n\ndef fetchsquare(request, id):\n try:\n therm = Therm.objects.get(id=id)\n except Therm.DoesNotExist:\n raise Http404('This item does not exist')\n return render(request, 'thermometer/fetchsquare.html', {'therm': therm})\n", "step-4": "from django.shortcuts import render\nfrom django.http import Http404\nfrom thermometer.models import Therm\n\n\ndef index(request):\n therms = Therm.objects.all()\n return render(request, 'thermometer/index.html', {'therms': therms})\n\n\ndef fetchsquare(request, id):\n try:\n therm = Therm.objects.get(id=id)\n except Therm.DoesNotExist:\n raise Http404('This item does not exist')\n return render(request, 'thermometer/fetchsquare.html', {'therm': therm})\n", "step-5": "from django.shortcuts import render\nfrom django.http import Http404\n\nfrom thermometer.models import Therm\n\ndef index(request):\n\ttherms = Therm.objects.all()\n\treturn render(request, 'thermometer/index.html', {\n\t\t'therms': therms,\n\t})\n\ndef fetchsquare(request, id):\n\ttry:\n\t\ttherm = Therm.objects.get(id=id)\n\texcept Therm.DoesNotExist:\n\t\traise Http404('This item does not exist')\n\treturn render(request, 'thermometer/fetchsquare.html', {\n\t\t'therm': therm,\n\t})", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Copyright 2011 Isaku Yamahata # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Tests for Block Device utility functions. """ from unittest import mock from oslo_utils.fixture import uuidsentinel as uuids from oslo_utils import units from nova import block_device from nova.compute import api as compute_api from nova import context from nova import exception from nova import objects from nova import test from nova.tests.unit import fake_block_device from nova.tests.unit import matchers from nova.volume import cinder class BlockDeviceTestCase(test.NoDBTestCase): def setUp(self): super(BlockDeviceTestCase, self).setUp() BDM = block_device.BlockDeviceDict self.new_mapping = [ BDM({'id': 1, 'instance_uuid': uuids.instance, 'device_name': '/dev/sdb1', 'source_type': 'blank', 'destination_type': 'local', 'delete_on_termination': True, 'volume_size': 1, 'guest_format': 'swap', 'boot_index': -1}), BDM({'id': 2, 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1', 'source_type': 'blank', 'destination_type': 'local', 'volume_size': 10, 'delete_on_termination': True, 'boot_index': -1}), BDM({'id': 3, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'fake-volume-id-1', 'connection_info': "{'fake': 'connection_info'}", 'boot_index': 0}), BDM({'id': 4, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda2', 'source_type': 'snapshot', 'destination_type': 'volume', 'connection_info': "{'fake': 'connection_info'}", 'snapshot_id': 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2', 'boot_index': -1}), BDM({'id': 5, 'instance_uuid': uuids.instance, 'no_device': True, 'device_name': '/dev/vdc'}), ] def test_properties(self): root_device0 = '/dev/sda' root_device1 = '/dev/sdb' mappings = [{'virtual': 'root', 'device': root_device0}] properties0 = {'mappings': mappings} properties1 = {'mappings': mappings, 'root_device_name': root_device1} self.assertIsNone(block_device.properties_root_device_name({})) self.assertEqual(root_device0, block_device.properties_root_device_name(properties0)) self.assertEqual(root_device1, block_device.properties_root_device_name(properties1)) def test_ephemeral(self): self.assertFalse(block_device.is_ephemeral('ephemeral')) self.assertTrue(block_device.is_ephemeral('ephemeral0')) self.assertTrue(block_device.is_ephemeral('ephemeral1')) self.assertTrue(block_device.is_ephemeral('ephemeral11')) self.assertFalse(block_device.is_ephemeral('root')) self.assertFalse(block_device.is_ephemeral('swap')) self.assertFalse(block_device.is_ephemeral('/dev/sda1')) self.assertEqual(0, block_device.ephemeral_num('ephemeral0')) self.assertEqual(1, block_device.ephemeral_num('ephemeral1')) self.assertEqual(11, block_device.ephemeral_num('ephemeral11')) self.assertFalse(block_device.is_swap_or_ephemeral('ephemeral')) self.assertTrue(block_device.is_swap_or_ephemeral('ephemeral0')) self.assertTrue(block_device.is_swap_or_ephemeral('ephemeral1')) self.assertTrue(block_device.is_swap_or_ephemeral('swap')) self.assertFalse(block_device.is_swap_or_ephemeral('root')) self.assertFalse(block_device.is_swap_or_ephemeral('/dev/sda1')) def test_mappings_prepend_dev(self): mapping = [ {'virtual': 'ami', 'device': '/dev/sda'}, {'virtual': 'root', 'device': 'sda'}, {'virtual': 'ephemeral0', 'device': 'sdb'}, {'virtual': 'swap', 'device': 'sdc'}, {'virtual': 'ephemeral1', 'device': 'sdd'}, {'virtual': 'ephemeral2', 'device': 'sde'}] expected = [ {'virtual': 'ami', 'device': '/dev/sda'}, {'virtual': 'root', 'device': 'sda'}, {'virtual': 'ephemeral0', 'device': '/dev/sdb'}, {'virtual': 'swap', 'device': '/dev/sdc'}, {'virtual': 'ephemeral1', 'device': '/dev/sdd'}, {'virtual': 'ephemeral2', 'device': '/dev/sde'}] prepended = block_device.mappings_prepend_dev(mapping) self.assertEqual(sorted(expected, key=lambda v: v['virtual']), sorted(prepended, key=lambda v: v['virtual'])) def test_strip_dev(self): self.assertEqual('sda', block_device.strip_dev('/dev/sda')) self.assertEqual('sda', block_device.strip_dev('sda')) self.assertIsNone(block_device.strip_dev(None)) def test_strip_prefix(self): self.assertEqual('a', block_device.strip_prefix('/dev/sda')) self.assertEqual('a', block_device.strip_prefix('a')) self.assertEqual('a', block_device.strip_prefix('xvda')) self.assertEqual('a', block_device.strip_prefix('vda')) self.assertEqual('a', block_device.strip_prefix('hda')) self.assertIsNone(block_device.strip_prefix(None)) def test_get_device_letter(self): self.assertEqual('', block_device.get_device_letter('')) self.assertEqual('a', block_device.get_device_letter('/dev/sda1')) self.assertEqual('b', block_device.get_device_letter('/dev/xvdb')) self.assertEqual('d', block_device.get_device_letter('/dev/d')) self.assertEqual('a', block_device.get_device_letter('a')) self.assertEqual('b', block_device.get_device_letter('sdb2')) self.assertEqual('c', block_device.get_device_letter('vdc')) self.assertEqual('c', block_device.get_device_letter('hdc')) self.assertIsNone(block_device.get_device_letter(None)) def test_generate_device_name(self): expected = ( ('vda', ("vd", 0)), ('vdaa', ("vd", 26)), ('vdabc', ("vd", 730)), ('vdidpok', ("vd", 4194304)), ('sdc', ("sd", 2)), ('sdaa', ("sd", 26)), ('sdiw', ("sd", 256)), ('hdzz', ("hd", 701)) ) for res, args in expected: self.assertEqual(res, block_device.generate_device_name(*args)) def test_volume_in_mapping(self): swap = {'device_name': '/dev/sdb', 'swap_size': 1} ephemerals = [{'num': 0, 'virtual_name': 'ephemeral0', 'device_name': '/dev/sdc1', 'size': 1}, {'num': 2, 'virtual_name': 'ephemeral2', 'device_name': '/dev/sdd', 'size': 1}] block_device_mapping = [{'mount_device': '/dev/sde', 'device_path': 'fake_device'}, {'mount_device': '/dev/sdf', 'device_path': 'fake_device'}] block_device_info = { 'root_device_name': '/dev/sda', 'swap': swap, 'ephemerals': ephemerals, 'block_device_mapping': block_device_mapping} def _assert_volume_in_mapping(device_name, true_or_false): in_mapping = block_device.volume_in_mapping( device_name, block_device_info) self.assertEqual(true_or_false, in_mapping) _assert_volume_in_mapping('sda', False) _assert_volume_in_mapping('sdb', True) _assert_volume_in_mapping('sdc1', True) _assert_volume_in_mapping('sdd', True) _assert_volume_in_mapping('sde', True) _assert_volume_in_mapping('sdf', True) _assert_volume_in_mapping('sdg', False) _assert_volume_in_mapping('sdh1', False) def test_get_root_bdm(self): root_bdm = {'device_name': 'vda', 'boot_index': 0} bdms = [root_bdm, {'device_name': 'vdb', 'boot_index': 1}, {'device_name': 'vdc', 'boot_index': -1}, {'device_name': 'vdd'}] self.assertEqual(root_bdm, block_device.get_root_bdm(bdms)) self.assertEqual(root_bdm, block_device.get_root_bdm([bdms[0]])) self.assertIsNone(block_device.get_root_bdm(bdms[1:])) self.assertIsNone(block_device.get_root_bdm(bdms[2:])) self.assertIsNone(block_device.get_root_bdm(bdms[3:])) self.assertIsNone(block_device.get_root_bdm([])) def test_get_bdm_ephemeral_disk_size(self): size = block_device.get_bdm_ephemeral_disk_size(self.new_mapping) self.assertEqual(10, size) def test_get_bdm_swap_list(self): swap_list = block_device.get_bdm_swap_list(self.new_mapping) self.assertEqual(1, len(swap_list)) self.assertEqual(1, swap_list[0].get('id')) def test_get_bdm_local_disk_num(self): size = block_device.get_bdm_local_disk_num(self.new_mapping) self.assertEqual(2, size) def test_new_format_is_swap(self): expected_results = [True, False, False, False, False] for expected, bdm in zip(expected_results, self.new_mapping): res = block_device.new_format_is_swap(bdm) self.assertEqual(expected, res) def test_new_format_is_ephemeral(self): expected_results = [False, True, False, False, False] for expected, bdm in zip(expected_results, self.new_mapping): res = block_device.new_format_is_ephemeral(bdm) self.assertEqual(expected, res) def test_validate_device_name(self): for value in [' ', 10, None, 'a' * 260]: self.assertRaises(exception.InvalidBDMFormat, block_device.validate_device_name, value) def test_validate_and_default_volume_size(self): bdm = {} for value in [-1, 'a', 2.5]: bdm['volume_size'] = value self.assertRaises(exception.InvalidBDMFormat, block_device.validate_and_default_volume_size, bdm) def test_get_bdms_to_connect(self): root_bdm = {'device_name': 'vda', 'boot_index': 0} bdms = [root_bdm, {'device_name': 'vdb', 'boot_index': 1}, {'device_name': 'vdc', 'boot_index': -1}, {'device_name': 'vde', 'boot_index': None}, {'device_name': 'vdd'}] self.assertNotIn(root_bdm, block_device.get_bdms_to_connect(bdms, exclude_root_mapping=True)) self.assertIn(root_bdm, block_device.get_bdms_to_connect(bdms)) class TestBlockDeviceDict(test.NoDBTestCase): def setUp(self): super(TestBlockDeviceDict, self).setUp() BDM = block_device.BlockDeviceDict self.api_mapping = [ {'id': 1, 'instance_uuid': uuids.instance, 'device_name': '/dev/sdb1', 'source_type': 'blank', 'destination_type': 'local', 'delete_on_termination': True, 'guest_format': 'swap', 'boot_index': -1}, {'id': 2, 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1', 'source_type': 'blank', 'destination_type': 'local', 'delete_on_termination': True, 'boot_index': -1}, {'id': 3, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1', 'source_type': 'volume', 'destination_type': 'volume', 'uuid': 'fake-volume-id-1', 'boot_index': 0}, {'id': 4, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda2', 'source_type': 'snapshot', 'destination_type': 'volume', 'uuid': 'fake-snapshot-id-1', 'boot_index': -1}, {'id': 5, 'instance_uuid': uuids.instance, 'no_device': True, 'device_name': '/dev/vdc'}, ] self.new_mapping = [ BDM({'id': 1, 'instance_uuid': uuids.instance, 'device_name': '/dev/sdb1', 'source_type': 'blank', 'destination_type': 'local', 'delete_on_termination': True, 'guest_format': 'swap', 'boot_index': -1}), BDM({'id': 2, 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1', 'source_type': 'blank', 'destination_type': 'local', 'delete_on_termination': True, 'boot_index': -1}), BDM({'id': 3, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'fake-volume-id-1', 'connection_info': "{'fake': 'connection_info'}", 'boot_index': 0}), BDM({'id': 4, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda2', 'source_type': 'snapshot', 'destination_type': 'volume', 'connection_info': "{'fake': 'connection_info'}", 'snapshot_id': 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2', 'boot_index': -1}), BDM({'id': 5, 'instance_uuid': uuids.instance, 'no_device': True, 'device_name': '/dev/vdc'}), ] self.legacy_mapping = [ {'id': 1, 'instance_uuid': uuids.instance, 'device_name': '/dev/sdb1', 'delete_on_termination': True, 'virtual_name': 'swap'}, {'id': 2, 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1', 'delete_on_termination': True, 'virtual_name': 'ephemeral0'}, {'id': 3, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1', 'volume_id': 'fake-volume-id-1', 'connection_info': "{'fake': 'connection_info'}"}, {'id': 4, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda2', 'connection_info': "{'fake': 'connection_info'}", 'snapshot_id': 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2'}, {'id': 5, 'instance_uuid': uuids.instance, 'no_device': True, 'device_name': '/dev/vdc'}, ] self.new_mapping_source_image = [ BDM({'id': 6, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda3', 'source_type': 'image', 'destination_type': 'volume', 'connection_info': "{'fake': 'connection_info'}", 'volume_id': 'fake-volume-id-3', 'boot_index': -1}), BDM({'id': 7, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda4', 'source_type': 'image', 'destination_type': 'local', 'connection_info': "{'fake': 'connection_info'}", 'image_id': 'fake-image-id-2', 'boot_index': -1}), ] self.legacy_mapping_source_image = [ {'id': 6, 'instance_uuid': uuids.instance, 'device_name': '/dev/sda3', 'connection_info': "{'fake': 'connection_info'}", 'volume_id': 'fake-volume-id-3'}, ] def test_init(self): def fake_validate(obj, dct): pass self.stub_out('nova.block_device.BlockDeviceDict._fields', set(['field1', 'field2'])) self.stub_out('nova.block_device.BlockDeviceDict._db_only_fields', set(['db_field1', 'db_field2'])) self.stub_out('nova.block_device.BlockDeviceDict._validate', fake_validate) # Make sure db fields are not picked up if they are not # in the original dict dev_dict = block_device.BlockDeviceDict({'field1': 'foo', 'field2': 'bar', 'db_field1': 'baz'}) self.assertIn('field1', dev_dict) self.assertIn('field2', dev_dict) self.assertIn('db_field1', dev_dict) self.assertNotIn('db_field2', dev_dict) # Make sure all expected fields are defaulted dev_dict = block_device.BlockDeviceDict({'field1': 'foo'}) self.assertIn('field1', dev_dict) self.assertIn('field2', dev_dict) self.assertIsNone(dev_dict['field2']) self.assertNotIn('db_field1', dev_dict) self.assertNotIn('db_field2', dev_dict) # Unless they are not meant to be dev_dict = block_device.BlockDeviceDict({'field1': 'foo'}, do_not_default=set(['field2'])) self.assertIn('field1', dev_dict) self.assertNotIn('field2', dev_dict) self.assertNotIn('db_field1', dev_dict) self.assertNotIn('db_field2', dev_dict) # Passing kwargs to constructor works dev_dict = block_device.BlockDeviceDict(field1='foo') self.assertIn('field1', dev_dict) self.assertIn('field2', dev_dict) self.assertIsNone(dev_dict['field2']) dev_dict = block_device.BlockDeviceDict( {'field1': 'foo'}, field2='bar') self.assertEqual('foo', dev_dict['field1']) self.assertEqual('bar', dev_dict['field2']) def test_init_prepend_dev_to_device_name(self): bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name': 'vda', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'fake-volume-id-1', 'boot_index': 0} bdm_dict = block_device.BlockDeviceDict(bdm) self.assertEqual('/dev/vda', bdm_dict['device_name']) bdm['device_name'] = '/dev/vdb' bdm_dict = block_device.BlockDeviceDict(bdm) self.assertEqual('/dev/vdb', bdm_dict['device_name']) bdm['device_name'] = None bdm_dict = block_device.BlockDeviceDict(bdm) self.assertIsNone(bdm_dict['device_name']) def test_init_boolify_delete_on_termination(self): # Make sure that when delete_on_termination is not passed it's # still set to False and not None bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name': 'vda', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'fake-volume-id-1', 'boot_index': 0} bdm_dict = block_device.BlockDeviceDict(bdm) self.assertFalse(bdm_dict['delete_on_termination']) def test_validate(self): self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict, {'bogus_field': 'lame_val'}) lame_bdm = dict(self.new_mapping[2]) del lame_bdm['source_type'] self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict, lame_bdm) lame_bdm['no_device'] = True block_device.BlockDeviceDict(lame_bdm) lame_dev_bdm = dict(self.new_mapping[2]) lame_dev_bdm['device_name'] = "not a valid name" self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict, lame_dev_bdm) lame_dev_bdm['device_name'] = "" self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict, lame_dev_bdm) cool_volume_size_bdm = dict(self.new_mapping[2]) cool_volume_size_bdm['volume_size'] = '42' cool_volume_size_bdm = block_device.BlockDeviceDict( cool_volume_size_bdm) self.assertEqual(42, cool_volume_size_bdm['volume_size']) lame_volume_size_bdm = dict(self.new_mapping[2]) lame_volume_size_bdm['volume_size'] = 'some_non_int_string' self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict, lame_volume_size_bdm) truthy_bdm = dict(self.new_mapping[2]) truthy_bdm['delete_on_termination'] = '1' truthy_bdm = block_device.BlockDeviceDict(truthy_bdm) self.assertTrue(truthy_bdm['delete_on_termination']) verbose_bdm = dict(self.new_mapping[2]) verbose_bdm['boot_index'] = 'first' self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict, verbose_bdm) def test_from_legacy(self): for legacy, new in zip(self.legacy_mapping, self.new_mapping): self.assertThat( block_device.BlockDeviceDict.from_legacy(legacy), matchers.IsSubDictOf(new)) def test_from_legacy_mapping(self): def _get_image_bdms(bdms): return [bdm for bdm in bdms if bdm['source_type'] == 'image'] def _get_bootable_bdms(bdms): return [bdm for bdm in bdms if (bdm['boot_index'] is not None and bdm['boot_index'] >= 0)] new_no_img = block_device.from_legacy_mapping(self.legacy_mapping) self.assertEqual(0, len(_get_image_bdms(new_no_img))) for new, expected in zip(new_no_img, self.new_mapping): self.assertThat(new, matchers.IsSubDictOf(expected)) new_with_img = block_device.from_legacy_mapping( self.legacy_mapping, 'fake_image_ref') image_bdms = _get_image_bdms(new_with_img) boot_bdms = _get_bootable_bdms(new_with_img) self.assertEqual(1, len(image_bdms)) self.assertEqual(1, len(boot_bdms)) self.assertEqual(0, image_bdms[0]['boot_index']) self.assertEqual('image', boot_bdms[0]['source_type']) new_with_img_and_root = block_device.from_legacy_mapping( self.legacy_mapping, 'fake_image_ref', 'sda1') image_bdms = _get_image_bdms(new_with_img_and_root) boot_bdms = _get_bootable_bdms(new_with_img_and_root) self.assertEqual(0, len(image_bdms)) self.assertEqual(1, len(boot_bdms)) self.assertEqual(0, boot_bdms[0]['boot_index']) self.assertEqual('volume', boot_bdms[0]['source_type']) new_no_root = block_device.from_legacy_mapping( self.legacy_mapping, 'fake_image_ref', 'sda1', no_root=True) self.assertEqual(0, len(_get_image_bdms(new_no_root))) self.assertEqual(0, len(_get_bootable_bdms(new_no_root))) def test_from_api(self): for api, new in zip(self.api_mapping, self.new_mapping): new['connection_info'] = None if new['snapshot_id']: new['volume_id'] = None self.assertThat( block_device.BlockDeviceDict.from_api(api, False), matchers.IsSubDictOf(new)) def test_from_api_invalid_blank_id(self): api_dict = {'id': 1, 'source_type': 'blank', 'destination_type': 'volume', 'uuid': 'fake-volume-id-1', 'delete_on_termination': True, 'boot_index': -1} self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict.from_api, api_dict, False) def test_from_api_invalid_source_to_local_mapping(self): api_dict = {'id': 1, 'source_type': 'image', 'destination_type': 'local', 'uuid': 'fake-volume-id-1'} self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict.from_api, api_dict, False) def test_from_api_valid_source_to_local_mapping(self): api_dict = {'id': 1, 'source_type': 'image', 'destination_type': 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1, 'boot_index': 0} retexp = block_device.BlockDeviceDict( {'id': 1, 'source_type': 'image', 'image_id': 1, 'destination_type': 'local', 'volume_id': 'fake-volume-id-1', 'boot_index': 0}) self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(api_dict, True)) def test_from_api_valid_source_to_local_mapping_with_string_bi(self): api_dict = {'id': 1, 'source_type': 'image', 'destination_type': 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1, 'boot_index': '0'} retexp = block_device.BlockDeviceDict( {'id': 1, 'source_type': 'image', 'image_id': 1, 'destination_type': 'local', 'volume_id': 'fake-volume-id-1', 'boot_index': 0}) self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(api_dict, True)) def test_from_api_invalid_image_to_destination_local_mapping(self): api_dict = {'id': 1, 'source_type': 'image', 'destination_type': 'local', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1', 'boot_index': 1} ex = self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict.from_api, api_dict, False) self.assertIn('Mapping image to local is not supported', str(ex)) def test_from_api_invalid_volume_type_to_destination_local_mapping(self): api_dict = {'id': 1, 'source_type': 'volume', 'destination_type': 'local', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'} ex = self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict.from_api, api_dict, False) self.assertIn('Specifying a volume_type with destination_type=local ' 'is not supported', str(ex)) def test_from_api_invalid_specify_volume_type_with_source_volume_mapping( self): api_dict = {'id': 1, 'source_type': 'volume', 'destination_type': 'volume', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'} ex = self.assertRaises(exception.InvalidBDMFormat, block_device.BlockDeviceDict.from_api, api_dict, False) self.assertIn('Specifying volume type to existing volume is ' 'not supported', str(ex)) def test_image_mapping(self): removed_fields = ['id', 'instance_uuid', 'connection_info', 'created_at', 'updated_at', 'deleted_at', 'deleted'] for bdm in self.new_mapping: mapping_bdm = fake_block_device.FakeDbBlockDeviceDict( bdm).get_image_mapping() for fld in removed_fields: self.assertNotIn(fld, mapping_bdm) def _test_snapshot_from_bdm(self, template): snapshot = block_device.snapshot_from_bdm('new-snapshot-id', template) self.assertEqual('new-snapshot-id', snapshot['snapshot_id']) self.assertEqual('snapshot', snapshot['source_type']) self.assertEqual('volume', snapshot['destination_type']) self.assertEqual(template.volume_size, snapshot['volume_size']) self.assertEqual(template.delete_on_termination, snapshot['delete_on_termination']) self.assertEqual(template.device_name, snapshot['device_name']) for key in ['disk_bus', 'device_type', 'boot_index']: self.assertEqual(template[key], snapshot[key]) def test_snapshot_from_bdm(self): for bdm in self.new_mapping: self._test_snapshot_from_bdm(objects.BlockDeviceMapping(**bdm)) def test_snapshot_from_object(self): for bdm in self.new_mapping[:-1]: obj = objects.BlockDeviceMapping() obj = objects.BlockDeviceMapping._from_db_object( None, obj, fake_block_device.FakeDbBlockDeviceDict( bdm)) self._test_snapshot_from_bdm(obj) class GetBDMImageMetadataTestCase(test.NoDBTestCase): def setUp(self): super().setUp() self.compute_api = compute_api.API() self.context = context.RequestContext('fake', 'fake') def _test_get_bdm_image_metadata__bootable(self, is_bootable=False): block_device_mapping = [{ 'id': 1, 'device_name': 'vda', 'no_device': None, 'virtual_name': None, 'snapshot_id': None, 'volume_id': '1', 'delete_on_termination': False, }] expected_meta = { 'min_disk': 0, 'min_ram': 0, 'properties': {}, 'size': 0, 'status': 'active', } def get_vol_data(*args, **kwargs): return {'bootable': is_bootable} with mock.patch.object( self.compute_api.volume_api, 'get', side_effect=get_vol_data, ): if not is_bootable: self.assertRaises( exception.InvalidBDMVolumeNotBootable, block_device.get_bdm_image_metadata, self.context, self.compute_api.image_api, self.compute_api.volume_api, block_device_mapping) else: meta = block_device.get_bdm_image_metadata( self.context, self.compute_api.image_api, self.compute_api.volume_api, block_device_mapping) self.assertEqual(expected_meta, meta) def test_get_bdm_image_metadata__non_bootable(self): self._test_get_bdm_image_metadata__bootable(False) def test_get_bdm_image_metadata__bootable(self): self._test_get_bdm_image_metadata__bootable(True) def test_get_bdm_image_metadata__basic_property(self): block_device_mapping = [{ 'id': 1, 'device_name': 'vda', 'no_device': None, 'virtual_name': None, 'snapshot_id': None, 'volume_id': '1', 'delete_on_termination': False, }] fake_volume = { 'volume_image_metadata': { 'min_ram': 256, 'min_disk': 128, 'foo': 'bar', }, } with mock.patch.object( self.compute_api.volume_api, 'get', return_value=fake_volume, ): meta = block_device.get_bdm_image_metadata( self.context, self.compute_api.image_api, self.compute_api.volume_api, block_device_mapping) self.assertEqual(256, meta['min_ram']) self.assertEqual(128, meta['min_disk']) self.assertEqual('active', meta['status']) self.assertEqual('bar', meta['properties']['foo']) def test_get_bdm_image_metadata__snapshot_basic_property(self): block_device_mapping = [{ 'id': 1, 'device_name': 'vda', 'no_device': None, 'virtual_name': None, 'snapshot_id': '2', 'volume_id': None, 'delete_on_termination': False, }] fake_volume = { 'volume_image_metadata': { 'min_ram': 256, 'min_disk': 128, 'foo': 'bar', }, } fake_snapshot = {'volume_id': '1'} with test.nested( mock.patch.object( self.compute_api.volume_api, 'get', return_value=fake_volume), mock.patch.object( self.compute_api.volume_api, 'get_snapshot', return_value=fake_snapshot), ) as (volume_get, volume_get_snapshot): meta = block_device.get_bdm_image_metadata( self.context, self.compute_api.image_api, self.compute_api.volume_api, block_device_mapping) self.assertEqual(256, meta['min_ram']) self.assertEqual(128, meta['min_disk']) self.assertEqual('active', meta['status']) self.assertEqual('bar', meta['properties']['foo']) volume_get_snapshot.assert_called_once_with( self.context, block_device_mapping[0]['snapshot_id']) volume_get.assert_called_once_with( self.context, fake_snapshot['volume_id']) @mock.patch.object( cinder.API, 'get', side_effect=exception.CinderConnectionFailed(reason='error')) def test_get_bdm_image_metadata__cinder_down(self, mock_get): bdms = [ objects.BlockDeviceMapping( **fake_block_device.FakeDbBlockDeviceDict({ 'id': 1, 'volume_id': 1, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': 'vda', }) ) ] self.assertRaises( exception.CinderConnectionFailed, block_device.get_bdm_image_metadata, self.context, self.compute_api.image_api, self.compute_api.volume_api, bdms, legacy_bdm=True) class GetImageMetadataFromVolumeTestCase(test.NoDBTestCase): def test_inherit_image_properties(self): properties = {'fake_prop': 'fake_value'} volume = {'volume_image_metadata': properties} image_meta = block_device.get_image_metadata_from_volume(volume) self.assertEqual(properties, image_meta['properties']) def test_image_size(self): volume = {'size': 10} image_meta = block_device.get_image_metadata_from_volume(volume) self.assertEqual(10 * units.Gi, image_meta['size']) def test_image_status(self): volume = {} image_meta = block_device.get_image_metadata_from_volume(volume) self.assertEqual('active', image_meta['status']) def test_values_conversion(self): properties = {'min_ram': '5', 'min_disk': '7'} volume = {'volume_image_metadata': properties} image_meta = block_device.get_image_metadata_from_volume(volume) self.assertEqual(5, image_meta['min_ram']) self.assertEqual(7, image_meta['min_disk']) def test_suppress_not_image_properties(self): properties = { 'min_ram': '256', 'min_disk': '128', 'image_id': 'fake_id', 'image_name': 'fake_name', 'container_format': 'ami', 'disk_format': 'ami', 'size': '1234', 'checksum': 'fake_checksum', } volume = {'volume_image_metadata': properties} image_meta = block_device.get_image_metadata_from_volume(volume) self.assertEqual({}, image_meta['properties']) self.assertEqual(0, image_meta['size']) # volume's properties should not be touched self.assertNotEqual({}, properties)
normal
{ "blob_id": "d56e313318635788ae5b3d3a3f767450ab2f2296", "index": 4985, "step-1": "<mask token>\n\n\nclass BlockDeviceTestCase(test.NoDBTestCase):\n <mask token>\n\n def test_properties(self):\n root_device0 = '/dev/sda'\n root_device1 = '/dev/sdb'\n mappings = [{'virtual': 'root', 'device': root_device0}]\n properties0 = {'mappings': mappings}\n properties1 = {'mappings': mappings, 'root_device_name': root_device1}\n self.assertIsNone(block_device.properties_root_device_name({}))\n self.assertEqual(root_device0, block_device.\n properties_root_device_name(properties0))\n self.assertEqual(root_device1, block_device.\n properties_root_device_name(properties1))\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def test_validate_device_name(self):\n for value in [' ', 10, None, 'a' * 260]:\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n validate_device_name, value)\n <mask token>\n <mask token>\n\n\nclass TestBlockDeviceDict(test.NoDBTestCase):\n\n def setUp(self):\n super(TestBlockDeviceDict, self).setUp()\n BDM = block_device.BlockDeviceDict\n self.api_mapping = [{'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'source_type': 'blank',\n 'destination_type': 'local', 'delete_on_termination': True,\n 'guest_format': 'swap', 'boot_index': -1}, {'id': 2,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1',\n 'source_type': 'blank', 'destination_type': 'local',\n 'delete_on_termination': True, 'boot_index': -1}, {'id': 3,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1',\n 'source_type': 'volume', 'destination_type': 'volume', 'uuid':\n 'fake-volume-id-1', 'boot_index': 0}, {'id': 4, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda2', 'source_type':\n 'snapshot', 'destination_type': 'volume', 'uuid':\n 'fake-snapshot-id-1', 'boot_index': -1}, {'id': 5,\n 'instance_uuid': uuids.instance, 'no_device': True,\n 'device_name': '/dev/vdc'}]\n self.new_mapping = [BDM({'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'source_type': 'blank',\n 'destination_type': 'local', 'delete_on_termination': True,\n 'guest_format': 'swap', 'boot_index': -1}), BDM({'id': 2,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1',\n 'source_type': 'blank', 'destination_type': 'local',\n 'delete_on_termination': True, 'boot_index': -1}), BDM({'id': 3,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1',\n 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'connection_info':\n \"{'fake': 'connection_info'}\", 'boot_index': 0}), BDM({'id': 4,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda2',\n 'source_type': 'snapshot', 'destination_type': 'volume',\n 'connection_info': \"{'fake': 'connection_info'}\", 'snapshot_id':\n 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2',\n 'boot_index': -1}), BDM({'id': 5, 'instance_uuid': uuids.\n instance, 'no_device': True, 'device_name': '/dev/vdc'})]\n self.legacy_mapping = [{'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'delete_on_termination': True,\n 'virtual_name': 'swap'}, {'id': 2, 'instance_uuid': uuids.\n instance, 'device_name': '/dev/sdc1', 'delete_on_termination': \n True, 'virtual_name': 'ephemeral0'}, {'id': 3, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda1', 'volume_id':\n 'fake-volume-id-1', 'connection_info':\n \"{'fake': 'connection_info'}\"}, {'id': 4, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda2', 'connection_info':\n \"{'fake': 'connection_info'}\", 'snapshot_id':\n 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2'}, {'id': \n 5, 'instance_uuid': uuids.instance, 'no_device': True,\n 'device_name': '/dev/vdc'}]\n self.new_mapping_source_image = [BDM({'id': 6, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda3', 'source_type':\n 'image', 'destination_type': 'volume', 'connection_info':\n \"{'fake': 'connection_info'}\", 'volume_id': 'fake-volume-id-3',\n 'boot_index': -1}), BDM({'id': 7, 'instance_uuid': uuids.\n instance, 'device_name': '/dev/sda4', 'source_type': 'image',\n 'destination_type': 'local', 'connection_info':\n \"{'fake': 'connection_info'}\", 'image_id': 'fake-image-id-2',\n 'boot_index': -1})]\n self.legacy_mapping_source_image = [{'id': 6, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda3', 'connection_info':\n \"{'fake': 'connection_info'}\", 'volume_id': 'fake-volume-id-3'}]\n\n def test_init(self):\n\n def fake_validate(obj, dct):\n pass\n self.stub_out('nova.block_device.BlockDeviceDict._fields', set([\n 'field1', 'field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._db_only_fields',\n set(['db_field1', 'db_field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._validate',\n fake_validate)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo', 'field2':\n 'bar', 'db_field1': 'baz'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'},\n do_not_default=set(['field2']))\n self.assertIn('field1', dev_dict)\n self.assertNotIn('field2', dev_dict)\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict(field1='foo')\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'}, field2='bar'\n )\n self.assertEqual('foo', dev_dict['field1'])\n self.assertEqual('bar', dev_dict['field2'])\n\n def test_init_prepend_dev_to_device_name(self):\n bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name':\n 'vda', 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vda', bdm_dict['device_name'])\n bdm['device_name'] = '/dev/vdb'\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vdb', bdm_dict['device_name'])\n bdm['device_name'] = None\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertIsNone(bdm_dict['device_name'])\n\n def test_init_boolify_delete_on_termination(self):\n bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name':\n 'vda', 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertFalse(bdm_dict['delete_on_termination'])\n\n def test_validate(self):\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, {'bogus_field': 'lame_val'})\n lame_bdm = dict(self.new_mapping[2])\n del lame_bdm['source_type']\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_bdm)\n lame_bdm['no_device'] = True\n block_device.BlockDeviceDict(lame_bdm)\n lame_dev_bdm = dict(self.new_mapping[2])\n lame_dev_bdm['device_name'] = 'not a valid name'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_dev_bdm)\n lame_dev_bdm['device_name'] = ''\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_dev_bdm)\n cool_volume_size_bdm = dict(self.new_mapping[2])\n cool_volume_size_bdm['volume_size'] = '42'\n cool_volume_size_bdm = block_device.BlockDeviceDict(\n cool_volume_size_bdm)\n self.assertEqual(42, cool_volume_size_bdm['volume_size'])\n lame_volume_size_bdm = dict(self.new_mapping[2])\n lame_volume_size_bdm['volume_size'] = 'some_non_int_string'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_volume_size_bdm)\n truthy_bdm = dict(self.new_mapping[2])\n truthy_bdm['delete_on_termination'] = '1'\n truthy_bdm = block_device.BlockDeviceDict(truthy_bdm)\n self.assertTrue(truthy_bdm['delete_on_termination'])\n verbose_bdm = dict(self.new_mapping[2])\n verbose_bdm['boot_index'] = 'first'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, verbose_bdm)\n\n def test_from_legacy(self):\n for legacy, new in zip(self.legacy_mapping, self.new_mapping):\n self.assertThat(block_device.BlockDeviceDict.from_legacy(legacy\n ), matchers.IsSubDictOf(new))\n\n def test_from_legacy_mapping(self):\n\n def _get_image_bdms(bdms):\n return [bdm for bdm in bdms if bdm['source_type'] == 'image']\n\n def _get_bootable_bdms(bdms):\n return [bdm for bdm in bdms if bdm['boot_index'] is not None and\n bdm['boot_index'] >= 0]\n new_no_img = block_device.from_legacy_mapping(self.legacy_mapping)\n self.assertEqual(0, len(_get_image_bdms(new_no_img)))\n for new, expected in zip(new_no_img, self.new_mapping):\n self.assertThat(new, matchers.IsSubDictOf(expected))\n new_with_img = block_device.from_legacy_mapping(self.legacy_mapping,\n 'fake_image_ref')\n image_bdms = _get_image_bdms(new_with_img)\n boot_bdms = _get_bootable_bdms(new_with_img)\n self.assertEqual(1, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, image_bdms[0]['boot_index'])\n self.assertEqual('image', boot_bdms[0]['source_type'])\n new_with_img_and_root = block_device.from_legacy_mapping(self.\n legacy_mapping, 'fake_image_ref', 'sda1')\n image_bdms = _get_image_bdms(new_with_img_and_root)\n boot_bdms = _get_bootable_bdms(new_with_img_and_root)\n self.assertEqual(0, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, boot_bdms[0]['boot_index'])\n self.assertEqual('volume', boot_bdms[0]['source_type'])\n new_no_root = block_device.from_legacy_mapping(self.legacy_mapping,\n 'fake_image_ref', 'sda1', no_root=True)\n self.assertEqual(0, len(_get_image_bdms(new_no_root)))\n self.assertEqual(0, len(_get_bootable_bdms(new_no_root)))\n\n def test_from_api(self):\n for api, new in zip(self.api_mapping, self.new_mapping):\n new['connection_info'] = None\n if new['snapshot_id']:\n new['volume_id'] = None\n self.assertThat(block_device.BlockDeviceDict.from_api(api, \n False), matchers.IsSubDictOf(new))\n\n def test_from_api_invalid_blank_id(self):\n api_dict = {'id': 1, 'source_type': 'blank', 'destination_type':\n 'volume', 'uuid': 'fake-volume-id-1', 'delete_on_termination': \n True, 'boot_index': -1}\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n\n def test_from_api_invalid_source_to_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1'}\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n\n def test_from_api_valid_source_to_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1,\n 'boot_index': 0}\n retexp = block_device.BlockDeviceDict({'id': 1, 'source_type':\n 'image', 'image_id': 1, 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0})\n self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(\n api_dict, True))\n\n def test_from_api_valid_source_to_local_mapping_with_string_bi(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1,\n 'boot_index': '0'}\n retexp = block_device.BlockDeviceDict({'id': 1, 'source_type':\n 'image', 'image_id': 1, 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0})\n self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(\n api_dict, True))\n\n def test_from_api_invalid_image_to_destination_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1', 'volume_type':\n 'fake-lvm-1', 'boot_index': 1}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn('Mapping image to local is not supported', str(ex))\n\n def test_from_api_invalid_volume_type_to_destination_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'volume', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn(\n 'Specifying a volume_type with destination_type=local is not supported'\n , str(ex))\n\n def test_from_api_invalid_specify_volume_type_with_source_volume_mapping(\n self):\n api_dict = {'id': 1, 'source_type': 'volume', 'destination_type':\n 'volume', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn(\n 'Specifying volume type to existing volume is not supported',\n str(ex))\n\n def test_image_mapping(self):\n removed_fields = ['id', 'instance_uuid', 'connection_info',\n 'created_at', 'updated_at', 'deleted_at', 'deleted']\n for bdm in self.new_mapping:\n mapping_bdm = fake_block_device.FakeDbBlockDeviceDict(bdm\n ).get_image_mapping()\n for fld in removed_fields:\n self.assertNotIn(fld, mapping_bdm)\n\n def _test_snapshot_from_bdm(self, template):\n snapshot = block_device.snapshot_from_bdm('new-snapshot-id', template)\n self.assertEqual('new-snapshot-id', snapshot['snapshot_id'])\n self.assertEqual('snapshot', snapshot['source_type'])\n self.assertEqual('volume', snapshot['destination_type'])\n self.assertEqual(template.volume_size, snapshot['volume_size'])\n self.assertEqual(template.delete_on_termination, snapshot[\n 'delete_on_termination'])\n self.assertEqual(template.device_name, snapshot['device_name'])\n for key in ['disk_bus', 'device_type', 'boot_index']:\n self.assertEqual(template[key], snapshot[key])\n\n def test_snapshot_from_bdm(self):\n for bdm in self.new_mapping:\n self._test_snapshot_from_bdm(objects.BlockDeviceMapping(**bdm))\n\n def test_snapshot_from_object(self):\n for bdm in self.new_mapping[:-1]:\n obj = objects.BlockDeviceMapping()\n obj = objects.BlockDeviceMapping._from_db_object(None, obj,\n fake_block_device.FakeDbBlockDeviceDict(bdm))\n self._test_snapshot_from_bdm(obj)\n\n\nclass GetBDMImageMetadataTestCase(test.NoDBTestCase):\n\n def setUp(self):\n super().setUp()\n self.compute_api = compute_api.API()\n self.context = context.RequestContext('fake', 'fake')\n\n def _test_get_bdm_image_metadata__bootable(self, is_bootable=False):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': None, 'volume_id':\n '1', 'delete_on_termination': False}]\n expected_meta = {'min_disk': 0, 'min_ram': 0, 'properties': {},\n 'size': 0, 'status': 'active'}\n\n def get_vol_data(*args, **kwargs):\n return {'bootable': is_bootable}\n with mock.patch.object(self.compute_api.volume_api, 'get',\n side_effect=get_vol_data):\n if not is_bootable:\n self.assertRaises(exception.InvalidBDMVolumeNotBootable,\n block_device.get_bdm_image_metadata, self.context, self\n .compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n else:\n meta = block_device.get_bdm_image_metadata(self.context,\n self.compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(expected_meta, meta)\n\n def test_get_bdm_image_metadata__non_bootable(self):\n self._test_get_bdm_image_metadata__bootable(False)\n\n def test_get_bdm_image_metadata__bootable(self):\n self._test_get_bdm_image_metadata__bootable(True)\n\n def test_get_bdm_image_metadata__basic_property(self):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': None, 'volume_id':\n '1', 'delete_on_termination': False}]\n fake_volume = {'volume_image_metadata': {'min_ram': 256, 'min_disk':\n 128, 'foo': 'bar'}}\n with mock.patch.object(self.compute_api.volume_api, 'get',\n return_value=fake_volume):\n meta = block_device.get_bdm_image_metadata(self.context, self.\n compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n\n def test_get_bdm_image_metadata__snapshot_basic_property(self):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': '2', 'volume_id':\n None, 'delete_on_termination': False}]\n fake_volume = {'volume_image_metadata': {'min_ram': 256, 'min_disk':\n 128, 'foo': 'bar'}}\n fake_snapshot = {'volume_id': '1'}\n with test.nested(mock.patch.object(self.compute_api.volume_api,\n 'get', return_value=fake_volume), mock.patch.object(self.\n compute_api.volume_api, 'get_snapshot', return_value=fake_snapshot)\n ) as (volume_get, volume_get_snapshot):\n meta = block_device.get_bdm_image_metadata(self.context, self.\n compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n volume_get_snapshot.assert_called_once_with(self.context,\n block_device_mapping[0]['snapshot_id'])\n volume_get.assert_called_once_with(self.context, fake_snapshot[\n 'volume_id'])\n\n @mock.patch.object(cinder.API, 'get', side_effect=exception.\n CinderConnectionFailed(reason='error'))\n def test_get_bdm_image_metadata__cinder_down(self, mock_get):\n bdms = [objects.BlockDeviceMapping(**fake_block_device.\n FakeDbBlockDeviceDict({'id': 1, 'volume_id': 1, 'source_type':\n 'volume', 'destination_type': 'volume', 'device_name': 'vda'}))]\n self.assertRaises(exception.CinderConnectionFailed, block_device.\n get_bdm_image_metadata, self.context, self.compute_api.\n image_api, self.compute_api.volume_api, bdms, legacy_bdm=True)\n\n\nclass GetImageMetadataFromVolumeTestCase(test.NoDBTestCase):\n\n def test_inherit_image_properties(self):\n properties = {'fake_prop': 'fake_value'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(properties, image_meta['properties'])\n\n def test_image_size(self):\n volume = {'size': 10}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(10 * units.Gi, image_meta['size'])\n\n def test_image_status(self):\n volume = {}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual('active', image_meta['status'])\n\n def test_values_conversion(self):\n properties = {'min_ram': '5', 'min_disk': '7'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(5, image_meta['min_ram'])\n self.assertEqual(7, image_meta['min_disk'])\n\n def test_suppress_not_image_properties(self):\n properties = {'min_ram': '256', 'min_disk': '128', 'image_id':\n 'fake_id', 'image_name': 'fake_name', 'container_format': 'ami',\n 'disk_format': 'ami', 'size': '1234', 'checksum': 'fake_checksum'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual({}, image_meta['properties'])\n self.assertEqual(0, image_meta['size'])\n self.assertNotEqual({}, properties)\n", "step-2": "<mask token>\n\n\nclass BlockDeviceTestCase(test.NoDBTestCase):\n <mask token>\n\n def test_properties(self):\n root_device0 = '/dev/sda'\n root_device1 = '/dev/sdb'\n mappings = [{'virtual': 'root', 'device': root_device0}]\n properties0 = {'mappings': mappings}\n properties1 = {'mappings': mappings, 'root_device_name': root_device1}\n self.assertIsNone(block_device.properties_root_device_name({}))\n self.assertEqual(root_device0, block_device.\n properties_root_device_name(properties0))\n self.assertEqual(root_device1, block_device.\n properties_root_device_name(properties1))\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def test_new_format_is_swap(self):\n expected_results = [True, False, False, False, False]\n for expected, bdm in zip(expected_results, self.new_mapping):\n res = block_device.new_format_is_swap(bdm)\n self.assertEqual(expected, res)\n <mask token>\n\n def test_validate_device_name(self):\n for value in [' ', 10, None, 'a' * 260]:\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n validate_device_name, value)\n <mask token>\n <mask token>\n\n\nclass TestBlockDeviceDict(test.NoDBTestCase):\n\n def setUp(self):\n super(TestBlockDeviceDict, self).setUp()\n BDM = block_device.BlockDeviceDict\n self.api_mapping = [{'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'source_type': 'blank',\n 'destination_type': 'local', 'delete_on_termination': True,\n 'guest_format': 'swap', 'boot_index': -1}, {'id': 2,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1',\n 'source_type': 'blank', 'destination_type': 'local',\n 'delete_on_termination': True, 'boot_index': -1}, {'id': 3,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1',\n 'source_type': 'volume', 'destination_type': 'volume', 'uuid':\n 'fake-volume-id-1', 'boot_index': 0}, {'id': 4, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda2', 'source_type':\n 'snapshot', 'destination_type': 'volume', 'uuid':\n 'fake-snapshot-id-1', 'boot_index': -1}, {'id': 5,\n 'instance_uuid': uuids.instance, 'no_device': True,\n 'device_name': '/dev/vdc'}]\n self.new_mapping = [BDM({'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'source_type': 'blank',\n 'destination_type': 'local', 'delete_on_termination': True,\n 'guest_format': 'swap', 'boot_index': -1}), BDM({'id': 2,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1',\n 'source_type': 'blank', 'destination_type': 'local',\n 'delete_on_termination': True, 'boot_index': -1}), BDM({'id': 3,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1',\n 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'connection_info':\n \"{'fake': 'connection_info'}\", 'boot_index': 0}), BDM({'id': 4,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda2',\n 'source_type': 'snapshot', 'destination_type': 'volume',\n 'connection_info': \"{'fake': 'connection_info'}\", 'snapshot_id':\n 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2',\n 'boot_index': -1}), BDM({'id': 5, 'instance_uuid': uuids.\n instance, 'no_device': True, 'device_name': '/dev/vdc'})]\n self.legacy_mapping = [{'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'delete_on_termination': True,\n 'virtual_name': 'swap'}, {'id': 2, 'instance_uuid': uuids.\n instance, 'device_name': '/dev/sdc1', 'delete_on_termination': \n True, 'virtual_name': 'ephemeral0'}, {'id': 3, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda1', 'volume_id':\n 'fake-volume-id-1', 'connection_info':\n \"{'fake': 'connection_info'}\"}, {'id': 4, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda2', 'connection_info':\n \"{'fake': 'connection_info'}\", 'snapshot_id':\n 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2'}, {'id': \n 5, 'instance_uuid': uuids.instance, 'no_device': True,\n 'device_name': '/dev/vdc'}]\n self.new_mapping_source_image = [BDM({'id': 6, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda3', 'source_type':\n 'image', 'destination_type': 'volume', 'connection_info':\n \"{'fake': 'connection_info'}\", 'volume_id': 'fake-volume-id-3',\n 'boot_index': -1}), BDM({'id': 7, 'instance_uuid': uuids.\n instance, 'device_name': '/dev/sda4', 'source_type': 'image',\n 'destination_type': 'local', 'connection_info':\n \"{'fake': 'connection_info'}\", 'image_id': 'fake-image-id-2',\n 'boot_index': -1})]\n self.legacy_mapping_source_image = [{'id': 6, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda3', 'connection_info':\n \"{'fake': 'connection_info'}\", 'volume_id': 'fake-volume-id-3'}]\n\n def test_init(self):\n\n def fake_validate(obj, dct):\n pass\n self.stub_out('nova.block_device.BlockDeviceDict._fields', set([\n 'field1', 'field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._db_only_fields',\n set(['db_field1', 'db_field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._validate',\n fake_validate)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo', 'field2':\n 'bar', 'db_field1': 'baz'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'},\n do_not_default=set(['field2']))\n self.assertIn('field1', dev_dict)\n self.assertNotIn('field2', dev_dict)\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict(field1='foo')\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'}, field2='bar'\n )\n self.assertEqual('foo', dev_dict['field1'])\n self.assertEqual('bar', dev_dict['field2'])\n\n def test_init_prepend_dev_to_device_name(self):\n bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name':\n 'vda', 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vda', bdm_dict['device_name'])\n bdm['device_name'] = '/dev/vdb'\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vdb', bdm_dict['device_name'])\n bdm['device_name'] = None\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertIsNone(bdm_dict['device_name'])\n\n def test_init_boolify_delete_on_termination(self):\n bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name':\n 'vda', 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertFalse(bdm_dict['delete_on_termination'])\n\n def test_validate(self):\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, {'bogus_field': 'lame_val'})\n lame_bdm = dict(self.new_mapping[2])\n del lame_bdm['source_type']\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_bdm)\n lame_bdm['no_device'] = True\n block_device.BlockDeviceDict(lame_bdm)\n lame_dev_bdm = dict(self.new_mapping[2])\n lame_dev_bdm['device_name'] = 'not a valid name'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_dev_bdm)\n lame_dev_bdm['device_name'] = ''\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_dev_bdm)\n cool_volume_size_bdm = dict(self.new_mapping[2])\n cool_volume_size_bdm['volume_size'] = '42'\n cool_volume_size_bdm = block_device.BlockDeviceDict(\n cool_volume_size_bdm)\n self.assertEqual(42, cool_volume_size_bdm['volume_size'])\n lame_volume_size_bdm = dict(self.new_mapping[2])\n lame_volume_size_bdm['volume_size'] = 'some_non_int_string'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_volume_size_bdm)\n truthy_bdm = dict(self.new_mapping[2])\n truthy_bdm['delete_on_termination'] = '1'\n truthy_bdm = block_device.BlockDeviceDict(truthy_bdm)\n self.assertTrue(truthy_bdm['delete_on_termination'])\n verbose_bdm = dict(self.new_mapping[2])\n verbose_bdm['boot_index'] = 'first'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, verbose_bdm)\n\n def test_from_legacy(self):\n for legacy, new in zip(self.legacy_mapping, self.new_mapping):\n self.assertThat(block_device.BlockDeviceDict.from_legacy(legacy\n ), matchers.IsSubDictOf(new))\n\n def test_from_legacy_mapping(self):\n\n def _get_image_bdms(bdms):\n return [bdm for bdm in bdms if bdm['source_type'] == 'image']\n\n def _get_bootable_bdms(bdms):\n return [bdm for bdm in bdms if bdm['boot_index'] is not None and\n bdm['boot_index'] >= 0]\n new_no_img = block_device.from_legacy_mapping(self.legacy_mapping)\n self.assertEqual(0, len(_get_image_bdms(new_no_img)))\n for new, expected in zip(new_no_img, self.new_mapping):\n self.assertThat(new, matchers.IsSubDictOf(expected))\n new_with_img = block_device.from_legacy_mapping(self.legacy_mapping,\n 'fake_image_ref')\n image_bdms = _get_image_bdms(new_with_img)\n boot_bdms = _get_bootable_bdms(new_with_img)\n self.assertEqual(1, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, image_bdms[0]['boot_index'])\n self.assertEqual('image', boot_bdms[0]['source_type'])\n new_with_img_and_root = block_device.from_legacy_mapping(self.\n legacy_mapping, 'fake_image_ref', 'sda1')\n image_bdms = _get_image_bdms(new_with_img_and_root)\n boot_bdms = _get_bootable_bdms(new_with_img_and_root)\n self.assertEqual(0, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, boot_bdms[0]['boot_index'])\n self.assertEqual('volume', boot_bdms[0]['source_type'])\n new_no_root = block_device.from_legacy_mapping(self.legacy_mapping,\n 'fake_image_ref', 'sda1', no_root=True)\n self.assertEqual(0, len(_get_image_bdms(new_no_root)))\n self.assertEqual(0, len(_get_bootable_bdms(new_no_root)))\n\n def test_from_api(self):\n for api, new in zip(self.api_mapping, self.new_mapping):\n new['connection_info'] = None\n if new['snapshot_id']:\n new['volume_id'] = None\n self.assertThat(block_device.BlockDeviceDict.from_api(api, \n False), matchers.IsSubDictOf(new))\n\n def test_from_api_invalid_blank_id(self):\n api_dict = {'id': 1, 'source_type': 'blank', 'destination_type':\n 'volume', 'uuid': 'fake-volume-id-1', 'delete_on_termination': \n True, 'boot_index': -1}\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n\n def test_from_api_invalid_source_to_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1'}\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n\n def test_from_api_valid_source_to_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1,\n 'boot_index': 0}\n retexp = block_device.BlockDeviceDict({'id': 1, 'source_type':\n 'image', 'image_id': 1, 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0})\n self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(\n api_dict, True))\n\n def test_from_api_valid_source_to_local_mapping_with_string_bi(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1,\n 'boot_index': '0'}\n retexp = block_device.BlockDeviceDict({'id': 1, 'source_type':\n 'image', 'image_id': 1, 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0})\n self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(\n api_dict, True))\n\n def test_from_api_invalid_image_to_destination_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1', 'volume_type':\n 'fake-lvm-1', 'boot_index': 1}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn('Mapping image to local is not supported', str(ex))\n\n def test_from_api_invalid_volume_type_to_destination_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'volume', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn(\n 'Specifying a volume_type with destination_type=local is not supported'\n , str(ex))\n\n def test_from_api_invalid_specify_volume_type_with_source_volume_mapping(\n self):\n api_dict = {'id': 1, 'source_type': 'volume', 'destination_type':\n 'volume', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn(\n 'Specifying volume type to existing volume is not supported',\n str(ex))\n\n def test_image_mapping(self):\n removed_fields = ['id', 'instance_uuid', 'connection_info',\n 'created_at', 'updated_at', 'deleted_at', 'deleted']\n for bdm in self.new_mapping:\n mapping_bdm = fake_block_device.FakeDbBlockDeviceDict(bdm\n ).get_image_mapping()\n for fld in removed_fields:\n self.assertNotIn(fld, mapping_bdm)\n\n def _test_snapshot_from_bdm(self, template):\n snapshot = block_device.snapshot_from_bdm('new-snapshot-id', template)\n self.assertEqual('new-snapshot-id', snapshot['snapshot_id'])\n self.assertEqual('snapshot', snapshot['source_type'])\n self.assertEqual('volume', snapshot['destination_type'])\n self.assertEqual(template.volume_size, snapshot['volume_size'])\n self.assertEqual(template.delete_on_termination, snapshot[\n 'delete_on_termination'])\n self.assertEqual(template.device_name, snapshot['device_name'])\n for key in ['disk_bus', 'device_type', 'boot_index']:\n self.assertEqual(template[key], snapshot[key])\n\n def test_snapshot_from_bdm(self):\n for bdm in self.new_mapping:\n self._test_snapshot_from_bdm(objects.BlockDeviceMapping(**bdm))\n\n def test_snapshot_from_object(self):\n for bdm in self.new_mapping[:-1]:\n obj = objects.BlockDeviceMapping()\n obj = objects.BlockDeviceMapping._from_db_object(None, obj,\n fake_block_device.FakeDbBlockDeviceDict(bdm))\n self._test_snapshot_from_bdm(obj)\n\n\nclass GetBDMImageMetadataTestCase(test.NoDBTestCase):\n\n def setUp(self):\n super().setUp()\n self.compute_api = compute_api.API()\n self.context = context.RequestContext('fake', 'fake')\n\n def _test_get_bdm_image_metadata__bootable(self, is_bootable=False):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': None, 'volume_id':\n '1', 'delete_on_termination': False}]\n expected_meta = {'min_disk': 0, 'min_ram': 0, 'properties': {},\n 'size': 0, 'status': 'active'}\n\n def get_vol_data(*args, **kwargs):\n return {'bootable': is_bootable}\n with mock.patch.object(self.compute_api.volume_api, 'get',\n side_effect=get_vol_data):\n if not is_bootable:\n self.assertRaises(exception.InvalidBDMVolumeNotBootable,\n block_device.get_bdm_image_metadata, self.context, self\n .compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n else:\n meta = block_device.get_bdm_image_metadata(self.context,\n self.compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(expected_meta, meta)\n\n def test_get_bdm_image_metadata__non_bootable(self):\n self._test_get_bdm_image_metadata__bootable(False)\n\n def test_get_bdm_image_metadata__bootable(self):\n self._test_get_bdm_image_metadata__bootable(True)\n\n def test_get_bdm_image_metadata__basic_property(self):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': None, 'volume_id':\n '1', 'delete_on_termination': False}]\n fake_volume = {'volume_image_metadata': {'min_ram': 256, 'min_disk':\n 128, 'foo': 'bar'}}\n with mock.patch.object(self.compute_api.volume_api, 'get',\n return_value=fake_volume):\n meta = block_device.get_bdm_image_metadata(self.context, self.\n compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n\n def test_get_bdm_image_metadata__snapshot_basic_property(self):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': '2', 'volume_id':\n None, 'delete_on_termination': False}]\n fake_volume = {'volume_image_metadata': {'min_ram': 256, 'min_disk':\n 128, 'foo': 'bar'}}\n fake_snapshot = {'volume_id': '1'}\n with test.nested(mock.patch.object(self.compute_api.volume_api,\n 'get', return_value=fake_volume), mock.patch.object(self.\n compute_api.volume_api, 'get_snapshot', return_value=fake_snapshot)\n ) as (volume_get, volume_get_snapshot):\n meta = block_device.get_bdm_image_metadata(self.context, self.\n compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n volume_get_snapshot.assert_called_once_with(self.context,\n block_device_mapping[0]['snapshot_id'])\n volume_get.assert_called_once_with(self.context, fake_snapshot[\n 'volume_id'])\n\n @mock.patch.object(cinder.API, 'get', side_effect=exception.\n CinderConnectionFailed(reason='error'))\n def test_get_bdm_image_metadata__cinder_down(self, mock_get):\n bdms = [objects.BlockDeviceMapping(**fake_block_device.\n FakeDbBlockDeviceDict({'id': 1, 'volume_id': 1, 'source_type':\n 'volume', 'destination_type': 'volume', 'device_name': 'vda'}))]\n self.assertRaises(exception.CinderConnectionFailed, block_device.\n get_bdm_image_metadata, self.context, self.compute_api.\n image_api, self.compute_api.volume_api, bdms, legacy_bdm=True)\n\n\nclass GetImageMetadataFromVolumeTestCase(test.NoDBTestCase):\n\n def test_inherit_image_properties(self):\n properties = {'fake_prop': 'fake_value'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(properties, image_meta['properties'])\n\n def test_image_size(self):\n volume = {'size': 10}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(10 * units.Gi, image_meta['size'])\n\n def test_image_status(self):\n volume = {}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual('active', image_meta['status'])\n\n def test_values_conversion(self):\n properties = {'min_ram': '5', 'min_disk': '7'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(5, image_meta['min_ram'])\n self.assertEqual(7, image_meta['min_disk'])\n\n def test_suppress_not_image_properties(self):\n properties = {'min_ram': '256', 'min_disk': '128', 'image_id':\n 'fake_id', 'image_name': 'fake_name', 'container_format': 'ami',\n 'disk_format': 'ami', 'size': '1234', 'checksum': 'fake_checksum'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual({}, image_meta['properties'])\n self.assertEqual(0, image_meta['size'])\n self.assertNotEqual({}, properties)\n", "step-3": "<mask token>\n\n\nclass BlockDeviceTestCase(test.NoDBTestCase):\n <mask token>\n\n def test_properties(self):\n root_device0 = '/dev/sda'\n root_device1 = '/dev/sdb'\n mappings = [{'virtual': 'root', 'device': root_device0}]\n properties0 = {'mappings': mappings}\n properties1 = {'mappings': mappings, 'root_device_name': root_device1}\n self.assertIsNone(block_device.properties_root_device_name({}))\n self.assertEqual(root_device0, block_device.\n properties_root_device_name(properties0))\n self.assertEqual(root_device1, block_device.\n properties_root_device_name(properties1))\n <mask token>\n <mask token>\n\n def test_strip_dev(self):\n self.assertEqual('sda', block_device.strip_dev('/dev/sda'))\n self.assertEqual('sda', block_device.strip_dev('sda'))\n self.assertIsNone(block_device.strip_dev(None))\n <mask token>\n\n def test_get_device_letter(self):\n self.assertEqual('', block_device.get_device_letter(''))\n self.assertEqual('a', block_device.get_device_letter('/dev/sda1'))\n self.assertEqual('b', block_device.get_device_letter('/dev/xvdb'))\n self.assertEqual('d', block_device.get_device_letter('/dev/d'))\n self.assertEqual('a', block_device.get_device_letter('a'))\n self.assertEqual('b', block_device.get_device_letter('sdb2'))\n self.assertEqual('c', block_device.get_device_letter('vdc'))\n self.assertEqual('c', block_device.get_device_letter('hdc'))\n self.assertIsNone(block_device.get_device_letter(None))\n\n def test_generate_device_name(self):\n expected = ('vda', ('vd', 0)), ('vdaa', ('vd', 26)), ('vdabc', (\n 'vd', 730)), ('vdidpok', ('vd', 4194304)), ('sdc', ('sd', 2)), (\n 'sdaa', ('sd', 26)), ('sdiw', ('sd', 256)), ('hdzz', ('hd', 701))\n for res, args in expected:\n self.assertEqual(res, block_device.generate_device_name(*args))\n <mask token>\n\n def test_get_root_bdm(self):\n root_bdm = {'device_name': 'vda', 'boot_index': 0}\n bdms = [root_bdm, {'device_name': 'vdb', 'boot_index': 1}, {\n 'device_name': 'vdc', 'boot_index': -1}, {'device_name': 'vdd'}]\n self.assertEqual(root_bdm, block_device.get_root_bdm(bdms))\n self.assertEqual(root_bdm, block_device.get_root_bdm([bdms[0]]))\n self.assertIsNone(block_device.get_root_bdm(bdms[1:]))\n self.assertIsNone(block_device.get_root_bdm(bdms[2:]))\n self.assertIsNone(block_device.get_root_bdm(bdms[3:]))\n self.assertIsNone(block_device.get_root_bdm([]))\n <mask token>\n <mask token>\n\n def test_get_bdm_local_disk_num(self):\n size = block_device.get_bdm_local_disk_num(self.new_mapping)\n self.assertEqual(2, size)\n\n def test_new_format_is_swap(self):\n expected_results = [True, False, False, False, False]\n for expected, bdm in zip(expected_results, self.new_mapping):\n res = block_device.new_format_is_swap(bdm)\n self.assertEqual(expected, res)\n <mask token>\n\n def test_validate_device_name(self):\n for value in [' ', 10, None, 'a' * 260]:\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n validate_device_name, value)\n <mask token>\n <mask token>\n\n\nclass TestBlockDeviceDict(test.NoDBTestCase):\n\n def setUp(self):\n super(TestBlockDeviceDict, self).setUp()\n BDM = block_device.BlockDeviceDict\n self.api_mapping = [{'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'source_type': 'blank',\n 'destination_type': 'local', 'delete_on_termination': True,\n 'guest_format': 'swap', 'boot_index': -1}, {'id': 2,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1',\n 'source_type': 'blank', 'destination_type': 'local',\n 'delete_on_termination': True, 'boot_index': -1}, {'id': 3,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1',\n 'source_type': 'volume', 'destination_type': 'volume', 'uuid':\n 'fake-volume-id-1', 'boot_index': 0}, {'id': 4, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda2', 'source_type':\n 'snapshot', 'destination_type': 'volume', 'uuid':\n 'fake-snapshot-id-1', 'boot_index': -1}, {'id': 5,\n 'instance_uuid': uuids.instance, 'no_device': True,\n 'device_name': '/dev/vdc'}]\n self.new_mapping = [BDM({'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'source_type': 'blank',\n 'destination_type': 'local', 'delete_on_termination': True,\n 'guest_format': 'swap', 'boot_index': -1}), BDM({'id': 2,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1',\n 'source_type': 'blank', 'destination_type': 'local',\n 'delete_on_termination': True, 'boot_index': -1}), BDM({'id': 3,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1',\n 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'connection_info':\n \"{'fake': 'connection_info'}\", 'boot_index': 0}), BDM({'id': 4,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda2',\n 'source_type': 'snapshot', 'destination_type': 'volume',\n 'connection_info': \"{'fake': 'connection_info'}\", 'snapshot_id':\n 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2',\n 'boot_index': -1}), BDM({'id': 5, 'instance_uuid': uuids.\n instance, 'no_device': True, 'device_name': '/dev/vdc'})]\n self.legacy_mapping = [{'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'delete_on_termination': True,\n 'virtual_name': 'swap'}, {'id': 2, 'instance_uuid': uuids.\n instance, 'device_name': '/dev/sdc1', 'delete_on_termination': \n True, 'virtual_name': 'ephemeral0'}, {'id': 3, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda1', 'volume_id':\n 'fake-volume-id-1', 'connection_info':\n \"{'fake': 'connection_info'}\"}, {'id': 4, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda2', 'connection_info':\n \"{'fake': 'connection_info'}\", 'snapshot_id':\n 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2'}, {'id': \n 5, 'instance_uuid': uuids.instance, 'no_device': True,\n 'device_name': '/dev/vdc'}]\n self.new_mapping_source_image = [BDM({'id': 6, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda3', 'source_type':\n 'image', 'destination_type': 'volume', 'connection_info':\n \"{'fake': 'connection_info'}\", 'volume_id': 'fake-volume-id-3',\n 'boot_index': -1}), BDM({'id': 7, 'instance_uuid': uuids.\n instance, 'device_name': '/dev/sda4', 'source_type': 'image',\n 'destination_type': 'local', 'connection_info':\n \"{'fake': 'connection_info'}\", 'image_id': 'fake-image-id-2',\n 'boot_index': -1})]\n self.legacy_mapping_source_image = [{'id': 6, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda3', 'connection_info':\n \"{'fake': 'connection_info'}\", 'volume_id': 'fake-volume-id-3'}]\n\n def test_init(self):\n\n def fake_validate(obj, dct):\n pass\n self.stub_out('nova.block_device.BlockDeviceDict._fields', set([\n 'field1', 'field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._db_only_fields',\n set(['db_field1', 'db_field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._validate',\n fake_validate)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo', 'field2':\n 'bar', 'db_field1': 'baz'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'},\n do_not_default=set(['field2']))\n self.assertIn('field1', dev_dict)\n self.assertNotIn('field2', dev_dict)\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict(field1='foo')\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'}, field2='bar'\n )\n self.assertEqual('foo', dev_dict['field1'])\n self.assertEqual('bar', dev_dict['field2'])\n\n def test_init_prepend_dev_to_device_name(self):\n bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name':\n 'vda', 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vda', bdm_dict['device_name'])\n bdm['device_name'] = '/dev/vdb'\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vdb', bdm_dict['device_name'])\n bdm['device_name'] = None\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertIsNone(bdm_dict['device_name'])\n\n def test_init_boolify_delete_on_termination(self):\n bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name':\n 'vda', 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertFalse(bdm_dict['delete_on_termination'])\n\n def test_validate(self):\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, {'bogus_field': 'lame_val'})\n lame_bdm = dict(self.new_mapping[2])\n del lame_bdm['source_type']\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_bdm)\n lame_bdm['no_device'] = True\n block_device.BlockDeviceDict(lame_bdm)\n lame_dev_bdm = dict(self.new_mapping[2])\n lame_dev_bdm['device_name'] = 'not a valid name'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_dev_bdm)\n lame_dev_bdm['device_name'] = ''\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_dev_bdm)\n cool_volume_size_bdm = dict(self.new_mapping[2])\n cool_volume_size_bdm['volume_size'] = '42'\n cool_volume_size_bdm = block_device.BlockDeviceDict(\n cool_volume_size_bdm)\n self.assertEqual(42, cool_volume_size_bdm['volume_size'])\n lame_volume_size_bdm = dict(self.new_mapping[2])\n lame_volume_size_bdm['volume_size'] = 'some_non_int_string'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_volume_size_bdm)\n truthy_bdm = dict(self.new_mapping[2])\n truthy_bdm['delete_on_termination'] = '1'\n truthy_bdm = block_device.BlockDeviceDict(truthy_bdm)\n self.assertTrue(truthy_bdm['delete_on_termination'])\n verbose_bdm = dict(self.new_mapping[2])\n verbose_bdm['boot_index'] = 'first'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, verbose_bdm)\n\n def test_from_legacy(self):\n for legacy, new in zip(self.legacy_mapping, self.new_mapping):\n self.assertThat(block_device.BlockDeviceDict.from_legacy(legacy\n ), matchers.IsSubDictOf(new))\n\n def test_from_legacy_mapping(self):\n\n def _get_image_bdms(bdms):\n return [bdm for bdm in bdms if bdm['source_type'] == 'image']\n\n def _get_bootable_bdms(bdms):\n return [bdm for bdm in bdms if bdm['boot_index'] is not None and\n bdm['boot_index'] >= 0]\n new_no_img = block_device.from_legacy_mapping(self.legacy_mapping)\n self.assertEqual(0, len(_get_image_bdms(new_no_img)))\n for new, expected in zip(new_no_img, self.new_mapping):\n self.assertThat(new, matchers.IsSubDictOf(expected))\n new_with_img = block_device.from_legacy_mapping(self.legacy_mapping,\n 'fake_image_ref')\n image_bdms = _get_image_bdms(new_with_img)\n boot_bdms = _get_bootable_bdms(new_with_img)\n self.assertEqual(1, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, image_bdms[0]['boot_index'])\n self.assertEqual('image', boot_bdms[0]['source_type'])\n new_with_img_and_root = block_device.from_legacy_mapping(self.\n legacy_mapping, 'fake_image_ref', 'sda1')\n image_bdms = _get_image_bdms(new_with_img_and_root)\n boot_bdms = _get_bootable_bdms(new_with_img_and_root)\n self.assertEqual(0, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, boot_bdms[0]['boot_index'])\n self.assertEqual('volume', boot_bdms[0]['source_type'])\n new_no_root = block_device.from_legacy_mapping(self.legacy_mapping,\n 'fake_image_ref', 'sda1', no_root=True)\n self.assertEqual(0, len(_get_image_bdms(new_no_root)))\n self.assertEqual(0, len(_get_bootable_bdms(new_no_root)))\n\n def test_from_api(self):\n for api, new in zip(self.api_mapping, self.new_mapping):\n new['connection_info'] = None\n if new['snapshot_id']:\n new['volume_id'] = None\n self.assertThat(block_device.BlockDeviceDict.from_api(api, \n False), matchers.IsSubDictOf(new))\n\n def test_from_api_invalid_blank_id(self):\n api_dict = {'id': 1, 'source_type': 'blank', 'destination_type':\n 'volume', 'uuid': 'fake-volume-id-1', 'delete_on_termination': \n True, 'boot_index': -1}\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n\n def test_from_api_invalid_source_to_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1'}\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n\n def test_from_api_valid_source_to_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1,\n 'boot_index': 0}\n retexp = block_device.BlockDeviceDict({'id': 1, 'source_type':\n 'image', 'image_id': 1, 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0})\n self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(\n api_dict, True))\n\n def test_from_api_valid_source_to_local_mapping_with_string_bi(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1,\n 'boot_index': '0'}\n retexp = block_device.BlockDeviceDict({'id': 1, 'source_type':\n 'image', 'image_id': 1, 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0})\n self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(\n api_dict, True))\n\n def test_from_api_invalid_image_to_destination_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1', 'volume_type':\n 'fake-lvm-1', 'boot_index': 1}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn('Mapping image to local is not supported', str(ex))\n\n def test_from_api_invalid_volume_type_to_destination_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'volume', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn(\n 'Specifying a volume_type with destination_type=local is not supported'\n , str(ex))\n\n def test_from_api_invalid_specify_volume_type_with_source_volume_mapping(\n self):\n api_dict = {'id': 1, 'source_type': 'volume', 'destination_type':\n 'volume', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn(\n 'Specifying volume type to existing volume is not supported',\n str(ex))\n\n def test_image_mapping(self):\n removed_fields = ['id', 'instance_uuid', 'connection_info',\n 'created_at', 'updated_at', 'deleted_at', 'deleted']\n for bdm in self.new_mapping:\n mapping_bdm = fake_block_device.FakeDbBlockDeviceDict(bdm\n ).get_image_mapping()\n for fld in removed_fields:\n self.assertNotIn(fld, mapping_bdm)\n\n def _test_snapshot_from_bdm(self, template):\n snapshot = block_device.snapshot_from_bdm('new-snapshot-id', template)\n self.assertEqual('new-snapshot-id', snapshot['snapshot_id'])\n self.assertEqual('snapshot', snapshot['source_type'])\n self.assertEqual('volume', snapshot['destination_type'])\n self.assertEqual(template.volume_size, snapshot['volume_size'])\n self.assertEqual(template.delete_on_termination, snapshot[\n 'delete_on_termination'])\n self.assertEqual(template.device_name, snapshot['device_name'])\n for key in ['disk_bus', 'device_type', 'boot_index']:\n self.assertEqual(template[key], snapshot[key])\n\n def test_snapshot_from_bdm(self):\n for bdm in self.new_mapping:\n self._test_snapshot_from_bdm(objects.BlockDeviceMapping(**bdm))\n\n def test_snapshot_from_object(self):\n for bdm in self.new_mapping[:-1]:\n obj = objects.BlockDeviceMapping()\n obj = objects.BlockDeviceMapping._from_db_object(None, obj,\n fake_block_device.FakeDbBlockDeviceDict(bdm))\n self._test_snapshot_from_bdm(obj)\n\n\nclass GetBDMImageMetadataTestCase(test.NoDBTestCase):\n\n def setUp(self):\n super().setUp()\n self.compute_api = compute_api.API()\n self.context = context.RequestContext('fake', 'fake')\n\n def _test_get_bdm_image_metadata__bootable(self, is_bootable=False):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': None, 'volume_id':\n '1', 'delete_on_termination': False}]\n expected_meta = {'min_disk': 0, 'min_ram': 0, 'properties': {},\n 'size': 0, 'status': 'active'}\n\n def get_vol_data(*args, **kwargs):\n return {'bootable': is_bootable}\n with mock.patch.object(self.compute_api.volume_api, 'get',\n side_effect=get_vol_data):\n if not is_bootable:\n self.assertRaises(exception.InvalidBDMVolumeNotBootable,\n block_device.get_bdm_image_metadata, self.context, self\n .compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n else:\n meta = block_device.get_bdm_image_metadata(self.context,\n self.compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(expected_meta, meta)\n\n def test_get_bdm_image_metadata__non_bootable(self):\n self._test_get_bdm_image_metadata__bootable(False)\n\n def test_get_bdm_image_metadata__bootable(self):\n self._test_get_bdm_image_metadata__bootable(True)\n\n def test_get_bdm_image_metadata__basic_property(self):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': None, 'volume_id':\n '1', 'delete_on_termination': False}]\n fake_volume = {'volume_image_metadata': {'min_ram': 256, 'min_disk':\n 128, 'foo': 'bar'}}\n with mock.patch.object(self.compute_api.volume_api, 'get',\n return_value=fake_volume):\n meta = block_device.get_bdm_image_metadata(self.context, self.\n compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n\n def test_get_bdm_image_metadata__snapshot_basic_property(self):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': '2', 'volume_id':\n None, 'delete_on_termination': False}]\n fake_volume = {'volume_image_metadata': {'min_ram': 256, 'min_disk':\n 128, 'foo': 'bar'}}\n fake_snapshot = {'volume_id': '1'}\n with test.nested(mock.patch.object(self.compute_api.volume_api,\n 'get', return_value=fake_volume), mock.patch.object(self.\n compute_api.volume_api, 'get_snapshot', return_value=fake_snapshot)\n ) as (volume_get, volume_get_snapshot):\n meta = block_device.get_bdm_image_metadata(self.context, self.\n compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n volume_get_snapshot.assert_called_once_with(self.context,\n block_device_mapping[0]['snapshot_id'])\n volume_get.assert_called_once_with(self.context, fake_snapshot[\n 'volume_id'])\n\n @mock.patch.object(cinder.API, 'get', side_effect=exception.\n CinderConnectionFailed(reason='error'))\n def test_get_bdm_image_metadata__cinder_down(self, mock_get):\n bdms = [objects.BlockDeviceMapping(**fake_block_device.\n FakeDbBlockDeviceDict({'id': 1, 'volume_id': 1, 'source_type':\n 'volume', 'destination_type': 'volume', 'device_name': 'vda'}))]\n self.assertRaises(exception.CinderConnectionFailed, block_device.\n get_bdm_image_metadata, self.context, self.compute_api.\n image_api, self.compute_api.volume_api, bdms, legacy_bdm=True)\n\n\nclass GetImageMetadataFromVolumeTestCase(test.NoDBTestCase):\n\n def test_inherit_image_properties(self):\n properties = {'fake_prop': 'fake_value'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(properties, image_meta['properties'])\n\n def test_image_size(self):\n volume = {'size': 10}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(10 * units.Gi, image_meta['size'])\n\n def test_image_status(self):\n volume = {}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual('active', image_meta['status'])\n\n def test_values_conversion(self):\n properties = {'min_ram': '5', 'min_disk': '7'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(5, image_meta['min_ram'])\n self.assertEqual(7, image_meta['min_disk'])\n\n def test_suppress_not_image_properties(self):\n properties = {'min_ram': '256', 'min_disk': '128', 'image_id':\n 'fake_id', 'image_name': 'fake_name', 'container_format': 'ami',\n 'disk_format': 'ami', 'size': '1234', 'checksum': 'fake_checksum'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual({}, image_meta['properties'])\n self.assertEqual(0, image_meta['size'])\n self.assertNotEqual({}, properties)\n", "step-4": "<mask token>\n\n\nclass BlockDeviceTestCase(test.NoDBTestCase):\n <mask token>\n\n def test_properties(self):\n root_device0 = '/dev/sda'\n root_device1 = '/dev/sdb'\n mappings = [{'virtual': 'root', 'device': root_device0}]\n properties0 = {'mappings': mappings}\n properties1 = {'mappings': mappings, 'root_device_name': root_device1}\n self.assertIsNone(block_device.properties_root_device_name({}))\n self.assertEqual(root_device0, block_device.\n properties_root_device_name(properties0))\n self.assertEqual(root_device1, block_device.\n properties_root_device_name(properties1))\n <mask token>\n\n def test_mappings_prepend_dev(self):\n mapping = [{'virtual': 'ami', 'device': '/dev/sda'}, {'virtual':\n 'root', 'device': 'sda'}, {'virtual': 'ephemeral0', 'device':\n 'sdb'}, {'virtual': 'swap', 'device': 'sdc'}, {'virtual':\n 'ephemeral1', 'device': 'sdd'}, {'virtual': 'ephemeral2',\n 'device': 'sde'}]\n expected = [{'virtual': 'ami', 'device': '/dev/sda'}, {'virtual':\n 'root', 'device': 'sda'}, {'virtual': 'ephemeral0', 'device':\n '/dev/sdb'}, {'virtual': 'swap', 'device': '/dev/sdc'}, {\n 'virtual': 'ephemeral1', 'device': '/dev/sdd'}, {'virtual':\n 'ephemeral2', 'device': '/dev/sde'}]\n prepended = block_device.mappings_prepend_dev(mapping)\n self.assertEqual(sorted(expected, key=lambda v: v['virtual']),\n sorted(prepended, key=lambda v: v['virtual']))\n\n def test_strip_dev(self):\n self.assertEqual('sda', block_device.strip_dev('/dev/sda'))\n self.assertEqual('sda', block_device.strip_dev('sda'))\n self.assertIsNone(block_device.strip_dev(None))\n\n def test_strip_prefix(self):\n self.assertEqual('a', block_device.strip_prefix('/dev/sda'))\n self.assertEqual('a', block_device.strip_prefix('a'))\n self.assertEqual('a', block_device.strip_prefix('xvda'))\n self.assertEqual('a', block_device.strip_prefix('vda'))\n self.assertEqual('a', block_device.strip_prefix('hda'))\n self.assertIsNone(block_device.strip_prefix(None))\n\n def test_get_device_letter(self):\n self.assertEqual('', block_device.get_device_letter(''))\n self.assertEqual('a', block_device.get_device_letter('/dev/sda1'))\n self.assertEqual('b', block_device.get_device_letter('/dev/xvdb'))\n self.assertEqual('d', block_device.get_device_letter('/dev/d'))\n self.assertEqual('a', block_device.get_device_letter('a'))\n self.assertEqual('b', block_device.get_device_letter('sdb2'))\n self.assertEqual('c', block_device.get_device_letter('vdc'))\n self.assertEqual('c', block_device.get_device_letter('hdc'))\n self.assertIsNone(block_device.get_device_letter(None))\n\n def test_generate_device_name(self):\n expected = ('vda', ('vd', 0)), ('vdaa', ('vd', 26)), ('vdabc', (\n 'vd', 730)), ('vdidpok', ('vd', 4194304)), ('sdc', ('sd', 2)), (\n 'sdaa', ('sd', 26)), ('sdiw', ('sd', 256)), ('hdzz', ('hd', 701))\n for res, args in expected:\n self.assertEqual(res, block_device.generate_device_name(*args))\n <mask token>\n\n def test_get_root_bdm(self):\n root_bdm = {'device_name': 'vda', 'boot_index': 0}\n bdms = [root_bdm, {'device_name': 'vdb', 'boot_index': 1}, {\n 'device_name': 'vdc', 'boot_index': -1}, {'device_name': 'vdd'}]\n self.assertEqual(root_bdm, block_device.get_root_bdm(bdms))\n self.assertEqual(root_bdm, block_device.get_root_bdm([bdms[0]]))\n self.assertIsNone(block_device.get_root_bdm(bdms[1:]))\n self.assertIsNone(block_device.get_root_bdm(bdms[2:]))\n self.assertIsNone(block_device.get_root_bdm(bdms[3:]))\n self.assertIsNone(block_device.get_root_bdm([]))\n\n def test_get_bdm_ephemeral_disk_size(self):\n size = block_device.get_bdm_ephemeral_disk_size(self.new_mapping)\n self.assertEqual(10, size)\n <mask token>\n\n def test_get_bdm_local_disk_num(self):\n size = block_device.get_bdm_local_disk_num(self.new_mapping)\n self.assertEqual(2, size)\n\n def test_new_format_is_swap(self):\n expected_results = [True, False, False, False, False]\n for expected, bdm in zip(expected_results, self.new_mapping):\n res = block_device.new_format_is_swap(bdm)\n self.assertEqual(expected, res)\n <mask token>\n\n def test_validate_device_name(self):\n for value in [' ', 10, None, 'a' * 260]:\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n validate_device_name, value)\n <mask token>\n <mask token>\n\n\nclass TestBlockDeviceDict(test.NoDBTestCase):\n\n def setUp(self):\n super(TestBlockDeviceDict, self).setUp()\n BDM = block_device.BlockDeviceDict\n self.api_mapping = [{'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'source_type': 'blank',\n 'destination_type': 'local', 'delete_on_termination': True,\n 'guest_format': 'swap', 'boot_index': -1}, {'id': 2,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1',\n 'source_type': 'blank', 'destination_type': 'local',\n 'delete_on_termination': True, 'boot_index': -1}, {'id': 3,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1',\n 'source_type': 'volume', 'destination_type': 'volume', 'uuid':\n 'fake-volume-id-1', 'boot_index': 0}, {'id': 4, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda2', 'source_type':\n 'snapshot', 'destination_type': 'volume', 'uuid':\n 'fake-snapshot-id-1', 'boot_index': -1}, {'id': 5,\n 'instance_uuid': uuids.instance, 'no_device': True,\n 'device_name': '/dev/vdc'}]\n self.new_mapping = [BDM({'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'source_type': 'blank',\n 'destination_type': 'local', 'delete_on_termination': True,\n 'guest_format': 'swap', 'boot_index': -1}), BDM({'id': 2,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sdc1',\n 'source_type': 'blank', 'destination_type': 'local',\n 'delete_on_termination': True, 'boot_index': -1}), BDM({'id': 3,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda1',\n 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'connection_info':\n \"{'fake': 'connection_info'}\", 'boot_index': 0}), BDM({'id': 4,\n 'instance_uuid': uuids.instance, 'device_name': '/dev/sda2',\n 'source_type': 'snapshot', 'destination_type': 'volume',\n 'connection_info': \"{'fake': 'connection_info'}\", 'snapshot_id':\n 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2',\n 'boot_index': -1}), BDM({'id': 5, 'instance_uuid': uuids.\n instance, 'no_device': True, 'device_name': '/dev/vdc'})]\n self.legacy_mapping = [{'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1', 'delete_on_termination': True,\n 'virtual_name': 'swap'}, {'id': 2, 'instance_uuid': uuids.\n instance, 'device_name': '/dev/sdc1', 'delete_on_termination': \n True, 'virtual_name': 'ephemeral0'}, {'id': 3, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda1', 'volume_id':\n 'fake-volume-id-1', 'connection_info':\n \"{'fake': 'connection_info'}\"}, {'id': 4, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda2', 'connection_info':\n \"{'fake': 'connection_info'}\", 'snapshot_id':\n 'fake-snapshot-id-1', 'volume_id': 'fake-volume-id-2'}, {'id': \n 5, 'instance_uuid': uuids.instance, 'no_device': True,\n 'device_name': '/dev/vdc'}]\n self.new_mapping_source_image = [BDM({'id': 6, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda3', 'source_type':\n 'image', 'destination_type': 'volume', 'connection_info':\n \"{'fake': 'connection_info'}\", 'volume_id': 'fake-volume-id-3',\n 'boot_index': -1}), BDM({'id': 7, 'instance_uuid': uuids.\n instance, 'device_name': '/dev/sda4', 'source_type': 'image',\n 'destination_type': 'local', 'connection_info':\n \"{'fake': 'connection_info'}\", 'image_id': 'fake-image-id-2',\n 'boot_index': -1})]\n self.legacy_mapping_source_image = [{'id': 6, 'instance_uuid':\n uuids.instance, 'device_name': '/dev/sda3', 'connection_info':\n \"{'fake': 'connection_info'}\", 'volume_id': 'fake-volume-id-3'}]\n\n def test_init(self):\n\n def fake_validate(obj, dct):\n pass\n self.stub_out('nova.block_device.BlockDeviceDict._fields', set([\n 'field1', 'field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._db_only_fields',\n set(['db_field1', 'db_field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._validate',\n fake_validate)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo', 'field2':\n 'bar', 'db_field1': 'baz'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'},\n do_not_default=set(['field2']))\n self.assertIn('field1', dev_dict)\n self.assertNotIn('field2', dev_dict)\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n dev_dict = block_device.BlockDeviceDict(field1='foo')\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'}, field2='bar'\n )\n self.assertEqual('foo', dev_dict['field1'])\n self.assertEqual('bar', dev_dict['field2'])\n\n def test_init_prepend_dev_to_device_name(self):\n bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name':\n 'vda', 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vda', bdm_dict['device_name'])\n bdm['device_name'] = '/dev/vdb'\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vdb', bdm_dict['device_name'])\n bdm['device_name'] = None\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertIsNone(bdm_dict['device_name'])\n\n def test_init_boolify_delete_on_termination(self):\n bdm = {'id': 3, 'instance_uuid': uuids.instance, 'device_name':\n 'vda', 'source_type': 'volume', 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertFalse(bdm_dict['delete_on_termination'])\n\n def test_validate(self):\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, {'bogus_field': 'lame_val'})\n lame_bdm = dict(self.new_mapping[2])\n del lame_bdm['source_type']\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_bdm)\n lame_bdm['no_device'] = True\n block_device.BlockDeviceDict(lame_bdm)\n lame_dev_bdm = dict(self.new_mapping[2])\n lame_dev_bdm['device_name'] = 'not a valid name'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_dev_bdm)\n lame_dev_bdm['device_name'] = ''\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_dev_bdm)\n cool_volume_size_bdm = dict(self.new_mapping[2])\n cool_volume_size_bdm['volume_size'] = '42'\n cool_volume_size_bdm = block_device.BlockDeviceDict(\n cool_volume_size_bdm)\n self.assertEqual(42, cool_volume_size_bdm['volume_size'])\n lame_volume_size_bdm = dict(self.new_mapping[2])\n lame_volume_size_bdm['volume_size'] = 'some_non_int_string'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, lame_volume_size_bdm)\n truthy_bdm = dict(self.new_mapping[2])\n truthy_bdm['delete_on_termination'] = '1'\n truthy_bdm = block_device.BlockDeviceDict(truthy_bdm)\n self.assertTrue(truthy_bdm['delete_on_termination'])\n verbose_bdm = dict(self.new_mapping[2])\n verbose_bdm['boot_index'] = 'first'\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict, verbose_bdm)\n\n def test_from_legacy(self):\n for legacy, new in zip(self.legacy_mapping, self.new_mapping):\n self.assertThat(block_device.BlockDeviceDict.from_legacy(legacy\n ), matchers.IsSubDictOf(new))\n\n def test_from_legacy_mapping(self):\n\n def _get_image_bdms(bdms):\n return [bdm for bdm in bdms if bdm['source_type'] == 'image']\n\n def _get_bootable_bdms(bdms):\n return [bdm for bdm in bdms if bdm['boot_index'] is not None and\n bdm['boot_index'] >= 0]\n new_no_img = block_device.from_legacy_mapping(self.legacy_mapping)\n self.assertEqual(0, len(_get_image_bdms(new_no_img)))\n for new, expected in zip(new_no_img, self.new_mapping):\n self.assertThat(new, matchers.IsSubDictOf(expected))\n new_with_img = block_device.from_legacy_mapping(self.legacy_mapping,\n 'fake_image_ref')\n image_bdms = _get_image_bdms(new_with_img)\n boot_bdms = _get_bootable_bdms(new_with_img)\n self.assertEqual(1, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, image_bdms[0]['boot_index'])\n self.assertEqual('image', boot_bdms[0]['source_type'])\n new_with_img_and_root = block_device.from_legacy_mapping(self.\n legacy_mapping, 'fake_image_ref', 'sda1')\n image_bdms = _get_image_bdms(new_with_img_and_root)\n boot_bdms = _get_bootable_bdms(new_with_img_and_root)\n self.assertEqual(0, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, boot_bdms[0]['boot_index'])\n self.assertEqual('volume', boot_bdms[0]['source_type'])\n new_no_root = block_device.from_legacy_mapping(self.legacy_mapping,\n 'fake_image_ref', 'sda1', no_root=True)\n self.assertEqual(0, len(_get_image_bdms(new_no_root)))\n self.assertEqual(0, len(_get_bootable_bdms(new_no_root)))\n\n def test_from_api(self):\n for api, new in zip(self.api_mapping, self.new_mapping):\n new['connection_info'] = None\n if new['snapshot_id']:\n new['volume_id'] = None\n self.assertThat(block_device.BlockDeviceDict.from_api(api, \n False), matchers.IsSubDictOf(new))\n\n def test_from_api_invalid_blank_id(self):\n api_dict = {'id': 1, 'source_type': 'blank', 'destination_type':\n 'volume', 'uuid': 'fake-volume-id-1', 'delete_on_termination': \n True, 'boot_index': -1}\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n\n def test_from_api_invalid_source_to_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1'}\n self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n\n def test_from_api_valid_source_to_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1,\n 'boot_index': 0}\n retexp = block_device.BlockDeviceDict({'id': 1, 'source_type':\n 'image', 'image_id': 1, 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0})\n self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(\n api_dict, True))\n\n def test_from_api_valid_source_to_local_mapping_with_string_bi(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'volume_id': 'fake-volume-id-1', 'uuid': 1,\n 'boot_index': '0'}\n retexp = block_device.BlockDeviceDict({'id': 1, 'source_type':\n 'image', 'image_id': 1, 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1', 'boot_index': 0})\n self.assertEqual(retexp, block_device.BlockDeviceDict.from_api(\n api_dict, True))\n\n def test_from_api_invalid_image_to_destination_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'image', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1', 'volume_type':\n 'fake-lvm-1', 'boot_index': 1}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn('Mapping image to local is not supported', str(ex))\n\n def test_from_api_invalid_volume_type_to_destination_local_mapping(self):\n api_dict = {'id': 1, 'source_type': 'volume', 'destination_type':\n 'local', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn(\n 'Specifying a volume_type with destination_type=local is not supported'\n , str(ex))\n\n def test_from_api_invalid_specify_volume_type_with_source_volume_mapping(\n self):\n api_dict = {'id': 1, 'source_type': 'volume', 'destination_type':\n 'volume', 'uuid': 'fake-volume-id-1', 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat, block_device.\n BlockDeviceDict.from_api, api_dict, False)\n self.assertIn(\n 'Specifying volume type to existing volume is not supported',\n str(ex))\n\n def test_image_mapping(self):\n removed_fields = ['id', 'instance_uuid', 'connection_info',\n 'created_at', 'updated_at', 'deleted_at', 'deleted']\n for bdm in self.new_mapping:\n mapping_bdm = fake_block_device.FakeDbBlockDeviceDict(bdm\n ).get_image_mapping()\n for fld in removed_fields:\n self.assertNotIn(fld, mapping_bdm)\n\n def _test_snapshot_from_bdm(self, template):\n snapshot = block_device.snapshot_from_bdm('new-snapshot-id', template)\n self.assertEqual('new-snapshot-id', snapshot['snapshot_id'])\n self.assertEqual('snapshot', snapshot['source_type'])\n self.assertEqual('volume', snapshot['destination_type'])\n self.assertEqual(template.volume_size, snapshot['volume_size'])\n self.assertEqual(template.delete_on_termination, snapshot[\n 'delete_on_termination'])\n self.assertEqual(template.device_name, snapshot['device_name'])\n for key in ['disk_bus', 'device_type', 'boot_index']:\n self.assertEqual(template[key], snapshot[key])\n\n def test_snapshot_from_bdm(self):\n for bdm in self.new_mapping:\n self._test_snapshot_from_bdm(objects.BlockDeviceMapping(**bdm))\n\n def test_snapshot_from_object(self):\n for bdm in self.new_mapping[:-1]:\n obj = objects.BlockDeviceMapping()\n obj = objects.BlockDeviceMapping._from_db_object(None, obj,\n fake_block_device.FakeDbBlockDeviceDict(bdm))\n self._test_snapshot_from_bdm(obj)\n\n\nclass GetBDMImageMetadataTestCase(test.NoDBTestCase):\n\n def setUp(self):\n super().setUp()\n self.compute_api = compute_api.API()\n self.context = context.RequestContext('fake', 'fake')\n\n def _test_get_bdm_image_metadata__bootable(self, is_bootable=False):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': None, 'volume_id':\n '1', 'delete_on_termination': False}]\n expected_meta = {'min_disk': 0, 'min_ram': 0, 'properties': {},\n 'size': 0, 'status': 'active'}\n\n def get_vol_data(*args, **kwargs):\n return {'bootable': is_bootable}\n with mock.patch.object(self.compute_api.volume_api, 'get',\n side_effect=get_vol_data):\n if not is_bootable:\n self.assertRaises(exception.InvalidBDMVolumeNotBootable,\n block_device.get_bdm_image_metadata, self.context, self\n .compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n else:\n meta = block_device.get_bdm_image_metadata(self.context,\n self.compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(expected_meta, meta)\n\n def test_get_bdm_image_metadata__non_bootable(self):\n self._test_get_bdm_image_metadata__bootable(False)\n\n def test_get_bdm_image_metadata__bootable(self):\n self._test_get_bdm_image_metadata__bootable(True)\n\n def test_get_bdm_image_metadata__basic_property(self):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': None, 'volume_id':\n '1', 'delete_on_termination': False}]\n fake_volume = {'volume_image_metadata': {'min_ram': 256, 'min_disk':\n 128, 'foo': 'bar'}}\n with mock.patch.object(self.compute_api.volume_api, 'get',\n return_value=fake_volume):\n meta = block_device.get_bdm_image_metadata(self.context, self.\n compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n\n def test_get_bdm_image_metadata__snapshot_basic_property(self):\n block_device_mapping = [{'id': 1, 'device_name': 'vda', 'no_device':\n None, 'virtual_name': None, 'snapshot_id': '2', 'volume_id':\n None, 'delete_on_termination': False}]\n fake_volume = {'volume_image_metadata': {'min_ram': 256, 'min_disk':\n 128, 'foo': 'bar'}}\n fake_snapshot = {'volume_id': '1'}\n with test.nested(mock.patch.object(self.compute_api.volume_api,\n 'get', return_value=fake_volume), mock.patch.object(self.\n compute_api.volume_api, 'get_snapshot', return_value=fake_snapshot)\n ) as (volume_get, volume_get_snapshot):\n meta = block_device.get_bdm_image_metadata(self.context, self.\n compute_api.image_api, self.compute_api.volume_api,\n block_device_mapping)\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n volume_get_snapshot.assert_called_once_with(self.context,\n block_device_mapping[0]['snapshot_id'])\n volume_get.assert_called_once_with(self.context, fake_snapshot[\n 'volume_id'])\n\n @mock.patch.object(cinder.API, 'get', side_effect=exception.\n CinderConnectionFailed(reason='error'))\n def test_get_bdm_image_metadata__cinder_down(self, mock_get):\n bdms = [objects.BlockDeviceMapping(**fake_block_device.\n FakeDbBlockDeviceDict({'id': 1, 'volume_id': 1, 'source_type':\n 'volume', 'destination_type': 'volume', 'device_name': 'vda'}))]\n self.assertRaises(exception.CinderConnectionFailed, block_device.\n get_bdm_image_metadata, self.context, self.compute_api.\n image_api, self.compute_api.volume_api, bdms, legacy_bdm=True)\n\n\nclass GetImageMetadataFromVolumeTestCase(test.NoDBTestCase):\n\n def test_inherit_image_properties(self):\n properties = {'fake_prop': 'fake_value'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(properties, image_meta['properties'])\n\n def test_image_size(self):\n volume = {'size': 10}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(10 * units.Gi, image_meta['size'])\n\n def test_image_status(self):\n volume = {}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual('active', image_meta['status'])\n\n def test_values_conversion(self):\n properties = {'min_ram': '5', 'min_disk': '7'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(5, image_meta['min_ram'])\n self.assertEqual(7, image_meta['min_disk'])\n\n def test_suppress_not_image_properties(self):\n properties = {'min_ram': '256', 'min_disk': '128', 'image_id':\n 'fake_id', 'image_name': 'fake_name', 'container_format': 'ami',\n 'disk_format': 'ami', 'size': '1234', 'checksum': 'fake_checksum'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual({}, image_meta['properties'])\n self.assertEqual(0, image_meta['size'])\n self.assertNotEqual({}, properties)\n", "step-5": "# Copyright 2011 Isaku Yamahata\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nTests for Block Device utility functions.\n\"\"\"\n\nfrom unittest import mock\n\nfrom oslo_utils.fixture import uuidsentinel as uuids\nfrom oslo_utils import units\n\nfrom nova import block_device\nfrom nova.compute import api as compute_api\nfrom nova import context\nfrom nova import exception\nfrom nova import objects\nfrom nova import test\nfrom nova.tests.unit import fake_block_device\nfrom nova.tests.unit import matchers\nfrom nova.volume import cinder\n\n\nclass BlockDeviceTestCase(test.NoDBTestCase):\n def setUp(self):\n super(BlockDeviceTestCase, self).setUp()\n BDM = block_device.BlockDeviceDict\n\n self.new_mapping = [\n BDM({'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1',\n 'source_type': 'blank',\n 'destination_type': 'local',\n 'delete_on_termination': True,\n 'volume_size': 1,\n 'guest_format': 'swap',\n 'boot_index': -1}),\n BDM({'id': 2, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdc1',\n 'source_type': 'blank',\n 'destination_type': 'local',\n 'volume_size': 10,\n 'delete_on_termination': True,\n 'boot_index': -1}),\n BDM({'id': 3, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda1',\n 'source_type': 'volume',\n 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1',\n 'connection_info': \"{'fake': 'connection_info'}\",\n 'boot_index': 0}),\n BDM({'id': 4, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda2',\n 'source_type': 'snapshot',\n 'destination_type': 'volume',\n 'connection_info': \"{'fake': 'connection_info'}\",\n 'snapshot_id': 'fake-snapshot-id-1',\n 'volume_id': 'fake-volume-id-2',\n 'boot_index': -1}),\n BDM({'id': 5, 'instance_uuid': uuids.instance,\n 'no_device': True,\n 'device_name': '/dev/vdc'}),\n ]\n\n def test_properties(self):\n root_device0 = '/dev/sda'\n root_device1 = '/dev/sdb'\n mappings = [{'virtual': 'root',\n 'device': root_device0}]\n\n properties0 = {'mappings': mappings}\n properties1 = {'mappings': mappings,\n 'root_device_name': root_device1}\n\n self.assertIsNone(block_device.properties_root_device_name({}))\n self.assertEqual(root_device0,\n block_device.properties_root_device_name(properties0))\n self.assertEqual(root_device1,\n block_device.properties_root_device_name(properties1))\n\n def test_ephemeral(self):\n self.assertFalse(block_device.is_ephemeral('ephemeral'))\n self.assertTrue(block_device.is_ephemeral('ephemeral0'))\n self.assertTrue(block_device.is_ephemeral('ephemeral1'))\n self.assertTrue(block_device.is_ephemeral('ephemeral11'))\n self.assertFalse(block_device.is_ephemeral('root'))\n self.assertFalse(block_device.is_ephemeral('swap'))\n self.assertFalse(block_device.is_ephemeral('/dev/sda1'))\n\n self.assertEqual(0, block_device.ephemeral_num('ephemeral0'))\n self.assertEqual(1, block_device.ephemeral_num('ephemeral1'))\n self.assertEqual(11, block_device.ephemeral_num('ephemeral11'))\n\n self.assertFalse(block_device.is_swap_or_ephemeral('ephemeral'))\n self.assertTrue(block_device.is_swap_or_ephemeral('ephemeral0'))\n self.assertTrue(block_device.is_swap_or_ephemeral('ephemeral1'))\n self.assertTrue(block_device.is_swap_or_ephemeral('swap'))\n self.assertFalse(block_device.is_swap_or_ephemeral('root'))\n self.assertFalse(block_device.is_swap_or_ephemeral('/dev/sda1'))\n\n def test_mappings_prepend_dev(self):\n mapping = [\n {'virtual': 'ami', 'device': '/dev/sda'},\n {'virtual': 'root', 'device': 'sda'},\n {'virtual': 'ephemeral0', 'device': 'sdb'},\n {'virtual': 'swap', 'device': 'sdc'},\n {'virtual': 'ephemeral1', 'device': 'sdd'},\n {'virtual': 'ephemeral2', 'device': 'sde'}]\n\n expected = [\n {'virtual': 'ami', 'device': '/dev/sda'},\n {'virtual': 'root', 'device': 'sda'},\n {'virtual': 'ephemeral0', 'device': '/dev/sdb'},\n {'virtual': 'swap', 'device': '/dev/sdc'},\n {'virtual': 'ephemeral1', 'device': '/dev/sdd'},\n {'virtual': 'ephemeral2', 'device': '/dev/sde'}]\n\n prepended = block_device.mappings_prepend_dev(mapping)\n self.assertEqual(sorted(expected, key=lambda v: v['virtual']),\n sorted(prepended, key=lambda v: v['virtual']))\n\n def test_strip_dev(self):\n self.assertEqual('sda', block_device.strip_dev('/dev/sda'))\n self.assertEqual('sda', block_device.strip_dev('sda'))\n self.assertIsNone(block_device.strip_dev(None))\n\n def test_strip_prefix(self):\n self.assertEqual('a', block_device.strip_prefix('/dev/sda'))\n self.assertEqual('a', block_device.strip_prefix('a'))\n self.assertEqual('a', block_device.strip_prefix('xvda'))\n self.assertEqual('a', block_device.strip_prefix('vda'))\n self.assertEqual('a', block_device.strip_prefix('hda'))\n self.assertIsNone(block_device.strip_prefix(None))\n\n def test_get_device_letter(self):\n self.assertEqual('', block_device.get_device_letter(''))\n self.assertEqual('a', block_device.get_device_letter('/dev/sda1'))\n self.assertEqual('b', block_device.get_device_letter('/dev/xvdb'))\n self.assertEqual('d', block_device.get_device_letter('/dev/d'))\n self.assertEqual('a', block_device.get_device_letter('a'))\n self.assertEqual('b', block_device.get_device_letter('sdb2'))\n self.assertEqual('c', block_device.get_device_letter('vdc'))\n self.assertEqual('c', block_device.get_device_letter('hdc'))\n self.assertIsNone(block_device.get_device_letter(None))\n\n def test_generate_device_name(self):\n expected = (\n ('vda', (\"vd\", 0)),\n ('vdaa', (\"vd\", 26)),\n ('vdabc', (\"vd\", 730)),\n ('vdidpok', (\"vd\", 4194304)),\n ('sdc', (\"sd\", 2)),\n ('sdaa', (\"sd\", 26)),\n ('sdiw', (\"sd\", 256)),\n ('hdzz', (\"hd\", 701))\n )\n for res, args in expected:\n self.assertEqual(res, block_device.generate_device_name(*args))\n\n def test_volume_in_mapping(self):\n swap = {'device_name': '/dev/sdb',\n 'swap_size': 1}\n ephemerals = [{'num': 0,\n 'virtual_name': 'ephemeral0',\n 'device_name': '/dev/sdc1',\n 'size': 1},\n {'num': 2,\n 'virtual_name': 'ephemeral2',\n 'device_name': '/dev/sdd',\n 'size': 1}]\n block_device_mapping = [{'mount_device': '/dev/sde',\n 'device_path': 'fake_device'},\n {'mount_device': '/dev/sdf',\n 'device_path': 'fake_device'}]\n block_device_info = {\n 'root_device_name': '/dev/sda',\n 'swap': swap,\n 'ephemerals': ephemerals,\n 'block_device_mapping': block_device_mapping}\n\n def _assert_volume_in_mapping(device_name, true_or_false):\n in_mapping = block_device.volume_in_mapping(\n device_name, block_device_info)\n self.assertEqual(true_or_false, in_mapping)\n\n _assert_volume_in_mapping('sda', False)\n _assert_volume_in_mapping('sdb', True)\n _assert_volume_in_mapping('sdc1', True)\n _assert_volume_in_mapping('sdd', True)\n _assert_volume_in_mapping('sde', True)\n _assert_volume_in_mapping('sdf', True)\n _assert_volume_in_mapping('sdg', False)\n _assert_volume_in_mapping('sdh1', False)\n\n def test_get_root_bdm(self):\n root_bdm = {'device_name': 'vda', 'boot_index': 0}\n bdms = [root_bdm,\n {'device_name': 'vdb', 'boot_index': 1},\n {'device_name': 'vdc', 'boot_index': -1},\n {'device_name': 'vdd'}]\n self.assertEqual(root_bdm, block_device.get_root_bdm(bdms))\n self.assertEqual(root_bdm, block_device.get_root_bdm([bdms[0]]))\n self.assertIsNone(block_device.get_root_bdm(bdms[1:]))\n self.assertIsNone(block_device.get_root_bdm(bdms[2:]))\n self.assertIsNone(block_device.get_root_bdm(bdms[3:]))\n self.assertIsNone(block_device.get_root_bdm([]))\n\n def test_get_bdm_ephemeral_disk_size(self):\n size = block_device.get_bdm_ephemeral_disk_size(self.new_mapping)\n self.assertEqual(10, size)\n\n def test_get_bdm_swap_list(self):\n swap_list = block_device.get_bdm_swap_list(self.new_mapping)\n self.assertEqual(1, len(swap_list))\n self.assertEqual(1, swap_list[0].get('id'))\n\n def test_get_bdm_local_disk_num(self):\n size = block_device.get_bdm_local_disk_num(self.new_mapping)\n self.assertEqual(2, size)\n\n def test_new_format_is_swap(self):\n expected_results = [True, False, False, False, False]\n for expected, bdm in zip(expected_results, self.new_mapping):\n res = block_device.new_format_is_swap(bdm)\n self.assertEqual(expected, res)\n\n def test_new_format_is_ephemeral(self):\n expected_results = [False, True, False, False, False]\n for expected, bdm in zip(expected_results, self.new_mapping):\n res = block_device.new_format_is_ephemeral(bdm)\n self.assertEqual(expected, res)\n\n def test_validate_device_name(self):\n for value in [' ', 10, None, 'a' * 260]:\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.validate_device_name,\n value)\n\n def test_validate_and_default_volume_size(self):\n bdm = {}\n for value in [-1, 'a', 2.5]:\n bdm['volume_size'] = value\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.validate_and_default_volume_size,\n bdm)\n\n def test_get_bdms_to_connect(self):\n root_bdm = {'device_name': 'vda', 'boot_index': 0}\n bdms = [root_bdm,\n {'device_name': 'vdb', 'boot_index': 1},\n {'device_name': 'vdc', 'boot_index': -1},\n {'device_name': 'vde', 'boot_index': None},\n {'device_name': 'vdd'}]\n self.assertNotIn(root_bdm, block_device.get_bdms_to_connect(bdms,\n exclude_root_mapping=True))\n self.assertIn(root_bdm, block_device.get_bdms_to_connect(bdms))\n\n\nclass TestBlockDeviceDict(test.NoDBTestCase):\n def setUp(self):\n super(TestBlockDeviceDict, self).setUp()\n\n BDM = block_device.BlockDeviceDict\n\n self.api_mapping = [\n {'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1',\n 'source_type': 'blank',\n 'destination_type': 'local',\n 'delete_on_termination': True,\n 'guest_format': 'swap',\n 'boot_index': -1},\n {'id': 2, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdc1',\n 'source_type': 'blank',\n 'destination_type': 'local',\n 'delete_on_termination': True,\n 'boot_index': -1},\n {'id': 3, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda1',\n 'source_type': 'volume',\n 'destination_type': 'volume',\n 'uuid': 'fake-volume-id-1',\n 'boot_index': 0},\n {'id': 4, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda2',\n 'source_type': 'snapshot',\n 'destination_type': 'volume',\n 'uuid': 'fake-snapshot-id-1',\n 'boot_index': -1},\n {'id': 5, 'instance_uuid': uuids.instance,\n 'no_device': True,\n 'device_name': '/dev/vdc'},\n ]\n\n self.new_mapping = [\n BDM({'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1',\n 'source_type': 'blank',\n 'destination_type': 'local',\n 'delete_on_termination': True,\n 'guest_format': 'swap',\n 'boot_index': -1}),\n BDM({'id': 2, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdc1',\n 'source_type': 'blank',\n 'destination_type': 'local',\n 'delete_on_termination': True,\n 'boot_index': -1}),\n BDM({'id': 3, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda1',\n 'source_type': 'volume',\n 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1',\n 'connection_info': \"{'fake': 'connection_info'}\",\n 'boot_index': 0}),\n BDM({'id': 4, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda2',\n 'source_type': 'snapshot',\n 'destination_type': 'volume',\n 'connection_info': \"{'fake': 'connection_info'}\",\n 'snapshot_id': 'fake-snapshot-id-1',\n 'volume_id': 'fake-volume-id-2',\n 'boot_index': -1}),\n BDM({'id': 5, 'instance_uuid': uuids.instance,\n 'no_device': True,\n 'device_name': '/dev/vdc'}),\n ]\n\n self.legacy_mapping = [\n {'id': 1, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdb1',\n 'delete_on_termination': True,\n 'virtual_name': 'swap'},\n {'id': 2, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sdc1',\n 'delete_on_termination': True,\n 'virtual_name': 'ephemeral0'},\n {'id': 3, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda1',\n 'volume_id': 'fake-volume-id-1',\n 'connection_info': \"{'fake': 'connection_info'}\"},\n {'id': 4, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda2',\n 'connection_info': \"{'fake': 'connection_info'}\",\n 'snapshot_id': 'fake-snapshot-id-1',\n 'volume_id': 'fake-volume-id-2'},\n {'id': 5, 'instance_uuid': uuids.instance,\n 'no_device': True,\n 'device_name': '/dev/vdc'},\n ]\n\n self.new_mapping_source_image = [\n BDM({'id': 6, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda3',\n 'source_type': 'image',\n 'destination_type': 'volume',\n 'connection_info': \"{'fake': 'connection_info'}\",\n 'volume_id': 'fake-volume-id-3',\n 'boot_index': -1}),\n BDM({'id': 7, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda4',\n 'source_type': 'image',\n 'destination_type': 'local',\n 'connection_info': \"{'fake': 'connection_info'}\",\n 'image_id': 'fake-image-id-2',\n 'boot_index': -1}),\n ]\n\n self.legacy_mapping_source_image = [\n {'id': 6, 'instance_uuid': uuids.instance,\n 'device_name': '/dev/sda3',\n 'connection_info': \"{'fake': 'connection_info'}\",\n 'volume_id': 'fake-volume-id-3'},\n ]\n\n def test_init(self):\n def fake_validate(obj, dct):\n pass\n\n self.stub_out('nova.block_device.BlockDeviceDict._fields',\n set(['field1', 'field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._db_only_fields',\n set(['db_field1', 'db_field2']))\n self.stub_out('nova.block_device.BlockDeviceDict._validate',\n fake_validate)\n\n # Make sure db fields are not picked up if they are not\n # in the original dict\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo',\n 'field2': 'bar',\n 'db_field1': 'baz'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n\n # Make sure all expected fields are defaulted\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'})\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n\n # Unless they are not meant to be\n dev_dict = block_device.BlockDeviceDict({'field1': 'foo'},\n do_not_default=set(['field2']))\n self.assertIn('field1', dev_dict)\n self.assertNotIn('field2', dev_dict)\n self.assertNotIn('db_field1', dev_dict)\n self.assertNotIn('db_field2', dev_dict)\n\n # Passing kwargs to constructor works\n dev_dict = block_device.BlockDeviceDict(field1='foo')\n self.assertIn('field1', dev_dict)\n self.assertIn('field2', dev_dict)\n self.assertIsNone(dev_dict['field2'])\n dev_dict = block_device.BlockDeviceDict(\n {'field1': 'foo'}, field2='bar')\n self.assertEqual('foo', dev_dict['field1'])\n self.assertEqual('bar', dev_dict['field2'])\n\n def test_init_prepend_dev_to_device_name(self):\n bdm = {'id': 3, 'instance_uuid': uuids.instance,\n 'device_name': 'vda',\n 'source_type': 'volume',\n 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1',\n 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vda', bdm_dict['device_name'])\n\n bdm['device_name'] = '/dev/vdb'\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertEqual('/dev/vdb', bdm_dict['device_name'])\n\n bdm['device_name'] = None\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertIsNone(bdm_dict['device_name'])\n\n def test_init_boolify_delete_on_termination(self):\n # Make sure that when delete_on_termination is not passed it's\n # still set to False and not None\n bdm = {'id': 3, 'instance_uuid': uuids.instance,\n 'device_name': 'vda',\n 'source_type': 'volume',\n 'destination_type': 'volume',\n 'volume_id': 'fake-volume-id-1',\n 'boot_index': 0}\n bdm_dict = block_device.BlockDeviceDict(bdm)\n self.assertFalse(bdm_dict['delete_on_termination'])\n\n def test_validate(self):\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict,\n {'bogus_field': 'lame_val'})\n\n lame_bdm = dict(self.new_mapping[2])\n del lame_bdm['source_type']\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict,\n lame_bdm)\n\n lame_bdm['no_device'] = True\n block_device.BlockDeviceDict(lame_bdm)\n\n lame_dev_bdm = dict(self.new_mapping[2])\n lame_dev_bdm['device_name'] = \"not a valid name\"\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict,\n lame_dev_bdm)\n\n lame_dev_bdm['device_name'] = \"\"\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict,\n lame_dev_bdm)\n\n cool_volume_size_bdm = dict(self.new_mapping[2])\n cool_volume_size_bdm['volume_size'] = '42'\n cool_volume_size_bdm = block_device.BlockDeviceDict(\n cool_volume_size_bdm)\n self.assertEqual(42, cool_volume_size_bdm['volume_size'])\n\n lame_volume_size_bdm = dict(self.new_mapping[2])\n lame_volume_size_bdm['volume_size'] = 'some_non_int_string'\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict,\n lame_volume_size_bdm)\n\n truthy_bdm = dict(self.new_mapping[2])\n truthy_bdm['delete_on_termination'] = '1'\n truthy_bdm = block_device.BlockDeviceDict(truthy_bdm)\n self.assertTrue(truthy_bdm['delete_on_termination'])\n\n verbose_bdm = dict(self.new_mapping[2])\n verbose_bdm['boot_index'] = 'first'\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict,\n verbose_bdm)\n\n def test_from_legacy(self):\n for legacy, new in zip(self.legacy_mapping, self.new_mapping):\n self.assertThat(\n block_device.BlockDeviceDict.from_legacy(legacy),\n matchers.IsSubDictOf(new))\n\n def test_from_legacy_mapping(self):\n def _get_image_bdms(bdms):\n return [bdm for bdm in bdms if bdm['source_type'] == 'image']\n\n def _get_bootable_bdms(bdms):\n return [bdm for bdm in bdms\n if (bdm['boot_index'] is not None and\n bdm['boot_index'] >= 0)]\n\n new_no_img = block_device.from_legacy_mapping(self.legacy_mapping)\n self.assertEqual(0, len(_get_image_bdms(new_no_img)))\n\n for new, expected in zip(new_no_img, self.new_mapping):\n self.assertThat(new, matchers.IsSubDictOf(expected))\n\n new_with_img = block_device.from_legacy_mapping(\n self.legacy_mapping, 'fake_image_ref')\n image_bdms = _get_image_bdms(new_with_img)\n boot_bdms = _get_bootable_bdms(new_with_img)\n self.assertEqual(1, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, image_bdms[0]['boot_index'])\n self.assertEqual('image', boot_bdms[0]['source_type'])\n\n new_with_img_and_root = block_device.from_legacy_mapping(\n self.legacy_mapping, 'fake_image_ref', 'sda1')\n image_bdms = _get_image_bdms(new_with_img_and_root)\n boot_bdms = _get_bootable_bdms(new_with_img_and_root)\n self.assertEqual(0, len(image_bdms))\n self.assertEqual(1, len(boot_bdms))\n self.assertEqual(0, boot_bdms[0]['boot_index'])\n self.assertEqual('volume', boot_bdms[0]['source_type'])\n\n new_no_root = block_device.from_legacy_mapping(\n self.legacy_mapping, 'fake_image_ref', 'sda1', no_root=True)\n self.assertEqual(0, len(_get_image_bdms(new_no_root)))\n self.assertEqual(0, len(_get_bootable_bdms(new_no_root)))\n\n def test_from_api(self):\n for api, new in zip(self.api_mapping, self.new_mapping):\n new['connection_info'] = None\n if new['snapshot_id']:\n new['volume_id'] = None\n self.assertThat(\n block_device.BlockDeviceDict.from_api(api, False),\n matchers.IsSubDictOf(new))\n\n def test_from_api_invalid_blank_id(self):\n api_dict = {'id': 1,\n 'source_type': 'blank',\n 'destination_type': 'volume',\n 'uuid': 'fake-volume-id-1',\n 'delete_on_termination': True,\n 'boot_index': -1}\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict.from_api, api_dict,\n False)\n\n def test_from_api_invalid_source_to_local_mapping(self):\n api_dict = {'id': 1,\n 'source_type': 'image',\n 'destination_type': 'local',\n 'uuid': 'fake-volume-id-1'}\n self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict.from_api, api_dict,\n False)\n\n def test_from_api_valid_source_to_local_mapping(self):\n api_dict = {'id': 1,\n 'source_type': 'image',\n 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1',\n 'uuid': 1,\n 'boot_index': 0}\n\n retexp = block_device.BlockDeviceDict(\n {'id': 1,\n 'source_type': 'image',\n 'image_id': 1,\n 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1',\n 'boot_index': 0})\n self.assertEqual(retexp,\n block_device.BlockDeviceDict.from_api(api_dict, True))\n\n def test_from_api_valid_source_to_local_mapping_with_string_bi(self):\n api_dict = {'id': 1,\n 'source_type': 'image',\n 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1',\n 'uuid': 1,\n 'boot_index': '0'}\n\n retexp = block_device.BlockDeviceDict(\n {'id': 1,\n 'source_type': 'image',\n 'image_id': 1,\n 'destination_type': 'local',\n 'volume_id': 'fake-volume-id-1',\n 'boot_index': 0})\n self.assertEqual(retexp,\n block_device.BlockDeviceDict.from_api(api_dict, True))\n\n def test_from_api_invalid_image_to_destination_local_mapping(self):\n api_dict = {'id': 1,\n 'source_type': 'image',\n 'destination_type': 'local',\n 'uuid': 'fake-volume-id-1',\n 'volume_type': 'fake-lvm-1',\n 'boot_index': 1}\n ex = self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict.from_api,\n api_dict, False)\n self.assertIn('Mapping image to local is not supported', str(ex))\n\n def test_from_api_invalid_volume_type_to_destination_local_mapping(self):\n api_dict = {'id': 1,\n 'source_type': 'volume',\n 'destination_type': 'local',\n 'uuid': 'fake-volume-id-1',\n 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict.from_api,\n api_dict, False)\n self.assertIn('Specifying a volume_type with destination_type=local '\n 'is not supported', str(ex))\n\n def test_from_api_invalid_specify_volume_type_with_source_volume_mapping(\n self):\n api_dict = {'id': 1,\n 'source_type': 'volume',\n 'destination_type': 'volume',\n 'uuid': 'fake-volume-id-1',\n 'volume_type': 'fake-lvm-1'}\n ex = self.assertRaises(exception.InvalidBDMFormat,\n block_device.BlockDeviceDict.from_api,\n api_dict, False)\n self.assertIn('Specifying volume type to existing volume is '\n 'not supported', str(ex))\n\n def test_image_mapping(self):\n removed_fields = ['id', 'instance_uuid', 'connection_info',\n 'created_at', 'updated_at', 'deleted_at', 'deleted']\n for bdm in self.new_mapping:\n mapping_bdm = fake_block_device.FakeDbBlockDeviceDict(\n bdm).get_image_mapping()\n for fld in removed_fields:\n self.assertNotIn(fld, mapping_bdm)\n\n def _test_snapshot_from_bdm(self, template):\n snapshot = block_device.snapshot_from_bdm('new-snapshot-id', template)\n self.assertEqual('new-snapshot-id', snapshot['snapshot_id'])\n self.assertEqual('snapshot', snapshot['source_type'])\n self.assertEqual('volume', snapshot['destination_type'])\n self.assertEqual(template.volume_size, snapshot['volume_size'])\n self.assertEqual(template.delete_on_termination,\n snapshot['delete_on_termination'])\n self.assertEqual(template.device_name, snapshot['device_name'])\n for key in ['disk_bus', 'device_type', 'boot_index']:\n self.assertEqual(template[key], snapshot[key])\n\n def test_snapshot_from_bdm(self):\n for bdm in self.new_mapping:\n self._test_snapshot_from_bdm(objects.BlockDeviceMapping(**bdm))\n\n def test_snapshot_from_object(self):\n for bdm in self.new_mapping[:-1]:\n obj = objects.BlockDeviceMapping()\n obj = objects.BlockDeviceMapping._from_db_object(\n None, obj, fake_block_device.FakeDbBlockDeviceDict(\n bdm))\n self._test_snapshot_from_bdm(obj)\n\n\nclass GetBDMImageMetadataTestCase(test.NoDBTestCase):\n\n def setUp(self):\n super().setUp()\n self.compute_api = compute_api.API()\n self.context = context.RequestContext('fake', 'fake')\n\n def _test_get_bdm_image_metadata__bootable(self, is_bootable=False):\n block_device_mapping = [{\n 'id': 1,\n 'device_name': 'vda',\n 'no_device': None,\n 'virtual_name': None,\n 'snapshot_id': None,\n 'volume_id': '1',\n 'delete_on_termination': False,\n }]\n\n expected_meta = {\n 'min_disk': 0, 'min_ram': 0, 'properties': {}, 'size': 0,\n 'status': 'active',\n }\n\n def get_vol_data(*args, **kwargs):\n return {'bootable': is_bootable}\n\n with mock.patch.object(\n self.compute_api.volume_api, 'get', side_effect=get_vol_data,\n ):\n if not is_bootable:\n self.assertRaises(\n exception.InvalidBDMVolumeNotBootable,\n block_device.get_bdm_image_metadata,\n self.context,\n self.compute_api.image_api,\n self.compute_api.volume_api,\n block_device_mapping)\n else:\n meta = block_device.get_bdm_image_metadata(\n self.context, self.compute_api.image_api,\n self.compute_api.volume_api, block_device_mapping)\n self.assertEqual(expected_meta, meta)\n\n def test_get_bdm_image_metadata__non_bootable(self):\n self._test_get_bdm_image_metadata__bootable(False)\n\n def test_get_bdm_image_metadata__bootable(self):\n self._test_get_bdm_image_metadata__bootable(True)\n\n def test_get_bdm_image_metadata__basic_property(self):\n block_device_mapping = [{\n 'id': 1,\n 'device_name': 'vda',\n 'no_device': None,\n 'virtual_name': None,\n 'snapshot_id': None,\n 'volume_id': '1',\n 'delete_on_termination': False,\n }]\n fake_volume = {\n 'volume_image_metadata': {\n 'min_ram': 256, 'min_disk': 128, 'foo': 'bar',\n },\n }\n with mock.patch.object(\n self.compute_api.volume_api, 'get', return_value=fake_volume,\n ):\n meta = block_device.get_bdm_image_metadata(\n self.context, self.compute_api.image_api,\n self.compute_api.volume_api, block_device_mapping)\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n\n def test_get_bdm_image_metadata__snapshot_basic_property(self):\n block_device_mapping = [{\n 'id': 1,\n 'device_name': 'vda',\n 'no_device': None,\n 'virtual_name': None,\n 'snapshot_id': '2',\n 'volume_id': None,\n 'delete_on_termination': False,\n }]\n fake_volume = {\n 'volume_image_metadata': {\n 'min_ram': 256, 'min_disk': 128, 'foo': 'bar',\n },\n }\n fake_snapshot = {'volume_id': '1'}\n with test.nested(\n mock.patch.object(\n self.compute_api.volume_api, 'get',\n return_value=fake_volume),\n mock.patch.object(\n self.compute_api.volume_api, 'get_snapshot',\n return_value=fake_snapshot),\n ) as (volume_get, volume_get_snapshot):\n meta = block_device.get_bdm_image_metadata(\n self.context, self.compute_api.image_api,\n self.compute_api.volume_api, block_device_mapping)\n\n self.assertEqual(256, meta['min_ram'])\n self.assertEqual(128, meta['min_disk'])\n self.assertEqual('active', meta['status'])\n self.assertEqual('bar', meta['properties']['foo'])\n volume_get_snapshot.assert_called_once_with(\n self.context, block_device_mapping[0]['snapshot_id'])\n volume_get.assert_called_once_with(\n self.context, fake_snapshot['volume_id'])\n\n @mock.patch.object(\n cinder.API, 'get',\n side_effect=exception.CinderConnectionFailed(reason='error'))\n def test_get_bdm_image_metadata__cinder_down(self, mock_get):\n bdms = [\n objects.BlockDeviceMapping(\n **fake_block_device.FakeDbBlockDeviceDict({\n 'id': 1,\n 'volume_id': 1,\n 'source_type': 'volume',\n 'destination_type': 'volume',\n 'device_name': 'vda',\n })\n )\n ]\n self.assertRaises(\n exception.CinderConnectionFailed,\n block_device.get_bdm_image_metadata,\n self.context,\n self.compute_api.image_api,\n self.compute_api.volume_api,\n bdms, legacy_bdm=True)\n\n\nclass GetImageMetadataFromVolumeTestCase(test.NoDBTestCase):\n def test_inherit_image_properties(self):\n properties = {'fake_prop': 'fake_value'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(properties, image_meta['properties'])\n\n def test_image_size(self):\n volume = {'size': 10}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(10 * units.Gi, image_meta['size'])\n\n def test_image_status(self):\n volume = {}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual('active', image_meta['status'])\n\n def test_values_conversion(self):\n properties = {'min_ram': '5', 'min_disk': '7'}\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual(5, image_meta['min_ram'])\n self.assertEqual(7, image_meta['min_disk'])\n\n def test_suppress_not_image_properties(self):\n properties = {\n 'min_ram': '256', 'min_disk': '128', 'image_id': 'fake_id',\n 'image_name': 'fake_name', 'container_format': 'ami',\n 'disk_format': 'ami', 'size': '1234', 'checksum': 'fake_checksum',\n }\n volume = {'volume_image_metadata': properties}\n image_meta = block_device.get_image_metadata_from_volume(volume)\n self.assertEqual({}, image_meta['properties'])\n self.assertEqual(0, image_meta['size'])\n # volume's properties should not be touched\n self.assertNotEqual({}, properties)\n", "step-ids": [ 37, 38, 43, 46, 55 ] }
[ 37, 38, 43, 46, 55 ]
from django.apps import AppConfig class ModuloConfig(AppConfig): name = 'modulo' verbose_name = 'TUM:JungeAkademie - Modulo' def ready(self): #start-up / initialization code here!!! from .recommender import Recommender Recommender.initialize()
normal
{ "blob_id": "31275ca9e20da9d2709ea396e55c113b3ff4f571", "index": 7738, "step-1": "<mask token>\n\n\nclass ModuloConfig(AppConfig):\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass ModuloConfig(AppConfig):\n <mask token>\n <mask token>\n\n def ready(self):\n from .recommender import Recommender\n Recommender.initialize()\n", "step-3": "<mask token>\n\n\nclass ModuloConfig(AppConfig):\n name = 'modulo'\n verbose_name = 'TUM:JungeAkademie - Modulo'\n\n def ready(self):\n from .recommender import Recommender\n Recommender.initialize()\n", "step-4": "from django.apps import AppConfig\n\n\nclass ModuloConfig(AppConfig):\n name = 'modulo'\n verbose_name = 'TUM:JungeAkademie - Modulo'\n\n def ready(self):\n from .recommender import Recommender\n Recommender.initialize()\n", "step-5": "from django.apps import AppConfig\n\n\nclass ModuloConfig(AppConfig):\n name = 'modulo'\n verbose_name = 'TUM:JungeAkademie - Modulo'\n \n def ready(self):\n #start-up / initialization code here!!!\n from .recommender import Recommender\n Recommender.initialize()", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> class LogoutSerializer(ModelSerializer): <|reserved_special_token_0|> <|reserved_special_token_0|> class Meta: model = DeviceUser fields = ['device_user_token', 'device_os', 'is_active'] <|reserved_special_token_0|> <|reserved_special_token_0|> class UserSettingsSerializer(serializers.ModelSerializer): class Meta: model = UserSettings fields = ('id', 'session_confirm', 'message', 'session_cancellation', 'location_change', 'session_reminder', 'available', 'push_notifications_enabled') class UserProfileDetailSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() settings = UserSettingsSerializer() class Meta: model = User fields = ('id', 'username', 'name', 'last_name', 'second_last_name', 'description', 'photo', 'email', 'phone', 'zip_code', 'birthday', 'gender', 'is_student', 'is_teacher', 'token', 'settings') def get_token(self, obj): """ Create token. """ return create_token(obj) class LoginResponseV2Serializer(serializers.ModelSerializer): """ Serializer used to return the proper token, when the user was succesfully logged in. """ token = serializers.SerializerMethodField() class Meta: model = User fields = 'token', def get_token(self, obj): """ Create token. """ return create_token(obj) <|reserved_special_token_1|> <|reserved_special_token_0|> class LogoutSerializer(ModelSerializer): <|reserved_special_token_0|> <|reserved_special_token_0|> class Meta: model = DeviceUser fields = ['device_user_token', 'device_os', 'is_active'] def validate(self, data): """ Validate that the requesting user owns the given device. """ request = self.context['request'] data.setdefault('user', request.user) data.setdefault('device_user_token', None) if not request.user.is_authenticated(): raise serializers.ValidationError('user is not logged in.') try: self.instance = DeviceUser.objects.get(**data) except DeviceUser.DoesNotExist: raise serializers.ValidationError('invalid device') return data def update(self): """ Mark the given device as inactive. """ self.instance.is_active = False self.instance.save() return self.instance class UserSettingsSerializer(serializers.ModelSerializer): class Meta: model = UserSettings fields = ('id', 'session_confirm', 'message', 'session_cancellation', 'location_change', 'session_reminder', 'available', 'push_notifications_enabled') class UserProfileDetailSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() settings = UserSettingsSerializer() class Meta: model = User fields = ('id', 'username', 'name', 'last_name', 'second_last_name', 'description', 'photo', 'email', 'phone', 'zip_code', 'birthday', 'gender', 'is_student', 'is_teacher', 'token', 'settings') def get_token(self, obj): """ Create token. """ return create_token(obj) class LoginResponseV2Serializer(serializers.ModelSerializer): """ Serializer used to return the proper token, when the user was succesfully logged in. """ token = serializers.SerializerMethodField() class Meta: model = User fields = 'token', def get_token(self, obj): """ Create token. """ return create_token(obj) <|reserved_special_token_1|> <|reserved_special_token_0|> class LoginSerializer(serializers.Serializer): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def validate(self, data): """ Validation email. """ try: user = User.objects.get(email__iexact=data.get('email')) except User.DoesNotExist: raise serializers.ValidationError('invalid credentials') if not user.check_password(data.get('password')): raise serializers.ValidationError('invalid credentials') return data <|reserved_special_token_0|> class LogoutSerializer(ModelSerializer): """ Serializer for log users out. """ is_active = serializers.ReadOnlyField() class Meta: model = DeviceUser fields = ['device_user_token', 'device_os', 'is_active'] def validate(self, data): """ Validate that the requesting user owns the given device. """ request = self.context['request'] data.setdefault('user', request.user) data.setdefault('device_user_token', None) if not request.user.is_authenticated(): raise serializers.ValidationError('user is not logged in.') try: self.instance = DeviceUser.objects.get(**data) except DeviceUser.DoesNotExist: raise serializers.ValidationError('invalid device') return data def update(self): """ Mark the given device as inactive. """ self.instance.is_active = False self.instance.save() return self.instance class UserSettingsSerializer(serializers.ModelSerializer): class Meta: model = UserSettings fields = ('id', 'session_confirm', 'message', 'session_cancellation', 'location_change', 'session_reminder', 'available', 'push_notifications_enabled') class UserProfileDetailSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() settings = UserSettingsSerializer() class Meta: model = User fields = ('id', 'username', 'name', 'last_name', 'second_last_name', 'description', 'photo', 'email', 'phone', 'zip_code', 'birthday', 'gender', 'is_student', 'is_teacher', 'token', 'settings') def get_token(self, obj): """ Create token. """ return create_token(obj) class LoginResponseV2Serializer(serializers.ModelSerializer): """ Serializer used to return the proper token, when the user was succesfully logged in. """ token = serializers.SerializerMethodField() class Meta: model = User fields = 'token', def get_token(self, obj): """ Create token. """ return create_token(obj) <|reserved_special_token_1|> <|reserved_special_token_0|> class LoginSerializer(serializers.Serializer): email = serializers.EmailField(required=True) password = serializers.CharField(required=True) device_user_token = serializers.CharField(max_length=250, allow_blank= True, required=False) device_os = serializers.CharField(max_length=30, allow_blank=False) def validate(self, data): """ Validation email. """ try: user = User.objects.get(email__iexact=data.get('email')) except User.DoesNotExist: raise serializers.ValidationError('invalid credentials') if not user.check_password(data.get('password')): raise serializers.ValidationError('invalid credentials') return data def create(self, validated_data): user = get_object_or_404(User, email=validated_data.get('email')) device_user_token = validated_data.get('device_user_token') device_os = validated_data.get('device_os') if isinstance(device_user_token, unicode) and len(device_user_token ) == 64 and (not device_os or device_os == ''): device_os = 'iOS' device, created = DeviceUser.objects.get_or_create(user=user, device_user_token=device_user_token) device.device_os = device_os device.is_active = True device.save() return user class LogoutSerializer(ModelSerializer): """ Serializer for log users out. """ is_active = serializers.ReadOnlyField() class Meta: model = DeviceUser fields = ['device_user_token', 'device_os', 'is_active'] def validate(self, data): """ Validate that the requesting user owns the given device. """ request = self.context['request'] data.setdefault('user', request.user) data.setdefault('device_user_token', None) if not request.user.is_authenticated(): raise serializers.ValidationError('user is not logged in.') try: self.instance = DeviceUser.objects.get(**data) except DeviceUser.DoesNotExist: raise serializers.ValidationError('invalid device') return data def update(self): """ Mark the given device as inactive. """ self.instance.is_active = False self.instance.save() return self.instance class UserSettingsSerializer(serializers.ModelSerializer): class Meta: model = UserSettings fields = ('id', 'session_confirm', 'message', 'session_cancellation', 'location_change', 'session_reminder', 'available', 'push_notifications_enabled') class UserProfileDetailSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() settings = UserSettingsSerializer() class Meta: model = User fields = ('id', 'username', 'name', 'last_name', 'second_last_name', 'description', 'photo', 'email', 'phone', 'zip_code', 'birthday', 'gender', 'is_student', 'is_teacher', 'token', 'settings') def get_token(self, obj): """ Create token. """ return create_token(obj) class LoginResponseV2Serializer(serializers.ModelSerializer): """ Serializer used to return the proper token, when the user was succesfully logged in. """ token = serializers.SerializerMethodField() class Meta: model = User fields = 'token', def get_token(self, obj): """ Create token. """ return create_token(obj) <|reserved_special_token_1|> # -*- coding: utf-8 -*- from django.shortcuts import get_object_or_404 from rest_framework import serializers from tandlr.core.api.serializers import ModelSerializer from tandlr.users.models import DeviceUser, User, UserSettings from tandlr.utils.refresh_token import create_token class LoginSerializer(serializers.Serializer): email = serializers.EmailField( required=True ) password = serializers.CharField( required=True ) device_user_token = serializers.CharField( max_length=250, allow_blank=True, required=False ) device_os = serializers.CharField( max_length=30, allow_blank=False ) def validate(self, data): """ Validation email. """ try: user = User.objects.get(email__iexact=data.get('email')) except User.DoesNotExist: raise serializers.ValidationError("invalid credentials") if not user.check_password(data.get('password')): raise serializers.ValidationError("invalid credentials") return data def create(self, validated_data): # Valitation mail user = get_object_or_404(User, email=validated_data.get('email')) device_user_token = validated_data.get('device_user_token') device_os = validated_data.get('device_os') if (isinstance(device_user_token, unicode) and len(device_user_token) == 64 and (not device_os or device_os == '')): device_os = 'iOS' # Save data of the device device, created = DeviceUser.objects.get_or_create( user=user, device_user_token=device_user_token ) device.device_os = device_os device.is_active = True device.save() return user class LogoutSerializer(ModelSerializer): """ Serializer for log users out. """ is_active = serializers.ReadOnlyField() class Meta: model = DeviceUser fields = ['device_user_token', 'device_os', 'is_active'] def validate(self, data): """ Validate that the requesting user owns the given device. """ request = self.context['request'] data.setdefault('user', request.user) data.setdefault('device_user_token', None) if not request.user.is_authenticated(): raise serializers.ValidationError('user is not logged in.') try: self.instance = DeviceUser.objects.get(**data) except DeviceUser.DoesNotExist: raise serializers.ValidationError('invalid device') return data def update(self): """ Mark the given device as inactive. """ self.instance.is_active = False self.instance.save() return self.instance class UserSettingsSerializer(serializers.ModelSerializer): class Meta: model = UserSettings fields = ( 'id', 'session_confirm', 'message', 'session_cancellation', 'location_change', 'session_reminder', 'available', 'push_notifications_enabled' ) class UserProfileDetailSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() settings = UserSettingsSerializer() class Meta: model = User fields = ( 'id', 'username', 'name', 'last_name', 'second_last_name', 'description', 'photo', 'email', 'phone', 'zip_code', 'birthday', 'gender', 'is_student', 'is_teacher', 'token', 'settings' ) def get_token(self, obj): """ Create token. """ return create_token(obj) class LoginResponseV2Serializer(serializers.ModelSerializer): """ Serializer used to return the proper token, when the user was succesfully logged in. """ token = serializers.SerializerMethodField() class Meta: model = User fields = ('token', ) def get_token(self, obj): """ Create token. """ return create_token(obj)
flexible
{ "blob_id": "01900c1d14a04ee43553c8602a07e0c6ecfabded", "index": 1803, "step-1": "<mask token>\n\n\nclass LogoutSerializer(ModelSerializer):\n <mask token>\n <mask token>\n\n\n class Meta:\n model = DeviceUser\n fields = ['device_user_token', 'device_os', 'is_active']\n <mask token>\n <mask token>\n\n\nclass UserSettingsSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = UserSettings\n fields = ('id', 'session_confirm', 'message',\n 'session_cancellation', 'location_change', 'session_reminder',\n 'available', 'push_notifications_enabled')\n\n\nclass UserProfileDetailSerializer(serializers.ModelSerializer):\n token = serializers.SerializerMethodField()\n settings = UserSettingsSerializer()\n\n\n class Meta:\n model = User\n fields = ('id', 'username', 'name', 'last_name', 'second_last_name',\n 'description', 'photo', 'email', 'phone', 'zip_code',\n 'birthday', 'gender', 'is_student', 'is_teacher', 'token',\n 'settings')\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n\n\nclass LoginResponseV2Serializer(serializers.ModelSerializer):\n \"\"\"\n Serializer used to return the proper token, when the user was succesfully\n logged in.\n \"\"\"\n token = serializers.SerializerMethodField()\n\n\n class Meta:\n model = User\n fields = 'token',\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n", "step-2": "<mask token>\n\n\nclass LogoutSerializer(ModelSerializer):\n <mask token>\n <mask token>\n\n\n class Meta:\n model = DeviceUser\n fields = ['device_user_token', 'device_os', 'is_active']\n\n def validate(self, data):\n \"\"\"\n Validate that the requesting user owns the given device.\n \"\"\"\n request = self.context['request']\n data.setdefault('user', request.user)\n data.setdefault('device_user_token', None)\n if not request.user.is_authenticated():\n raise serializers.ValidationError('user is not logged in.')\n try:\n self.instance = DeviceUser.objects.get(**data)\n except DeviceUser.DoesNotExist:\n raise serializers.ValidationError('invalid device')\n return data\n\n def update(self):\n \"\"\"\n Mark the given device as inactive.\n \"\"\"\n self.instance.is_active = False\n self.instance.save()\n return self.instance\n\n\nclass UserSettingsSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = UserSettings\n fields = ('id', 'session_confirm', 'message',\n 'session_cancellation', 'location_change', 'session_reminder',\n 'available', 'push_notifications_enabled')\n\n\nclass UserProfileDetailSerializer(serializers.ModelSerializer):\n token = serializers.SerializerMethodField()\n settings = UserSettingsSerializer()\n\n\n class Meta:\n model = User\n fields = ('id', 'username', 'name', 'last_name', 'second_last_name',\n 'description', 'photo', 'email', 'phone', 'zip_code',\n 'birthday', 'gender', 'is_student', 'is_teacher', 'token',\n 'settings')\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n\n\nclass LoginResponseV2Serializer(serializers.ModelSerializer):\n \"\"\"\n Serializer used to return the proper token, when the user was succesfully\n logged in.\n \"\"\"\n token = serializers.SerializerMethodField()\n\n\n class Meta:\n model = User\n fields = 'token',\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n", "step-3": "<mask token>\n\n\nclass LoginSerializer(serializers.Serializer):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def validate(self, data):\n \"\"\"\n Validation email.\n \"\"\"\n try:\n user = User.objects.get(email__iexact=data.get('email'))\n except User.DoesNotExist:\n raise serializers.ValidationError('invalid credentials')\n if not user.check_password(data.get('password')):\n raise serializers.ValidationError('invalid credentials')\n return data\n <mask token>\n\n\nclass LogoutSerializer(ModelSerializer):\n \"\"\"\n Serializer for log users out.\n \"\"\"\n is_active = serializers.ReadOnlyField()\n\n\n class Meta:\n model = DeviceUser\n fields = ['device_user_token', 'device_os', 'is_active']\n\n def validate(self, data):\n \"\"\"\n Validate that the requesting user owns the given device.\n \"\"\"\n request = self.context['request']\n data.setdefault('user', request.user)\n data.setdefault('device_user_token', None)\n if not request.user.is_authenticated():\n raise serializers.ValidationError('user is not logged in.')\n try:\n self.instance = DeviceUser.objects.get(**data)\n except DeviceUser.DoesNotExist:\n raise serializers.ValidationError('invalid device')\n return data\n\n def update(self):\n \"\"\"\n Mark the given device as inactive.\n \"\"\"\n self.instance.is_active = False\n self.instance.save()\n return self.instance\n\n\nclass UserSettingsSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = UserSettings\n fields = ('id', 'session_confirm', 'message',\n 'session_cancellation', 'location_change', 'session_reminder',\n 'available', 'push_notifications_enabled')\n\n\nclass UserProfileDetailSerializer(serializers.ModelSerializer):\n token = serializers.SerializerMethodField()\n settings = UserSettingsSerializer()\n\n\n class Meta:\n model = User\n fields = ('id', 'username', 'name', 'last_name', 'second_last_name',\n 'description', 'photo', 'email', 'phone', 'zip_code',\n 'birthday', 'gender', 'is_student', 'is_teacher', 'token',\n 'settings')\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n\n\nclass LoginResponseV2Serializer(serializers.ModelSerializer):\n \"\"\"\n Serializer used to return the proper token, when the user was succesfully\n logged in.\n \"\"\"\n token = serializers.SerializerMethodField()\n\n\n class Meta:\n model = User\n fields = 'token',\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n", "step-4": "<mask token>\n\n\nclass LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(required=True)\n password = serializers.CharField(required=True)\n device_user_token = serializers.CharField(max_length=250, allow_blank=\n True, required=False)\n device_os = serializers.CharField(max_length=30, allow_blank=False)\n\n def validate(self, data):\n \"\"\"\n Validation email.\n \"\"\"\n try:\n user = User.objects.get(email__iexact=data.get('email'))\n except User.DoesNotExist:\n raise serializers.ValidationError('invalid credentials')\n if not user.check_password(data.get('password')):\n raise serializers.ValidationError('invalid credentials')\n return data\n\n def create(self, validated_data):\n user = get_object_or_404(User, email=validated_data.get('email'))\n device_user_token = validated_data.get('device_user_token')\n device_os = validated_data.get('device_os')\n if isinstance(device_user_token, unicode) and len(device_user_token\n ) == 64 and (not device_os or device_os == ''):\n device_os = 'iOS'\n device, created = DeviceUser.objects.get_or_create(user=user,\n device_user_token=device_user_token)\n device.device_os = device_os\n device.is_active = True\n device.save()\n return user\n\n\nclass LogoutSerializer(ModelSerializer):\n \"\"\"\n Serializer for log users out.\n \"\"\"\n is_active = serializers.ReadOnlyField()\n\n\n class Meta:\n model = DeviceUser\n fields = ['device_user_token', 'device_os', 'is_active']\n\n def validate(self, data):\n \"\"\"\n Validate that the requesting user owns the given device.\n \"\"\"\n request = self.context['request']\n data.setdefault('user', request.user)\n data.setdefault('device_user_token', None)\n if not request.user.is_authenticated():\n raise serializers.ValidationError('user is not logged in.')\n try:\n self.instance = DeviceUser.objects.get(**data)\n except DeviceUser.DoesNotExist:\n raise serializers.ValidationError('invalid device')\n return data\n\n def update(self):\n \"\"\"\n Mark the given device as inactive.\n \"\"\"\n self.instance.is_active = False\n self.instance.save()\n return self.instance\n\n\nclass UserSettingsSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = UserSettings\n fields = ('id', 'session_confirm', 'message',\n 'session_cancellation', 'location_change', 'session_reminder',\n 'available', 'push_notifications_enabled')\n\n\nclass UserProfileDetailSerializer(serializers.ModelSerializer):\n token = serializers.SerializerMethodField()\n settings = UserSettingsSerializer()\n\n\n class Meta:\n model = User\n fields = ('id', 'username', 'name', 'last_name', 'second_last_name',\n 'description', 'photo', 'email', 'phone', 'zip_code',\n 'birthday', 'gender', 'is_student', 'is_teacher', 'token',\n 'settings')\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n\n\nclass LoginResponseV2Serializer(serializers.ModelSerializer):\n \"\"\"\n Serializer used to return the proper token, when the user was succesfully\n logged in.\n \"\"\"\n token = serializers.SerializerMethodField()\n\n\n class Meta:\n model = User\n fields = 'token',\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n", "step-5": "# -*- coding: utf-8 -*-\nfrom django.shortcuts import get_object_or_404\n\nfrom rest_framework import serializers\n\nfrom tandlr.core.api.serializers import ModelSerializer\nfrom tandlr.users.models import DeviceUser, User, UserSettings\nfrom tandlr.utils.refresh_token import create_token\n\n\nclass LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(\n required=True\n )\n\n password = serializers.CharField(\n required=True\n )\n\n device_user_token = serializers.CharField(\n max_length=250,\n allow_blank=True,\n required=False\n )\n\n device_os = serializers.CharField(\n max_length=30,\n allow_blank=False\n )\n\n def validate(self, data):\n \"\"\"\n Validation email.\n \"\"\"\n try:\n user = User.objects.get(email__iexact=data.get('email'))\n except User.DoesNotExist:\n raise serializers.ValidationError(\"invalid credentials\")\n\n if not user.check_password(data.get('password')):\n raise serializers.ValidationError(\"invalid credentials\")\n\n return data\n\n def create(self, validated_data):\n # Valitation mail\n user = get_object_or_404(User, email=validated_data.get('email'))\n\n device_user_token = validated_data.get('device_user_token')\n device_os = validated_data.get('device_os')\n\n if (isinstance(device_user_token, unicode) and\n len(device_user_token) == 64 and\n (not device_os or device_os == '')):\n device_os = 'iOS'\n\n # Save data of the device\n device, created = DeviceUser.objects.get_or_create(\n user=user,\n device_user_token=device_user_token\n )\n\n device.device_os = device_os\n device.is_active = True\n device.save()\n\n return user\n\n\nclass LogoutSerializer(ModelSerializer):\n \"\"\"\n Serializer for log users out.\n \"\"\"\n is_active = serializers.ReadOnlyField()\n\n class Meta:\n model = DeviceUser\n fields = ['device_user_token', 'device_os', 'is_active']\n\n def validate(self, data):\n \"\"\"\n Validate that the requesting user owns the given device.\n \"\"\"\n request = self.context['request']\n data.setdefault('user', request.user)\n data.setdefault('device_user_token', None)\n\n if not request.user.is_authenticated():\n raise serializers.ValidationError('user is not logged in.')\n\n try:\n self.instance = DeviceUser.objects.get(**data)\n\n except DeviceUser.DoesNotExist:\n raise serializers.ValidationError('invalid device')\n\n return data\n\n def update(self):\n \"\"\"\n Mark the given device as inactive.\n \"\"\"\n self.instance.is_active = False\n self.instance.save()\n\n return self.instance\n\n\nclass UserSettingsSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = UserSettings\n fields = (\n 'id',\n 'session_confirm',\n 'message',\n 'session_cancellation',\n 'location_change',\n 'session_reminder',\n 'available',\n 'push_notifications_enabled'\n )\n\n\nclass UserProfileDetailSerializer(serializers.ModelSerializer):\n\n token = serializers.SerializerMethodField()\n settings = UserSettingsSerializer()\n\n class Meta:\n model = User\n fields = (\n 'id', 'username', 'name', 'last_name',\n 'second_last_name', 'description', 'photo', 'email',\n 'phone', 'zip_code', 'birthday', 'gender', 'is_student',\n 'is_teacher', 'token', 'settings'\n )\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n\n\nclass LoginResponseV2Serializer(serializers.ModelSerializer):\n \"\"\"\n Serializer used to return the proper token, when the user was succesfully\n logged in.\n \"\"\"\n\n token = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n fields = ('token', )\n\n def get_token(self, obj):\n \"\"\"\n Create token.\n \"\"\"\n return create_token(obj)\n", "step-ids": [ 9, 11, 15, 17, 19 ] }
[ 9, 11, 15, 17, 19 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): initial = True dependencies = [] operations = [migrations.CreateModel(name='Expression', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize= False, verbose_name='ID')), ('value', models.FloatField())]), migrations.CreateModel(name='Gene', fields=[('id', models.AutoField (auto_created=True, primary_key=True, serialize=False, verbose_name ='ID')), ('gene_id', models.CharField(max_length=20, unique=True)), ('summary', models.CharField(max_length=10000))]), migrations. CreateModel(name='MutualInformation', fields=[('id', models. AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.FloatField()), ('dataset', models.CharField(max_length=1000)), ('gene1', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name='gene1', to='plots.Gene')), ('gene2', models.ForeignKey(on_delete=django.db. models.deletion.CASCADE, related_name='gene2', to='plots.Gene'))]), migrations.CreateModel(name='Pca', fields=[('id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name= 'ID')), ('pc1', models.FloatField()), ('pc2', models.FloatField())] ), migrations.CreateModel(name='Sample', fields=[('id', models. AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=1000)), ( 'cell_type', models.CharField(max_length=100)), ('dataset', models. CharField(max_length=1000))]), migrations.AddField(model_name='pca', name='sample', field=models.ForeignKey(on_delete=django.db.models. deletion.CASCADE, to='plots.Sample')), migrations.AddField( model_name='expression', name='gene', field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='plots.Gene')), migrations.AddField(model_name='expression', name='sample', field= models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to= 'plots.Sample'))] <|reserved_special_token_1|> from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [] operations = [migrations.CreateModel(name='Expression', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize= False, verbose_name='ID')), ('value', models.FloatField())]), migrations.CreateModel(name='Gene', fields=[('id', models.AutoField (auto_created=True, primary_key=True, serialize=False, verbose_name ='ID')), ('gene_id', models.CharField(max_length=20, unique=True)), ('summary', models.CharField(max_length=10000))]), migrations. CreateModel(name='MutualInformation', fields=[('id', models. AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.FloatField()), ('dataset', models.CharField(max_length=1000)), ('gene1', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name='gene1', to='plots.Gene')), ('gene2', models.ForeignKey(on_delete=django.db. models.deletion.CASCADE, related_name='gene2', to='plots.Gene'))]), migrations.CreateModel(name='Pca', fields=[('id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name= 'ID')), ('pc1', models.FloatField()), ('pc2', models.FloatField())] ), migrations.CreateModel(name='Sample', fields=[('id', models. AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=1000)), ( 'cell_type', models.CharField(max_length=100)), ('dataset', models. CharField(max_length=1000))]), migrations.AddField(model_name='pca', name='sample', field=models.ForeignKey(on_delete=django.db.models. deletion.CASCADE, to='plots.Sample')), migrations.AddField( model_name='expression', name='gene', field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='plots.Gene')), migrations.AddField(model_name='expression', name='sample', field= models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to= 'plots.Sample'))] <|reserved_special_token_1|> # Generated by Django 2.0.2 on 2018-06-10 18:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Expression', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.FloatField()), ], ), migrations.CreateModel( name='Gene', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('gene_id', models.CharField(max_length=20, unique=True)), ('summary', models.CharField(max_length=10000)), ], ), migrations.CreateModel( name='MutualInformation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.FloatField()), ('dataset', models.CharField(max_length=1000)), ('gene1', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='gene1', to='plots.Gene')), ('gene2', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='gene2', to='plots.Gene')), ], ), migrations.CreateModel( name='Pca', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pc1', models.FloatField()), ('pc2', models.FloatField()), ], ), migrations.CreateModel( name='Sample', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=1000)), ('cell_type', models.CharField(max_length=100)), ('dataset', models.CharField(max_length=1000)), ], ), migrations.AddField( model_name='pca', name='sample', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='plots.Sample'), ), migrations.AddField( model_name='expression', name='gene', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='plots.Gene'), ), migrations.AddField( model_name='expression', name='sample', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='plots.Sample'), ), ]
flexible
{ "blob_id": "87e0b9dc518d439f71e261d5c5047153324919ba", "index": 9547, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='Expression', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('value', models.FloatField())]),\n migrations.CreateModel(name='Gene', fields=[('id', models.AutoField\n (auto_created=True, primary_key=True, serialize=False, verbose_name\n ='ID')), ('gene_id', models.CharField(max_length=20, unique=True)),\n ('summary', models.CharField(max_length=10000))]), migrations.\n CreateModel(name='MutualInformation', fields=[('id', models.\n AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('value', models.FloatField()), ('dataset',\n models.CharField(max_length=1000)), ('gene1', models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE, related_name='gene1',\n to='plots.Gene')), ('gene2', models.ForeignKey(on_delete=django.db.\n models.deletion.CASCADE, related_name='gene2', to='plots.Gene'))]),\n migrations.CreateModel(name='Pca', fields=[('id', models.AutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), ('pc1', models.FloatField()), ('pc2', models.FloatField())]\n ), migrations.CreateModel(name='Sample', fields=[('id', models.\n AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('name', models.CharField(max_length=1000)), (\n 'cell_type', models.CharField(max_length=100)), ('dataset', models.\n CharField(max_length=1000))]), migrations.AddField(model_name='pca',\n name='sample', field=models.ForeignKey(on_delete=django.db.models.\n deletion.CASCADE, to='plots.Sample')), migrations.AddField(\n model_name='expression', name='gene', field=models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE, to='plots.Gene')),\n migrations.AddField(model_name='expression', name='sample', field=\n models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=\n 'plots.Sample'))]\n", "step-4": "from django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='Expression', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('value', models.FloatField())]),\n migrations.CreateModel(name='Gene', fields=[('id', models.AutoField\n (auto_created=True, primary_key=True, serialize=False, verbose_name\n ='ID')), ('gene_id', models.CharField(max_length=20, unique=True)),\n ('summary', models.CharField(max_length=10000))]), migrations.\n CreateModel(name='MutualInformation', fields=[('id', models.\n AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('value', models.FloatField()), ('dataset',\n models.CharField(max_length=1000)), ('gene1', models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE, related_name='gene1',\n to='plots.Gene')), ('gene2', models.ForeignKey(on_delete=django.db.\n models.deletion.CASCADE, related_name='gene2', to='plots.Gene'))]),\n migrations.CreateModel(name='Pca', fields=[('id', models.AutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), ('pc1', models.FloatField()), ('pc2', models.FloatField())]\n ), migrations.CreateModel(name='Sample', fields=[('id', models.\n AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('name', models.CharField(max_length=1000)), (\n 'cell_type', models.CharField(max_length=100)), ('dataset', models.\n CharField(max_length=1000))]), migrations.AddField(model_name='pca',\n name='sample', field=models.ForeignKey(on_delete=django.db.models.\n deletion.CASCADE, to='plots.Sample')), migrations.AddField(\n model_name='expression', name='gene', field=models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE, to='plots.Gene')),\n migrations.AddField(model_name='expression', name='sample', field=\n models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=\n 'plots.Sample'))]\n", "step-5": "# Generated by Django 2.0.2 on 2018-06-10 18:24\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Expression',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('value', models.FloatField()),\n ],\n ),\n migrations.CreateModel(\n name='Gene',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('gene_id', models.CharField(max_length=20, unique=True)),\n ('summary', models.CharField(max_length=10000)),\n ],\n ),\n migrations.CreateModel(\n name='MutualInformation',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('value', models.FloatField()),\n ('dataset', models.CharField(max_length=1000)),\n ('gene1', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='gene1', to='plots.Gene')),\n ('gene2', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='gene2', to='plots.Gene')),\n ],\n ),\n migrations.CreateModel(\n name='Pca',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('pc1', models.FloatField()),\n ('pc2', models.FloatField()),\n ],\n ),\n migrations.CreateModel(\n name='Sample',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=1000)),\n ('cell_type', models.CharField(max_length=100)),\n ('dataset', models.CharField(max_length=1000)),\n ],\n ),\n migrations.AddField(\n model_name='pca',\n name='sample',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='plots.Sample'),\n ),\n migrations.AddField(\n model_name='expression',\n name='gene',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='plots.Gene'),\n ),\n migrations.AddField(\n model_name='expression',\n name='sample',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='plots.Sample'),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def get_repo_url(repo): url = repo.replace('upstream:', 'git://git.baserock.org/delta/') url = url.replace('baserock:baserock/', 'git://git.baserock.org/baserock/baserock/') url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/') url = url.replace('github:', 'git://github.com/') url = url.replace('gnome:', 'git://git.gnome.org') if url.endswith('.git'): url = url[:-4] return url def get_repo_name(repo): """ Convert URIs to strings that only contain digits, letters, _ and %. NOTE: When changing the code of this function, make sure to also apply the same to the quote_url() function of lorry. Otherwise the git tarballs generated by lorry may no longer be found by morph. """ valid_chars = string.digits + string.ascii_letters + '%_' transl = lambda x: x if x in valid_chars else '_' return ''.join([transl(x) for x in get_repo_url(repo)]) def get_upstream_version(repo, ref): try: gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) with app.chdir(gitdir), open(os.devnull, 'w') as fnull: last_tag = check_output(['git', 'describe', '--abbrev=0', '--tags', ref], stderr=fnull)[0:-1] commits = check_output(['git', 'rev-list', last_tag + '..' + ref, '--count']) result = '%s (%s + %s commits)' % (ref[:8], last_tag, commits[0:-1]) except: result = ref[:8] + ' ' + '(No tag found)' return result <|reserved_special_token_0|> def copy_repo(repo, destdir): """Copies a cached repository into a directory using cp. This also fixes up the repository afterwards, so that it can contain code etc. It does not leave any given branch ready for use. """ call(['cp', '-a', repo, os.path.join(destdir, '.git')]) call(['git', 'config', 'core.bare', 'false']) call(['git', 'config', '--unset', 'remote.origin.mirror']) with open(os.devnull, 'w') as fnull: call(['git', 'config', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*'], stdout=fnull, stderr=fnull) call(['git', 'config', 'remote.origin.url', repo]) call(['git', 'pack-refs', '--all', '--prune']) with open(os.path.join(destdir, '.git', 'packed-refs'), 'r') as ref_fh: pack_lines = ref_fh.read().split('\n') with open(os.path.join(destdir, '.git', 'packed-refs'), 'w') as ref_fh: ref_fh.write(pack_lines.pop(0) + '\n') for refline in pack_lines: if ' refs/remotes/' in refline: continue if ' refs/heads/' in refline: sha, ref = refline[:40], refline[41:] if ref.startswith('refs/heads/'): ref = 'refs/remotes/origin/' + ref[11:] refline = '%s %s' % (sha, ref) ref_fh.write('%s\n' % refline) with open(os.devnull, 'w') as fnull: call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull, stderr=fnull) <|reserved_special_token_0|> def checkout_submodules(name, ref): app.log(name, 'Git submodules') with open('.gitmodules', 'r') as gitfile: content = '\n'.join([l.strip() for l in gitfile.read().splitlines()]) io = StringIO.StringIO(content) parser = ConfigParser.RawConfigParser() parser.readfp(io) for section in parser.sections(): submodule = re.sub('submodule "(.*)"', '\\1', section) url = parser.get(section, 'url') path = parser.get(section, 'path') try: commit = check_output(['git', 'ls-tree', ref, path]) fields = commit.split() if len(fields) >= 2 and fields[1] == 'commit': submodule_commit = commit.split()[2] if len(submodule_commit) != 40: raise Exception fulldir = os.path.join(os.getcwd(), path) checkout(submodule, url, submodule_commit, fulldir) else: app.log(this, 'Skipping submodule "%s" as %s:%s has a non-commit object for it' % (name, url)) except: app.log(name, 'ERROR: Git submodules problem') raise SystemExit <|reserved_special_token_1|> <|reserved_special_token_0|> def get_repo_url(repo): url = repo.replace('upstream:', 'git://git.baserock.org/delta/') url = url.replace('baserock:baserock/', 'git://git.baserock.org/baserock/baserock/') url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/') url = url.replace('github:', 'git://github.com/') url = url.replace('gnome:', 'git://git.gnome.org') if url.endswith('.git'): url = url[:-4] return url def get_repo_name(repo): """ Convert URIs to strings that only contain digits, letters, _ and %. NOTE: When changing the code of this function, make sure to also apply the same to the quote_url() function of lorry. Otherwise the git tarballs generated by lorry may no longer be found by morph. """ valid_chars = string.digits + string.ascii_letters + '%_' transl = lambda x: x if x in valid_chars else '_' return ''.join([transl(x) for x in get_repo_url(repo)]) def get_upstream_version(repo, ref): try: gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) with app.chdir(gitdir), open(os.devnull, 'w') as fnull: last_tag = check_output(['git', 'describe', '--abbrev=0', '--tags', ref], stderr=fnull)[0:-1] commits = check_output(['git', 'rev-list', last_tag + '..' + ref, '--count']) result = '%s (%s + %s commits)' % (ref[:8], last_tag, commits[0:-1]) except: result = ref[:8] + ' ' + '(No tag found)' return result def get_tree(this): ref = this['ref'] gitdir = os.path.join(app.settings['gits'], get_repo_name(this['repo'])) if not os.path.exists(gitdir): try: url = app.settings['cache-server-url'] + 'repo=' + get_repo_url( this['repo']) + '&ref=' + ref with urllib2.urlopen(url) as response: tree = json.loads(response.read().decode())['tree'] return tree except: app.log(this, 'WARNING: no tree from cache-server', ref) mirror(this['name'], this['repo']) with app.chdir(gitdir), open(os.devnull, 'w') as fnull: if call(['git', 'rev-parse', ref + '^{object}'], stdout=fnull, stderr=fnull): call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull) try: tree = check_output(['git', 'rev-parse', ref + '^{tree}'], universal_newlines=True)[0:-1] return tree except: app.log(this, 'ERROR: could not find tree for ref', ref) raise SystemExit def copy_repo(repo, destdir): """Copies a cached repository into a directory using cp. This also fixes up the repository afterwards, so that it can contain code etc. It does not leave any given branch ready for use. """ call(['cp', '-a', repo, os.path.join(destdir, '.git')]) call(['git', 'config', 'core.bare', 'false']) call(['git', 'config', '--unset', 'remote.origin.mirror']) with open(os.devnull, 'w') as fnull: call(['git', 'config', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*'], stdout=fnull, stderr=fnull) call(['git', 'config', 'remote.origin.url', repo]) call(['git', 'pack-refs', '--all', '--prune']) with open(os.path.join(destdir, '.git', 'packed-refs'), 'r') as ref_fh: pack_lines = ref_fh.read().split('\n') with open(os.path.join(destdir, '.git', 'packed-refs'), 'w') as ref_fh: ref_fh.write(pack_lines.pop(0) + '\n') for refline in pack_lines: if ' refs/remotes/' in refline: continue if ' refs/heads/' in refline: sha, ref = refline[:40], refline[41:] if ref.startswith('refs/heads/'): ref = 'refs/remotes/origin/' + ref[11:] refline = '%s %s' % (sha, ref) ref_fh.write('%s\n' % refline) with open(os.devnull, 'w') as fnull: call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull, stderr=fnull) <|reserved_special_token_0|> def checkout(name, repo, ref, checkoutdir): gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) if not os.path.exists(gitdir): mirror(name, repo) app.log(name, 'Upstream version:', get_upstream_version(repo, ref)) app.log(name, 'Git checkout %s in %s' % (repo, checkoutdir)) with app.chdir(checkoutdir), open(os.devnull, 'w') as fnull: copy_repo(gitdir, checkoutdir) if call(['git', 'checkout', ref], stdout=fnull, stderr=fnull): app.log(name, 'ERROR: git checkout failed for', ref) raise SystemExit if os.path.exists('.gitmodules'): checkout_submodules(name, ref) utils.set_mtime_recursively(checkoutdir) def checkout_submodules(name, ref): app.log(name, 'Git submodules') with open('.gitmodules', 'r') as gitfile: content = '\n'.join([l.strip() for l in gitfile.read().splitlines()]) io = StringIO.StringIO(content) parser = ConfigParser.RawConfigParser() parser.readfp(io) for section in parser.sections(): submodule = re.sub('submodule "(.*)"', '\\1', section) url = parser.get(section, 'url') path = parser.get(section, 'path') try: commit = check_output(['git', 'ls-tree', ref, path]) fields = commit.split() if len(fields) >= 2 and fields[1] == 'commit': submodule_commit = commit.split()[2] if len(submodule_commit) != 40: raise Exception fulldir = os.path.join(os.getcwd(), path) checkout(submodule, url, submodule_commit, fulldir) else: app.log(this, 'Skipping submodule "%s" as %s:%s has a non-commit object for it' % (name, url)) except: app.log(name, 'ERROR: Git submodules problem') raise SystemExit <|reserved_special_token_1|> <|reserved_special_token_0|> def get_repo_url(repo): url = repo.replace('upstream:', 'git://git.baserock.org/delta/') url = url.replace('baserock:baserock/', 'git://git.baserock.org/baserock/baserock/') url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/') url = url.replace('github:', 'git://github.com/') url = url.replace('gnome:', 'git://git.gnome.org') if url.endswith('.git'): url = url[:-4] return url def get_repo_name(repo): """ Convert URIs to strings that only contain digits, letters, _ and %. NOTE: When changing the code of this function, make sure to also apply the same to the quote_url() function of lorry. Otherwise the git tarballs generated by lorry may no longer be found by morph. """ valid_chars = string.digits + string.ascii_letters + '%_' transl = lambda x: x if x in valid_chars else '_' return ''.join([transl(x) for x in get_repo_url(repo)]) def get_upstream_version(repo, ref): try: gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) with app.chdir(gitdir), open(os.devnull, 'w') as fnull: last_tag = check_output(['git', 'describe', '--abbrev=0', '--tags', ref], stderr=fnull)[0:-1] commits = check_output(['git', 'rev-list', last_tag + '..' + ref, '--count']) result = '%s (%s + %s commits)' % (ref[:8], last_tag, commits[0:-1]) except: result = ref[:8] + ' ' + '(No tag found)' return result def get_tree(this): ref = this['ref'] gitdir = os.path.join(app.settings['gits'], get_repo_name(this['repo'])) if not os.path.exists(gitdir): try: url = app.settings['cache-server-url'] + 'repo=' + get_repo_url( this['repo']) + '&ref=' + ref with urllib2.urlopen(url) as response: tree = json.loads(response.read().decode())['tree'] return tree except: app.log(this, 'WARNING: no tree from cache-server', ref) mirror(this['name'], this['repo']) with app.chdir(gitdir), open(os.devnull, 'w') as fnull: if call(['git', 'rev-parse', ref + '^{object}'], stdout=fnull, stderr=fnull): call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull) try: tree = check_output(['git', 'rev-parse', ref + '^{tree}'], universal_newlines=True)[0:-1] return tree except: app.log(this, 'ERROR: could not find tree for ref', ref) raise SystemExit def copy_repo(repo, destdir): """Copies a cached repository into a directory using cp. This also fixes up the repository afterwards, so that it can contain code etc. It does not leave any given branch ready for use. """ call(['cp', '-a', repo, os.path.join(destdir, '.git')]) call(['git', 'config', 'core.bare', 'false']) call(['git', 'config', '--unset', 'remote.origin.mirror']) with open(os.devnull, 'w') as fnull: call(['git', 'config', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*'], stdout=fnull, stderr=fnull) call(['git', 'config', 'remote.origin.url', repo]) call(['git', 'pack-refs', '--all', '--prune']) with open(os.path.join(destdir, '.git', 'packed-refs'), 'r') as ref_fh: pack_lines = ref_fh.read().split('\n') with open(os.path.join(destdir, '.git', 'packed-refs'), 'w') as ref_fh: ref_fh.write(pack_lines.pop(0) + '\n') for refline in pack_lines: if ' refs/remotes/' in refline: continue if ' refs/heads/' in refline: sha, ref = refline[:40], refline[41:] if ref.startswith('refs/heads/'): ref = 'refs/remotes/origin/' + ref[11:] refline = '%s %s' % (sha, ref) ref_fh.write('%s\n' % refline) with open(os.devnull, 'w') as fnull: call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull, stderr=fnull) def mirror(name, repo): gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) repo_url = get_repo_url(repo) try: os.makedirs(gitdir) tar_file = get_repo_name(repo_url) + '.tar' app.log(name, 'Try fetching tarball %s' % tar_file) with app.chdir(gitdir), open(os.devnull, 'w') as fnull: call(['wget', app['tar-url']], stdout=fnull, stderr=fnull) call(['tar', 'xf', tar_file], stdout=fnull, stderr=fnull) os.remove(tar_file) call(['git', 'config', 'remote.origin.url', repo_url], stdout= fnull, stderr=fnull) call(['git', 'config', 'remote.origin.mirror', 'true'], stdout= fnull, stderr=fnull) if call(['git', 'config', 'remote.origin.fetch', '+refs/*:refs/*'], stdout=fnull, stderr=fnull) != 0: raise BaseException('Did not get a valid git repo') call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull) except: app.log(name, 'Using git clone from ', repo_url) try: with open(os.devnull, 'w') as fnull: call(['git', 'clone', '--mirror', '-n', repo_url, gitdir], stdout=fnull, stderr=fnull) except: app.log(name, 'ERROR: failed to clone', repo) raise SystemExit app.log(name, 'Git repo is mirrored at', gitdir) <|reserved_special_token_0|> def checkout(name, repo, ref, checkoutdir): gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) if not os.path.exists(gitdir): mirror(name, repo) app.log(name, 'Upstream version:', get_upstream_version(repo, ref)) app.log(name, 'Git checkout %s in %s' % (repo, checkoutdir)) with app.chdir(checkoutdir), open(os.devnull, 'w') as fnull: copy_repo(gitdir, checkoutdir) if call(['git', 'checkout', ref], stdout=fnull, stderr=fnull): app.log(name, 'ERROR: git checkout failed for', ref) raise SystemExit if os.path.exists('.gitmodules'): checkout_submodules(name, ref) utils.set_mtime_recursively(checkoutdir) def checkout_submodules(name, ref): app.log(name, 'Git submodules') with open('.gitmodules', 'r') as gitfile: content = '\n'.join([l.strip() for l in gitfile.read().splitlines()]) io = StringIO.StringIO(content) parser = ConfigParser.RawConfigParser() parser.readfp(io) for section in parser.sections(): submodule = re.sub('submodule "(.*)"', '\\1', section) url = parser.get(section, 'url') path = parser.get(section, 'path') try: commit = check_output(['git', 'ls-tree', ref, path]) fields = commit.split() if len(fields) >= 2 and fields[1] == 'commit': submodule_commit = commit.split()[2] if len(submodule_commit) != 40: raise Exception fulldir = os.path.join(os.getcwd(), path) checkout(submodule, url, submodule_commit, fulldir) else: app.log(this, 'Skipping submodule "%s" as %s:%s has a non-commit object for it' % (name, url)) except: app.log(name, 'ERROR: Git submodules problem') raise SystemExit <|reserved_special_token_1|> import os import app import re from subprocess import call from subprocess import check_output import string import definitions import urllib2 import json import utils import ConfigParser import StringIO import re def get_repo_url(repo): url = repo.replace('upstream:', 'git://git.baserock.org/delta/') url = url.replace('baserock:baserock/', 'git://git.baserock.org/baserock/baserock/') url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/') url = url.replace('github:', 'git://github.com/') url = url.replace('gnome:', 'git://git.gnome.org') if url.endswith('.git'): url = url[:-4] return url def get_repo_name(repo): """ Convert URIs to strings that only contain digits, letters, _ and %. NOTE: When changing the code of this function, make sure to also apply the same to the quote_url() function of lorry. Otherwise the git tarballs generated by lorry may no longer be found by morph. """ valid_chars = string.digits + string.ascii_letters + '%_' transl = lambda x: x if x in valid_chars else '_' return ''.join([transl(x) for x in get_repo_url(repo)]) def get_upstream_version(repo, ref): try: gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) with app.chdir(gitdir), open(os.devnull, 'w') as fnull: last_tag = check_output(['git', 'describe', '--abbrev=0', '--tags', ref], stderr=fnull)[0:-1] commits = check_output(['git', 'rev-list', last_tag + '..' + ref, '--count']) result = '%s (%s + %s commits)' % (ref[:8], last_tag, commits[0:-1]) except: result = ref[:8] + ' ' + '(No tag found)' return result def get_tree(this): ref = this['ref'] gitdir = os.path.join(app.settings['gits'], get_repo_name(this['repo'])) if not os.path.exists(gitdir): try: url = app.settings['cache-server-url'] + 'repo=' + get_repo_url( this['repo']) + '&ref=' + ref with urllib2.urlopen(url) as response: tree = json.loads(response.read().decode())['tree'] return tree except: app.log(this, 'WARNING: no tree from cache-server', ref) mirror(this['name'], this['repo']) with app.chdir(gitdir), open(os.devnull, 'w') as fnull: if call(['git', 'rev-parse', ref + '^{object}'], stdout=fnull, stderr=fnull): call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull) try: tree = check_output(['git', 'rev-parse', ref + '^{tree}'], universal_newlines=True)[0:-1] return tree except: app.log(this, 'ERROR: could not find tree for ref', ref) raise SystemExit def copy_repo(repo, destdir): """Copies a cached repository into a directory using cp. This also fixes up the repository afterwards, so that it can contain code etc. It does not leave any given branch ready for use. """ call(['cp', '-a', repo, os.path.join(destdir, '.git')]) call(['git', 'config', 'core.bare', 'false']) call(['git', 'config', '--unset', 'remote.origin.mirror']) with open(os.devnull, 'w') as fnull: call(['git', 'config', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*'], stdout=fnull, stderr=fnull) call(['git', 'config', 'remote.origin.url', repo]) call(['git', 'pack-refs', '--all', '--prune']) with open(os.path.join(destdir, '.git', 'packed-refs'), 'r') as ref_fh: pack_lines = ref_fh.read().split('\n') with open(os.path.join(destdir, '.git', 'packed-refs'), 'w') as ref_fh: ref_fh.write(pack_lines.pop(0) + '\n') for refline in pack_lines: if ' refs/remotes/' in refline: continue if ' refs/heads/' in refline: sha, ref = refline[:40], refline[41:] if ref.startswith('refs/heads/'): ref = 'refs/remotes/origin/' + ref[11:] refline = '%s %s' % (sha, ref) ref_fh.write('%s\n' % refline) with open(os.devnull, 'w') as fnull: call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull, stderr=fnull) def mirror(name, repo): gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) repo_url = get_repo_url(repo) try: os.makedirs(gitdir) tar_file = get_repo_name(repo_url) + '.tar' app.log(name, 'Try fetching tarball %s' % tar_file) with app.chdir(gitdir), open(os.devnull, 'w') as fnull: call(['wget', app['tar-url']], stdout=fnull, stderr=fnull) call(['tar', 'xf', tar_file], stdout=fnull, stderr=fnull) os.remove(tar_file) call(['git', 'config', 'remote.origin.url', repo_url], stdout= fnull, stderr=fnull) call(['git', 'config', 'remote.origin.mirror', 'true'], stdout= fnull, stderr=fnull) if call(['git', 'config', 'remote.origin.fetch', '+refs/*:refs/*'], stdout=fnull, stderr=fnull) != 0: raise BaseException('Did not get a valid git repo') call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull) except: app.log(name, 'Using git clone from ', repo_url) try: with open(os.devnull, 'w') as fnull: call(['git', 'clone', '--mirror', '-n', repo_url, gitdir], stdout=fnull, stderr=fnull) except: app.log(name, 'ERROR: failed to clone', repo) raise SystemExit app.log(name, 'Git repo is mirrored at', gitdir) def fetch(repo): with app.chdir(repo), open(os.devnull, 'w') as fnull: call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull) def checkout(name, repo, ref, checkoutdir): gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) if not os.path.exists(gitdir): mirror(name, repo) app.log(name, 'Upstream version:', get_upstream_version(repo, ref)) app.log(name, 'Git checkout %s in %s' % (repo, checkoutdir)) with app.chdir(checkoutdir), open(os.devnull, 'w') as fnull: copy_repo(gitdir, checkoutdir) if call(['git', 'checkout', ref], stdout=fnull, stderr=fnull): app.log(name, 'ERROR: git checkout failed for', ref) raise SystemExit if os.path.exists('.gitmodules'): checkout_submodules(name, ref) utils.set_mtime_recursively(checkoutdir) def checkout_submodules(name, ref): app.log(name, 'Git submodules') with open('.gitmodules', 'r') as gitfile: content = '\n'.join([l.strip() for l in gitfile.read().splitlines()]) io = StringIO.StringIO(content) parser = ConfigParser.RawConfigParser() parser.readfp(io) for section in parser.sections(): submodule = re.sub('submodule "(.*)"', '\\1', section) url = parser.get(section, 'url') path = parser.get(section, 'path') try: commit = check_output(['git', 'ls-tree', ref, path]) fields = commit.split() if len(fields) >= 2 and fields[1] == 'commit': submodule_commit = commit.split()[2] if len(submodule_commit) != 40: raise Exception fulldir = os.path.join(os.getcwd(), path) checkout(submodule, url, submodule_commit, fulldir) else: app.log(this, 'Skipping submodule "%s" as %s:%s has a non-commit object for it' % (name, url)) except: app.log(name, 'ERROR: Git submodules problem') raise SystemExit <|reserved_special_token_1|> #!/usr/bin/env python3 # # Copyright (C) 2011-2015 Codethink Limited # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # =*= License: GPL-2 =*= import os import app import re from subprocess import call from subprocess import check_output import string import definitions import urllib2 import json import utils import ConfigParser import StringIO import re def get_repo_url(repo): url = repo.replace('upstream:', 'git://git.baserock.org/delta/') url = url.replace('baserock:baserock/', 'git://git.baserock.org/baserock/baserock/') url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/') url = url.replace('github:', 'git://github.com/') url = url.replace('gnome:', 'git://git.gnome.org') if url.endswith('.git'): url = url[:-4] return url def get_repo_name(repo): ''' Convert URIs to strings that only contain digits, letters, _ and %. NOTE: When changing the code of this function, make sure to also apply the same to the quote_url() function of lorry. Otherwise the git tarballs generated by lorry may no longer be found by morph. ''' valid_chars = string.digits + string.ascii_letters + '%_' transl = lambda x: x if x in valid_chars else '_' return ''.join([transl(x) for x in get_repo_url(repo)]) def get_upstream_version(repo, ref): try: gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) with app.chdir(gitdir), open(os.devnull, "w") as fnull: last_tag = check_output(['git', 'describe', '--abbrev=0', '--tags', ref], stderr=fnull)[0:-1] commits = check_output(['git', 'rev-list', last_tag + '..' + ref, '--count']) result = "%s (%s + %s commits)" % (ref[:8], last_tag, commits[0:-1]) except: result = ref[:8] + " " + "(No tag found)" return result def get_tree(this): ref = this['ref'] gitdir = os.path.join(app.settings['gits'], get_repo_name(this['repo'])) if not os.path.exists(gitdir): try: url = (app.settings['cache-server-url'] + 'repo=' + get_repo_url(this['repo']) + '&ref=' + ref) with urllib2.urlopen(url) as response: tree = json.loads(response.read().decode())['tree'] return tree except: app.log(this, 'WARNING: no tree from cache-server', ref) mirror(this['name'], this['repo']) with app.chdir(gitdir), open(os.devnull, "w") as fnull: if call(['git', 'rev-parse', ref + '^{object}'], stdout=fnull, stderr=fnull): # can't resolve this ref. is it upstream? call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull) try: tree = check_output(['git', 'rev-parse', ref + '^{tree}'], universal_newlines=True)[0:-1] return tree except: # either we don't have a git dir, or ref is not unique # or ref does not exist app.log(this, 'ERROR: could not find tree for ref', ref) raise SystemExit def copy_repo(repo, destdir): '''Copies a cached repository into a directory using cp. This also fixes up the repository afterwards, so that it can contain code etc. It does not leave any given branch ready for use. ''' # core.bare should be false so that git believes work trees are possible # we do not want the origin remote to behave as a mirror for pulls # we want a traditional refs/heads -> refs/remotes/origin ref mapping # set the origin url to the cached repo so that we can quickly clean up # by packing the refs, we can then edit then en-masse easily call(['cp', '-a', repo, os.path.join(destdir, '.git')]) call(['git', 'config', 'core.bare', 'false']) call(['git', 'config', '--unset', 'remote.origin.mirror']) with open(os.devnull, "w") as fnull: call(['git', 'config', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*'], stdout=fnull, stderr=fnull) call(['git', 'config', 'remote.origin.url', repo]) call(['git', 'pack-refs', '--all', '--prune']) # turn refs/heads/* into refs/remotes/origin/* in the packed refs # so that the new copy behaves more like a traditional clone. with open(os.path.join(destdir, ".git", "packed-refs"), "r") as ref_fh: pack_lines = ref_fh.read().split("\n") with open(os.path.join(destdir, ".git", "packed-refs"), "w") as ref_fh: ref_fh.write(pack_lines.pop(0) + "\n") for refline in pack_lines: if ' refs/remotes/' in refline: continue if ' refs/heads/' in refline: sha, ref = refline[:40], refline[41:] if ref.startswith("refs/heads/"): ref = "refs/remotes/origin/" + ref[11:] refline = "%s %s" % (sha, ref) ref_fh.write("%s\n" % (refline)) # Finally run a remote update to clear up the refs ready for use. with open(os.devnull, "w") as fnull: call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull, stderr=fnull) def mirror(name, repo): # try tarball first gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) repo_url = get_repo_url(repo) try: os.makedirs(gitdir) tar_file = get_repo_name(repo_url) + '.tar' app.log(name, 'Try fetching tarball %s' % tar_file) with app.chdir(gitdir), open(os.devnull, "w") as fnull: call(['wget', app['tar-url']], stdout=fnull, stderr=fnull) call(['tar', 'xf', tar_file], stdout=fnull, stderr=fnull) os.remove(tar_file) call(['git', 'config', 'remote.origin.url', repo_url], stdout=fnull, stderr=fnull) call(['git', 'config', 'remote.origin.mirror', 'true'], stdout=fnull, stderr=fnull) if call(['git', 'config', 'remote.origin.fetch', '+refs/*:refs/*'], stdout=fnull, stderr=fnull) != 0: raise BaseException('Did not get a valid git repo') call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull) except: app.log(name, 'Using git clone from ', repo_url) try: with open(os.devnull, "w") as fnull: call(['git', 'clone', '--mirror', '-n', repo_url, gitdir], stdout=fnull, stderr=fnull) except: app.log(name, 'ERROR: failed to clone', repo) raise SystemExit app.log(name, 'Git repo is mirrored at', gitdir) def fetch(repo): with app.chdir(repo), open(os.devnull, "w") as fnull: call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull) def checkout(name, repo, ref, checkoutdir): gitdir = os.path.join(app.settings['gits'], get_repo_name(repo)) if not os.path.exists(gitdir): mirror(name, repo) app.log(name, 'Upstream version:', get_upstream_version(repo, ref)) app.log(name, 'Git checkout %s in %s' % (repo, checkoutdir)) # checkout the required version of this from git with app.chdir(checkoutdir), open(os.devnull, "w") as fnull: copy_repo(gitdir, checkoutdir) if call(['git', 'checkout', ref], stdout=fnull, stderr=fnull): app.log(name, 'ERROR: git checkout failed for', ref) raise SystemExit if os.path.exists('.gitmodules'): checkout_submodules(name, ref) utils.set_mtime_recursively(checkoutdir) def checkout_submodules(name, ref): app.log(name, 'Git submodules') with open('.gitmodules', "r") as gitfile: # drop indentation in sections, as RawConfigParser cannot handle it content = '\n'.join([l.strip() for l in gitfile.read().splitlines()]) io = StringIO.StringIO(content) parser = ConfigParser.RawConfigParser() parser.readfp(io) for section in parser.sections(): # validate section name against the 'submodule "foo"' pattern submodule = re.sub(r'submodule "(.*)"', r'\1', section) url = parser.get(section, 'url') path = parser.get(section, 'path') try: # list objects in the parent repo tree to find the commit # object that corresponds to the submodule commit = check_output(['git', 'ls-tree', ref, path]) # read the commit hash from the output fields = commit.split() if len(fields) >= 2 and fields[1] == 'commit': submodule_commit = commit.split()[2] # fail if the commit hash is invalid if len(submodule_commit) != 40: raise Exception fulldir = os.path.join(os.getcwd(), path) checkout(submodule, url, submodule_commit, fulldir) else: app.log(this, 'Skipping submodule "%s" as %s:%s has ' 'a non-commit object for it' % (name, url)) except: app.log(name, "ERROR: Git submodules problem") raise SystemExit
flexible
{ "blob_id": "955cf040aaf882328e31e6a943bce04cf721cb11", "index": 538, "step-1": "<mask token>\n\n\ndef get_repo_url(repo):\n url = repo.replace('upstream:', 'git://git.baserock.org/delta/')\n url = url.replace('baserock:baserock/',\n 'git://git.baserock.org/baserock/baserock/')\n url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/')\n url = url.replace('github:', 'git://github.com/')\n url = url.replace('gnome:', 'git://git.gnome.org')\n if url.endswith('.git'):\n url = url[:-4]\n return url\n\n\ndef get_repo_name(repo):\n \"\"\" Convert URIs to strings that only contain digits, letters, _ and %.\n\n NOTE: When changing the code of this function, make sure to also apply\n the same to the quote_url() function of lorry. Otherwise the git tarballs\n generated by lorry may no longer be found by morph.\n\n \"\"\"\n valid_chars = string.digits + string.ascii_letters + '%_'\n transl = lambda x: x if x in valid_chars else '_'\n return ''.join([transl(x) for x in get_repo_url(repo)])\n\n\ndef get_upstream_version(repo, ref):\n try:\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n with app.chdir(gitdir), open(os.devnull, 'w') as fnull:\n last_tag = check_output(['git', 'describe', '--abbrev=0',\n '--tags', ref], stderr=fnull)[0:-1]\n commits = check_output(['git', 'rev-list', last_tag + '..' +\n ref, '--count'])\n result = '%s (%s + %s commits)' % (ref[:8], last_tag, commits[0:-1])\n except:\n result = ref[:8] + ' ' + '(No tag found)'\n return result\n\n\n<mask token>\n\n\ndef copy_repo(repo, destdir):\n \"\"\"Copies a cached repository into a directory using cp.\n\n This also fixes up the repository afterwards, so that it can contain\n code etc. It does not leave any given branch ready for use.\n\n \"\"\"\n call(['cp', '-a', repo, os.path.join(destdir, '.git')])\n call(['git', 'config', 'core.bare', 'false'])\n call(['git', 'config', '--unset', 'remote.origin.mirror'])\n with open(os.devnull, 'w') as fnull:\n call(['git', 'config', 'remote.origin.fetch',\n '+refs/heads/*:refs/remotes/origin/*'], stdout=fnull, stderr=fnull)\n call(['git', 'config', 'remote.origin.url', repo])\n call(['git', 'pack-refs', '--all', '--prune'])\n with open(os.path.join(destdir, '.git', 'packed-refs'), 'r') as ref_fh:\n pack_lines = ref_fh.read().split('\\n')\n with open(os.path.join(destdir, '.git', 'packed-refs'), 'w') as ref_fh:\n ref_fh.write(pack_lines.pop(0) + '\\n')\n for refline in pack_lines:\n if ' refs/remotes/' in refline:\n continue\n if ' refs/heads/' in refline:\n sha, ref = refline[:40], refline[41:]\n if ref.startswith('refs/heads/'):\n ref = 'refs/remotes/origin/' + ref[11:]\n refline = '%s %s' % (sha, ref)\n ref_fh.write('%s\\n' % refline)\n with open(os.devnull, 'w') as fnull:\n call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull,\n stderr=fnull)\n\n\n<mask token>\n\n\ndef checkout_submodules(name, ref):\n app.log(name, 'Git submodules')\n with open('.gitmodules', 'r') as gitfile:\n content = '\\n'.join([l.strip() for l in gitfile.read().splitlines()])\n io = StringIO.StringIO(content)\n parser = ConfigParser.RawConfigParser()\n parser.readfp(io)\n for section in parser.sections():\n submodule = re.sub('submodule \"(.*)\"', '\\\\1', section)\n url = parser.get(section, 'url')\n path = parser.get(section, 'path')\n try:\n commit = check_output(['git', 'ls-tree', ref, path])\n fields = commit.split()\n if len(fields) >= 2 and fields[1] == 'commit':\n submodule_commit = commit.split()[2]\n if len(submodule_commit) != 40:\n raise Exception\n fulldir = os.path.join(os.getcwd(), path)\n checkout(submodule, url, submodule_commit, fulldir)\n else:\n app.log(this, \n 'Skipping submodule \"%s\" as %s:%s has a non-commit object for it'\n % (name, url))\n except:\n app.log(name, 'ERROR: Git submodules problem')\n raise SystemExit\n", "step-2": "<mask token>\n\n\ndef get_repo_url(repo):\n url = repo.replace('upstream:', 'git://git.baserock.org/delta/')\n url = url.replace('baserock:baserock/',\n 'git://git.baserock.org/baserock/baserock/')\n url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/')\n url = url.replace('github:', 'git://github.com/')\n url = url.replace('gnome:', 'git://git.gnome.org')\n if url.endswith('.git'):\n url = url[:-4]\n return url\n\n\ndef get_repo_name(repo):\n \"\"\" Convert URIs to strings that only contain digits, letters, _ and %.\n\n NOTE: When changing the code of this function, make sure to also apply\n the same to the quote_url() function of lorry. Otherwise the git tarballs\n generated by lorry may no longer be found by morph.\n\n \"\"\"\n valid_chars = string.digits + string.ascii_letters + '%_'\n transl = lambda x: x if x in valid_chars else '_'\n return ''.join([transl(x) for x in get_repo_url(repo)])\n\n\ndef get_upstream_version(repo, ref):\n try:\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n with app.chdir(gitdir), open(os.devnull, 'w') as fnull:\n last_tag = check_output(['git', 'describe', '--abbrev=0',\n '--tags', ref], stderr=fnull)[0:-1]\n commits = check_output(['git', 'rev-list', last_tag + '..' +\n ref, '--count'])\n result = '%s (%s + %s commits)' % (ref[:8], last_tag, commits[0:-1])\n except:\n result = ref[:8] + ' ' + '(No tag found)'\n return result\n\n\ndef get_tree(this):\n ref = this['ref']\n gitdir = os.path.join(app.settings['gits'], get_repo_name(this['repo']))\n if not os.path.exists(gitdir):\n try:\n url = app.settings['cache-server-url'] + 'repo=' + get_repo_url(\n this['repo']) + '&ref=' + ref\n with urllib2.urlopen(url) as response:\n tree = json.loads(response.read().decode())['tree']\n return tree\n except:\n app.log(this, 'WARNING: no tree from cache-server', ref)\n mirror(this['name'], this['repo'])\n with app.chdir(gitdir), open(os.devnull, 'w') as fnull:\n if call(['git', 'rev-parse', ref + '^{object}'], stdout=fnull,\n stderr=fnull):\n call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull)\n try:\n tree = check_output(['git', 'rev-parse', ref + '^{tree}'],\n universal_newlines=True)[0:-1]\n return tree\n except:\n app.log(this, 'ERROR: could not find tree for ref', ref)\n raise SystemExit\n\n\ndef copy_repo(repo, destdir):\n \"\"\"Copies a cached repository into a directory using cp.\n\n This also fixes up the repository afterwards, so that it can contain\n code etc. It does not leave any given branch ready for use.\n\n \"\"\"\n call(['cp', '-a', repo, os.path.join(destdir, '.git')])\n call(['git', 'config', 'core.bare', 'false'])\n call(['git', 'config', '--unset', 'remote.origin.mirror'])\n with open(os.devnull, 'w') as fnull:\n call(['git', 'config', 'remote.origin.fetch',\n '+refs/heads/*:refs/remotes/origin/*'], stdout=fnull, stderr=fnull)\n call(['git', 'config', 'remote.origin.url', repo])\n call(['git', 'pack-refs', '--all', '--prune'])\n with open(os.path.join(destdir, '.git', 'packed-refs'), 'r') as ref_fh:\n pack_lines = ref_fh.read().split('\\n')\n with open(os.path.join(destdir, '.git', 'packed-refs'), 'w') as ref_fh:\n ref_fh.write(pack_lines.pop(0) + '\\n')\n for refline in pack_lines:\n if ' refs/remotes/' in refline:\n continue\n if ' refs/heads/' in refline:\n sha, ref = refline[:40], refline[41:]\n if ref.startswith('refs/heads/'):\n ref = 'refs/remotes/origin/' + ref[11:]\n refline = '%s %s' % (sha, ref)\n ref_fh.write('%s\\n' % refline)\n with open(os.devnull, 'w') as fnull:\n call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull,\n stderr=fnull)\n\n\n<mask token>\n\n\ndef checkout(name, repo, ref, checkoutdir):\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n if not os.path.exists(gitdir):\n mirror(name, repo)\n app.log(name, 'Upstream version:', get_upstream_version(repo, ref))\n app.log(name, 'Git checkout %s in %s' % (repo, checkoutdir))\n with app.chdir(checkoutdir), open(os.devnull, 'w') as fnull:\n copy_repo(gitdir, checkoutdir)\n if call(['git', 'checkout', ref], stdout=fnull, stderr=fnull):\n app.log(name, 'ERROR: git checkout failed for', ref)\n raise SystemExit\n if os.path.exists('.gitmodules'):\n checkout_submodules(name, ref)\n utils.set_mtime_recursively(checkoutdir)\n\n\ndef checkout_submodules(name, ref):\n app.log(name, 'Git submodules')\n with open('.gitmodules', 'r') as gitfile:\n content = '\\n'.join([l.strip() for l in gitfile.read().splitlines()])\n io = StringIO.StringIO(content)\n parser = ConfigParser.RawConfigParser()\n parser.readfp(io)\n for section in parser.sections():\n submodule = re.sub('submodule \"(.*)\"', '\\\\1', section)\n url = parser.get(section, 'url')\n path = parser.get(section, 'path')\n try:\n commit = check_output(['git', 'ls-tree', ref, path])\n fields = commit.split()\n if len(fields) >= 2 and fields[1] == 'commit':\n submodule_commit = commit.split()[2]\n if len(submodule_commit) != 40:\n raise Exception\n fulldir = os.path.join(os.getcwd(), path)\n checkout(submodule, url, submodule_commit, fulldir)\n else:\n app.log(this, \n 'Skipping submodule \"%s\" as %s:%s has a non-commit object for it'\n % (name, url))\n except:\n app.log(name, 'ERROR: Git submodules problem')\n raise SystemExit\n", "step-3": "<mask token>\n\n\ndef get_repo_url(repo):\n url = repo.replace('upstream:', 'git://git.baserock.org/delta/')\n url = url.replace('baserock:baserock/',\n 'git://git.baserock.org/baserock/baserock/')\n url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/')\n url = url.replace('github:', 'git://github.com/')\n url = url.replace('gnome:', 'git://git.gnome.org')\n if url.endswith('.git'):\n url = url[:-4]\n return url\n\n\ndef get_repo_name(repo):\n \"\"\" Convert URIs to strings that only contain digits, letters, _ and %.\n\n NOTE: When changing the code of this function, make sure to also apply\n the same to the quote_url() function of lorry. Otherwise the git tarballs\n generated by lorry may no longer be found by morph.\n\n \"\"\"\n valid_chars = string.digits + string.ascii_letters + '%_'\n transl = lambda x: x if x in valid_chars else '_'\n return ''.join([transl(x) for x in get_repo_url(repo)])\n\n\ndef get_upstream_version(repo, ref):\n try:\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n with app.chdir(gitdir), open(os.devnull, 'w') as fnull:\n last_tag = check_output(['git', 'describe', '--abbrev=0',\n '--tags', ref], stderr=fnull)[0:-1]\n commits = check_output(['git', 'rev-list', last_tag + '..' +\n ref, '--count'])\n result = '%s (%s + %s commits)' % (ref[:8], last_tag, commits[0:-1])\n except:\n result = ref[:8] + ' ' + '(No tag found)'\n return result\n\n\ndef get_tree(this):\n ref = this['ref']\n gitdir = os.path.join(app.settings['gits'], get_repo_name(this['repo']))\n if not os.path.exists(gitdir):\n try:\n url = app.settings['cache-server-url'] + 'repo=' + get_repo_url(\n this['repo']) + '&ref=' + ref\n with urllib2.urlopen(url) as response:\n tree = json.loads(response.read().decode())['tree']\n return tree\n except:\n app.log(this, 'WARNING: no tree from cache-server', ref)\n mirror(this['name'], this['repo'])\n with app.chdir(gitdir), open(os.devnull, 'w') as fnull:\n if call(['git', 'rev-parse', ref + '^{object}'], stdout=fnull,\n stderr=fnull):\n call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull)\n try:\n tree = check_output(['git', 'rev-parse', ref + '^{tree}'],\n universal_newlines=True)[0:-1]\n return tree\n except:\n app.log(this, 'ERROR: could not find tree for ref', ref)\n raise SystemExit\n\n\ndef copy_repo(repo, destdir):\n \"\"\"Copies a cached repository into a directory using cp.\n\n This also fixes up the repository afterwards, so that it can contain\n code etc. It does not leave any given branch ready for use.\n\n \"\"\"\n call(['cp', '-a', repo, os.path.join(destdir, '.git')])\n call(['git', 'config', 'core.bare', 'false'])\n call(['git', 'config', '--unset', 'remote.origin.mirror'])\n with open(os.devnull, 'w') as fnull:\n call(['git', 'config', 'remote.origin.fetch',\n '+refs/heads/*:refs/remotes/origin/*'], stdout=fnull, stderr=fnull)\n call(['git', 'config', 'remote.origin.url', repo])\n call(['git', 'pack-refs', '--all', '--prune'])\n with open(os.path.join(destdir, '.git', 'packed-refs'), 'r') as ref_fh:\n pack_lines = ref_fh.read().split('\\n')\n with open(os.path.join(destdir, '.git', 'packed-refs'), 'w') as ref_fh:\n ref_fh.write(pack_lines.pop(0) + '\\n')\n for refline in pack_lines:\n if ' refs/remotes/' in refline:\n continue\n if ' refs/heads/' in refline:\n sha, ref = refline[:40], refline[41:]\n if ref.startswith('refs/heads/'):\n ref = 'refs/remotes/origin/' + ref[11:]\n refline = '%s %s' % (sha, ref)\n ref_fh.write('%s\\n' % refline)\n with open(os.devnull, 'w') as fnull:\n call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull,\n stderr=fnull)\n\n\ndef mirror(name, repo):\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n repo_url = get_repo_url(repo)\n try:\n os.makedirs(gitdir)\n tar_file = get_repo_name(repo_url) + '.tar'\n app.log(name, 'Try fetching tarball %s' % tar_file)\n with app.chdir(gitdir), open(os.devnull, 'w') as fnull:\n call(['wget', app['tar-url']], stdout=fnull, stderr=fnull)\n call(['tar', 'xf', tar_file], stdout=fnull, stderr=fnull)\n os.remove(tar_file)\n call(['git', 'config', 'remote.origin.url', repo_url], stdout=\n fnull, stderr=fnull)\n call(['git', 'config', 'remote.origin.mirror', 'true'], stdout=\n fnull, stderr=fnull)\n if call(['git', 'config', 'remote.origin.fetch',\n '+refs/*:refs/*'], stdout=fnull, stderr=fnull) != 0:\n raise BaseException('Did not get a valid git repo')\n call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull)\n except:\n app.log(name, 'Using git clone from ', repo_url)\n try:\n with open(os.devnull, 'w') as fnull:\n call(['git', 'clone', '--mirror', '-n', repo_url, gitdir],\n stdout=fnull, stderr=fnull)\n except:\n app.log(name, 'ERROR: failed to clone', repo)\n raise SystemExit\n app.log(name, 'Git repo is mirrored at', gitdir)\n\n\n<mask token>\n\n\ndef checkout(name, repo, ref, checkoutdir):\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n if not os.path.exists(gitdir):\n mirror(name, repo)\n app.log(name, 'Upstream version:', get_upstream_version(repo, ref))\n app.log(name, 'Git checkout %s in %s' % (repo, checkoutdir))\n with app.chdir(checkoutdir), open(os.devnull, 'w') as fnull:\n copy_repo(gitdir, checkoutdir)\n if call(['git', 'checkout', ref], stdout=fnull, stderr=fnull):\n app.log(name, 'ERROR: git checkout failed for', ref)\n raise SystemExit\n if os.path.exists('.gitmodules'):\n checkout_submodules(name, ref)\n utils.set_mtime_recursively(checkoutdir)\n\n\ndef checkout_submodules(name, ref):\n app.log(name, 'Git submodules')\n with open('.gitmodules', 'r') as gitfile:\n content = '\\n'.join([l.strip() for l in gitfile.read().splitlines()])\n io = StringIO.StringIO(content)\n parser = ConfigParser.RawConfigParser()\n parser.readfp(io)\n for section in parser.sections():\n submodule = re.sub('submodule \"(.*)\"', '\\\\1', section)\n url = parser.get(section, 'url')\n path = parser.get(section, 'path')\n try:\n commit = check_output(['git', 'ls-tree', ref, path])\n fields = commit.split()\n if len(fields) >= 2 and fields[1] == 'commit':\n submodule_commit = commit.split()[2]\n if len(submodule_commit) != 40:\n raise Exception\n fulldir = os.path.join(os.getcwd(), path)\n checkout(submodule, url, submodule_commit, fulldir)\n else:\n app.log(this, \n 'Skipping submodule \"%s\" as %s:%s has a non-commit object for it'\n % (name, url))\n except:\n app.log(name, 'ERROR: Git submodules problem')\n raise SystemExit\n", "step-4": "import os\nimport app\nimport re\nfrom subprocess import call\nfrom subprocess import check_output\nimport string\nimport definitions\nimport urllib2\nimport json\nimport utils\nimport ConfigParser\nimport StringIO\nimport re\n\n\ndef get_repo_url(repo):\n url = repo.replace('upstream:', 'git://git.baserock.org/delta/')\n url = url.replace('baserock:baserock/',\n 'git://git.baserock.org/baserock/baserock/')\n url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/')\n url = url.replace('github:', 'git://github.com/')\n url = url.replace('gnome:', 'git://git.gnome.org')\n if url.endswith('.git'):\n url = url[:-4]\n return url\n\n\ndef get_repo_name(repo):\n \"\"\" Convert URIs to strings that only contain digits, letters, _ and %.\n\n NOTE: When changing the code of this function, make sure to also apply\n the same to the quote_url() function of lorry. Otherwise the git tarballs\n generated by lorry may no longer be found by morph.\n\n \"\"\"\n valid_chars = string.digits + string.ascii_letters + '%_'\n transl = lambda x: x if x in valid_chars else '_'\n return ''.join([transl(x) for x in get_repo_url(repo)])\n\n\ndef get_upstream_version(repo, ref):\n try:\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n with app.chdir(gitdir), open(os.devnull, 'w') as fnull:\n last_tag = check_output(['git', 'describe', '--abbrev=0',\n '--tags', ref], stderr=fnull)[0:-1]\n commits = check_output(['git', 'rev-list', last_tag + '..' +\n ref, '--count'])\n result = '%s (%s + %s commits)' % (ref[:8], last_tag, commits[0:-1])\n except:\n result = ref[:8] + ' ' + '(No tag found)'\n return result\n\n\ndef get_tree(this):\n ref = this['ref']\n gitdir = os.path.join(app.settings['gits'], get_repo_name(this['repo']))\n if not os.path.exists(gitdir):\n try:\n url = app.settings['cache-server-url'] + 'repo=' + get_repo_url(\n this['repo']) + '&ref=' + ref\n with urllib2.urlopen(url) as response:\n tree = json.loads(response.read().decode())['tree']\n return tree\n except:\n app.log(this, 'WARNING: no tree from cache-server', ref)\n mirror(this['name'], this['repo'])\n with app.chdir(gitdir), open(os.devnull, 'w') as fnull:\n if call(['git', 'rev-parse', ref + '^{object}'], stdout=fnull,\n stderr=fnull):\n call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull)\n try:\n tree = check_output(['git', 'rev-parse', ref + '^{tree}'],\n universal_newlines=True)[0:-1]\n return tree\n except:\n app.log(this, 'ERROR: could not find tree for ref', ref)\n raise SystemExit\n\n\ndef copy_repo(repo, destdir):\n \"\"\"Copies a cached repository into a directory using cp.\n\n This also fixes up the repository afterwards, so that it can contain\n code etc. It does not leave any given branch ready for use.\n\n \"\"\"\n call(['cp', '-a', repo, os.path.join(destdir, '.git')])\n call(['git', 'config', 'core.bare', 'false'])\n call(['git', 'config', '--unset', 'remote.origin.mirror'])\n with open(os.devnull, 'w') as fnull:\n call(['git', 'config', 'remote.origin.fetch',\n '+refs/heads/*:refs/remotes/origin/*'], stdout=fnull, stderr=fnull)\n call(['git', 'config', 'remote.origin.url', repo])\n call(['git', 'pack-refs', '--all', '--prune'])\n with open(os.path.join(destdir, '.git', 'packed-refs'), 'r') as ref_fh:\n pack_lines = ref_fh.read().split('\\n')\n with open(os.path.join(destdir, '.git', 'packed-refs'), 'w') as ref_fh:\n ref_fh.write(pack_lines.pop(0) + '\\n')\n for refline in pack_lines:\n if ' refs/remotes/' in refline:\n continue\n if ' refs/heads/' in refline:\n sha, ref = refline[:40], refline[41:]\n if ref.startswith('refs/heads/'):\n ref = 'refs/remotes/origin/' + ref[11:]\n refline = '%s %s' % (sha, ref)\n ref_fh.write('%s\\n' % refline)\n with open(os.devnull, 'w') as fnull:\n call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull,\n stderr=fnull)\n\n\ndef mirror(name, repo):\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n repo_url = get_repo_url(repo)\n try:\n os.makedirs(gitdir)\n tar_file = get_repo_name(repo_url) + '.tar'\n app.log(name, 'Try fetching tarball %s' % tar_file)\n with app.chdir(gitdir), open(os.devnull, 'w') as fnull:\n call(['wget', app['tar-url']], stdout=fnull, stderr=fnull)\n call(['tar', 'xf', tar_file], stdout=fnull, stderr=fnull)\n os.remove(tar_file)\n call(['git', 'config', 'remote.origin.url', repo_url], stdout=\n fnull, stderr=fnull)\n call(['git', 'config', 'remote.origin.mirror', 'true'], stdout=\n fnull, stderr=fnull)\n if call(['git', 'config', 'remote.origin.fetch',\n '+refs/*:refs/*'], stdout=fnull, stderr=fnull) != 0:\n raise BaseException('Did not get a valid git repo')\n call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull)\n except:\n app.log(name, 'Using git clone from ', repo_url)\n try:\n with open(os.devnull, 'w') as fnull:\n call(['git', 'clone', '--mirror', '-n', repo_url, gitdir],\n stdout=fnull, stderr=fnull)\n except:\n app.log(name, 'ERROR: failed to clone', repo)\n raise SystemExit\n app.log(name, 'Git repo is mirrored at', gitdir)\n\n\ndef fetch(repo):\n with app.chdir(repo), open(os.devnull, 'w') as fnull:\n call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull)\n\n\ndef checkout(name, repo, ref, checkoutdir):\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n if not os.path.exists(gitdir):\n mirror(name, repo)\n app.log(name, 'Upstream version:', get_upstream_version(repo, ref))\n app.log(name, 'Git checkout %s in %s' % (repo, checkoutdir))\n with app.chdir(checkoutdir), open(os.devnull, 'w') as fnull:\n copy_repo(gitdir, checkoutdir)\n if call(['git', 'checkout', ref], stdout=fnull, stderr=fnull):\n app.log(name, 'ERROR: git checkout failed for', ref)\n raise SystemExit\n if os.path.exists('.gitmodules'):\n checkout_submodules(name, ref)\n utils.set_mtime_recursively(checkoutdir)\n\n\ndef checkout_submodules(name, ref):\n app.log(name, 'Git submodules')\n with open('.gitmodules', 'r') as gitfile:\n content = '\\n'.join([l.strip() for l in gitfile.read().splitlines()])\n io = StringIO.StringIO(content)\n parser = ConfigParser.RawConfigParser()\n parser.readfp(io)\n for section in parser.sections():\n submodule = re.sub('submodule \"(.*)\"', '\\\\1', section)\n url = parser.get(section, 'url')\n path = parser.get(section, 'path')\n try:\n commit = check_output(['git', 'ls-tree', ref, path])\n fields = commit.split()\n if len(fields) >= 2 and fields[1] == 'commit':\n submodule_commit = commit.split()[2]\n if len(submodule_commit) != 40:\n raise Exception\n fulldir = os.path.join(os.getcwd(), path)\n checkout(submodule, url, submodule_commit, fulldir)\n else:\n app.log(this, \n 'Skipping submodule \"%s\" as %s:%s has a non-commit object for it'\n % (name, url))\n except:\n app.log(name, 'ERROR: Git submodules problem')\n raise SystemExit\n", "step-5": "#!/usr/bin/env python3\n#\n# Copyright (C) 2011-2015 Codethink Limited\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n#\n# =*= License: GPL-2 =*=\n\nimport os\nimport app\nimport re\nfrom subprocess import call\nfrom subprocess import check_output\nimport string\nimport definitions\nimport urllib2\nimport json\nimport utils\nimport ConfigParser\nimport StringIO\nimport re\n\n\ndef get_repo_url(repo):\n url = repo.replace('upstream:', 'git://git.baserock.org/delta/')\n url = url.replace('baserock:baserock/',\n 'git://git.baserock.org/baserock/baserock/')\n url = url.replace('freedesktop:', 'git://anongit.freedesktop.org/')\n url = url.replace('github:', 'git://github.com/')\n url = url.replace('gnome:', 'git://git.gnome.org')\n if url.endswith('.git'):\n url = url[:-4]\n return url\n\n\ndef get_repo_name(repo):\n ''' Convert URIs to strings that only contain digits, letters, _ and %.\n\n NOTE: When changing the code of this function, make sure to also apply\n the same to the quote_url() function of lorry. Otherwise the git tarballs\n generated by lorry may no longer be found by morph.\n\n '''\n valid_chars = string.digits + string.ascii_letters + '%_'\n transl = lambda x: x if x in valid_chars else '_'\n return ''.join([transl(x) for x in get_repo_url(repo)])\n\n\ndef get_upstream_version(repo, ref):\n try:\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n with app.chdir(gitdir), open(os.devnull, \"w\") as fnull:\n last_tag = check_output(['git', 'describe', '--abbrev=0',\n '--tags', ref], stderr=fnull)[0:-1]\n commits = check_output(['git', 'rev-list', last_tag + '..' + ref,\n '--count'])\n\n result = \"%s (%s + %s commits)\" % (ref[:8], last_tag, commits[0:-1])\n except:\n result = ref[:8] + \" \" + \"(No tag found)\"\n\n return result\n\n\ndef get_tree(this):\n ref = this['ref']\n gitdir = os.path.join(app.settings['gits'], get_repo_name(this['repo']))\n if not os.path.exists(gitdir):\n try:\n url = (app.settings['cache-server-url'] + 'repo='\n + get_repo_url(this['repo']) + '&ref=' + ref)\n with urllib2.urlopen(url) as response:\n tree = json.loads(response.read().decode())['tree']\n return tree\n except:\n app.log(this, 'WARNING: no tree from cache-server', ref)\n mirror(this['name'], this['repo'])\n\n with app.chdir(gitdir), open(os.devnull, \"w\") as fnull:\n if call(['git', 'rev-parse', ref + '^{object}'], stdout=fnull,\n stderr=fnull):\n # can't resolve this ref. is it upstream?\n call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull)\n\n try:\n tree = check_output(['git', 'rev-parse', ref + '^{tree}'],\n universal_newlines=True)[0:-1]\n return tree\n\n except:\n # either we don't have a git dir, or ref is not unique\n # or ref does not exist\n\n app.log(this, 'ERROR: could not find tree for ref', ref)\n raise SystemExit\n\n\ndef copy_repo(repo, destdir):\n '''Copies a cached repository into a directory using cp.\n\n This also fixes up the repository afterwards, so that it can contain\n code etc. It does not leave any given branch ready for use.\n\n '''\n\n # core.bare should be false so that git believes work trees are possible\n # we do not want the origin remote to behave as a mirror for pulls\n # we want a traditional refs/heads -> refs/remotes/origin ref mapping\n # set the origin url to the cached repo so that we can quickly clean up\n # by packing the refs, we can then edit then en-masse easily\n call(['cp', '-a', repo, os.path.join(destdir, '.git')])\n call(['git', 'config', 'core.bare', 'false'])\n call(['git', 'config', '--unset', 'remote.origin.mirror'])\n with open(os.devnull, \"w\") as fnull:\n call(['git', 'config', 'remote.origin.fetch',\n '+refs/heads/*:refs/remotes/origin/*'],\n stdout=fnull,\n stderr=fnull)\n call(['git', 'config', 'remote.origin.url', repo])\n call(['git', 'pack-refs', '--all', '--prune'])\n\n # turn refs/heads/* into refs/remotes/origin/* in the packed refs\n # so that the new copy behaves more like a traditional clone.\n with open(os.path.join(destdir, \".git\", \"packed-refs\"), \"r\") as ref_fh:\n pack_lines = ref_fh.read().split(\"\\n\")\n with open(os.path.join(destdir, \".git\", \"packed-refs\"), \"w\") as ref_fh:\n ref_fh.write(pack_lines.pop(0) + \"\\n\")\n for refline in pack_lines:\n if ' refs/remotes/' in refline:\n continue\n if ' refs/heads/' in refline:\n sha, ref = refline[:40], refline[41:]\n if ref.startswith(\"refs/heads/\"):\n ref = \"refs/remotes/origin/\" + ref[11:]\n refline = \"%s %s\" % (sha, ref)\n ref_fh.write(\"%s\\n\" % (refline))\n # Finally run a remote update to clear up the refs ready for use.\n with open(os.devnull, \"w\") as fnull:\n call(['git', 'remote', 'update', 'origin', '--prune'], stdout=fnull,\n stderr=fnull)\n\n\ndef mirror(name, repo):\n # try tarball first\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n repo_url = get_repo_url(repo)\n try:\n os.makedirs(gitdir)\n tar_file = get_repo_name(repo_url) + '.tar'\n app.log(name, 'Try fetching tarball %s' % tar_file)\n with app.chdir(gitdir), open(os.devnull, \"w\") as fnull:\n call(['wget', app['tar-url']], stdout=fnull, stderr=fnull)\n call(['tar', 'xf', tar_file], stdout=fnull, stderr=fnull)\n os.remove(tar_file)\n call(['git', 'config', 'remote.origin.url', repo_url],\n stdout=fnull, stderr=fnull)\n call(['git', 'config', 'remote.origin.mirror', 'true'],\n stdout=fnull, stderr=fnull)\n if call(['git', 'config', 'remote.origin.fetch',\n '+refs/*:refs/*'],\n stdout=fnull, stderr=fnull) != 0:\n raise BaseException('Did not get a valid git repo')\n call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull)\n except:\n app.log(name, 'Using git clone from ', repo_url)\n try:\n with open(os.devnull, \"w\") as fnull:\n call(['git', 'clone', '--mirror', '-n', repo_url, gitdir],\n stdout=fnull, stderr=fnull)\n except:\n app.log(name, 'ERROR: failed to clone', repo)\n raise SystemExit\n\n app.log(name, 'Git repo is mirrored at', gitdir)\n\n\ndef fetch(repo):\n with app.chdir(repo), open(os.devnull, \"w\") as fnull:\n call(['git', 'fetch', 'origin'], stdout=fnull, stderr=fnull)\n\n\ndef checkout(name, repo, ref, checkoutdir):\n gitdir = os.path.join(app.settings['gits'], get_repo_name(repo))\n if not os.path.exists(gitdir):\n mirror(name, repo)\n app.log(name, 'Upstream version:', get_upstream_version(repo, ref))\n app.log(name, 'Git checkout %s in %s' % (repo, checkoutdir))\n # checkout the required version of this from git\n with app.chdir(checkoutdir), open(os.devnull, \"w\") as fnull:\n copy_repo(gitdir, checkoutdir)\n if call(['git', 'checkout', ref], stdout=fnull, stderr=fnull):\n app.log(name, 'ERROR: git checkout failed for', ref)\n raise SystemExit\n\n if os.path.exists('.gitmodules'):\n checkout_submodules(name, ref)\n\n utils.set_mtime_recursively(checkoutdir)\n\n\ndef checkout_submodules(name, ref):\n app.log(name, 'Git submodules')\n with open('.gitmodules', \"r\") as gitfile:\n # drop indentation in sections, as RawConfigParser cannot handle it\n content = '\\n'.join([l.strip() for l in gitfile.read().splitlines()])\n io = StringIO.StringIO(content)\n parser = ConfigParser.RawConfigParser()\n parser.readfp(io)\n\n for section in parser.sections():\n # validate section name against the 'submodule \"foo\"' pattern\n submodule = re.sub(r'submodule \"(.*)\"', r'\\1', section)\n url = parser.get(section, 'url')\n path = parser.get(section, 'path')\n\n try:\n # list objects in the parent repo tree to find the commit\n # object that corresponds to the submodule\n commit = check_output(['git', 'ls-tree', ref, path])\n\n # read the commit hash from the output\n fields = commit.split()\n if len(fields) >= 2 and fields[1] == 'commit':\n submodule_commit = commit.split()[2]\n\n # fail if the commit hash is invalid\n if len(submodule_commit) != 40:\n raise Exception\n\n fulldir = os.path.join(os.getcwd(), path)\n checkout(submodule, url, submodule_commit, fulldir)\n\n else:\n app.log(this, 'Skipping submodule \"%s\" as %s:%s has '\n 'a non-commit object for it' % (name, url))\n\n except:\n app.log(name, \"ERROR: Git submodules problem\")\n raise SystemExit\n", "step-ids": [ 5, 7, 8, 10, 11 ] }
[ 5, 7, 8, 10, 11 ]
import rospy #: the parameter namespace for the arni_countermeasure node ARNI_CTM_NS = "arni/countermeasure/" #: the parameter namespace for configuration files #: of the arni_countermeasure node ARNI_CTM_CFG_NS = ARNI_CTM_NS + "config/" def get_param_num(param): #dummy val value = 1 try: value = rospy.get_param(param) if not isinstance(value, (int, float, long)): err_msg = ( "Param %s is not an number" % param) rospy.logerr(err_msg) rospy.signal_shutdown(err_msg) except KeyError: err_msg = ( "Param %s is not set" % param + " and its default value has been forcefully removed") rospy.logerr(err_msg) rospy.signal_shutdown(err_msg) return value def get_param_duration(param): """Calls rospy.get_param and logs errors. Logs if the param does not exist or is not parsable to rospy.Durotation. And calls rospy.signal_shutdown if the value is invalid/not existing. :return: The Param param from the parameter server. :rtype: rospy.Duration """ # dummy value value = rospy.Duration(1) try: # only a default value in case the param gets fuzzed. value = rospy.Duration(get_param_num(param)) except ValueError: err_msg = ( "Param %s has the invalid value '%s'." % (param, rospy.get_param(param))) rospy.logerr(err_msg) rospy.signal_shutdown(err_msg) value = rospy.Duration(1) return value
normal
{ "blob_id": "70c9d75dabfa9eac23e34f94f34d39c08e21b3c0", "index": 6070, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_param_num(param):\n value = 1\n try:\n value = rospy.get_param(param)\n if not isinstance(value, (int, float, long)):\n err_msg = 'Param %s is not an number' % param\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n except KeyError:\n err_msg = ('Param %s is not set' % param +\n ' and its default value has been forcefully removed')\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n return value\n\n\ndef get_param_duration(param):\n \"\"\"Calls rospy.get_param and logs errors.\n\n Logs if the param does not exist or is not parsable to rospy.Durotation.\n And calls rospy.signal_shutdown if the value is invalid/not existing.\n\n :return: The Param param from the parameter server.\n :rtype: rospy.Duration\n\n \"\"\"\n value = rospy.Duration(1)\n try:\n value = rospy.Duration(get_param_num(param))\n except ValueError:\n err_msg = \"Param %s has the invalid value '%s'.\" % (param, rospy.\n get_param(param))\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n value = rospy.Duration(1)\n return value\n", "step-3": "<mask token>\nARNI_CTM_NS = 'arni/countermeasure/'\nARNI_CTM_CFG_NS = ARNI_CTM_NS + 'config/'\n\n\ndef get_param_num(param):\n value = 1\n try:\n value = rospy.get_param(param)\n if not isinstance(value, (int, float, long)):\n err_msg = 'Param %s is not an number' % param\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n except KeyError:\n err_msg = ('Param %s is not set' % param +\n ' and its default value has been forcefully removed')\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n return value\n\n\ndef get_param_duration(param):\n \"\"\"Calls rospy.get_param and logs errors.\n\n Logs if the param does not exist or is not parsable to rospy.Durotation.\n And calls rospy.signal_shutdown if the value is invalid/not existing.\n\n :return: The Param param from the parameter server.\n :rtype: rospy.Duration\n\n \"\"\"\n value = rospy.Duration(1)\n try:\n value = rospy.Duration(get_param_num(param))\n except ValueError:\n err_msg = \"Param %s has the invalid value '%s'.\" % (param, rospy.\n get_param(param))\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n value = rospy.Duration(1)\n return value\n", "step-4": "import rospy\nARNI_CTM_NS = 'arni/countermeasure/'\nARNI_CTM_CFG_NS = ARNI_CTM_NS + 'config/'\n\n\ndef get_param_num(param):\n value = 1\n try:\n value = rospy.get_param(param)\n if not isinstance(value, (int, float, long)):\n err_msg = 'Param %s is not an number' % param\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n except KeyError:\n err_msg = ('Param %s is not set' % param +\n ' and its default value has been forcefully removed')\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n return value\n\n\ndef get_param_duration(param):\n \"\"\"Calls rospy.get_param and logs errors.\n\n Logs if the param does not exist or is not parsable to rospy.Durotation.\n And calls rospy.signal_shutdown if the value is invalid/not existing.\n\n :return: The Param param from the parameter server.\n :rtype: rospy.Duration\n\n \"\"\"\n value = rospy.Duration(1)\n try:\n value = rospy.Duration(get_param_num(param))\n except ValueError:\n err_msg = \"Param %s has the invalid value '%s'.\" % (param, rospy.\n get_param(param))\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n value = rospy.Duration(1)\n return value\n", "step-5": "import rospy\n\n#: the parameter namespace for the arni_countermeasure node\nARNI_CTM_NS = \"arni/countermeasure/\"\n\n#: the parameter namespace for configuration files\n#: of the arni_countermeasure node\nARNI_CTM_CFG_NS = ARNI_CTM_NS + \"config/\"\n\n\ndef get_param_num(param):\n\n #dummy val\n value = 1\n try:\n value = rospy.get_param(param)\n if not isinstance(value, (int, float, long)):\n err_msg = (\n \"Param %s is not an number\" % param)\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n except KeyError:\n err_msg = (\n \"Param %s is not set\" % param\n + \" and its default value has been forcefully removed\")\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n return value\n\n\ndef get_param_duration(param):\n \"\"\"Calls rospy.get_param and logs errors.\n\n Logs if the param does not exist or is not parsable to rospy.Durotation.\n And calls rospy.signal_shutdown if the value is invalid/not existing.\n\n :return: The Param param from the parameter server.\n :rtype: rospy.Duration\n\n \"\"\"\n\n # dummy value\n value = rospy.Duration(1)\n\n try:\n # only a default value in case the param gets fuzzed.\n value = rospy.Duration(get_param_num(param))\n except ValueError:\n err_msg = (\n \"Param %s has the invalid value '%s'.\"\n % (param, rospy.get_param(param)))\n rospy.logerr(err_msg)\n rospy.signal_shutdown(err_msg)\n value = rospy.Duration(1)\n return value\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
import sys filepath = 'input.txt' def intersection(list1, list2): return set(list1).intersection(list2) def computeSteps(x, y, step, steps): # build dictionary with steps for each point curr = 0 if (x,y) in steps: curr = steps.get((x,y)) steps[(x,y)] = step + curr def buildPoints(wire, steps): points = [] x, y = 0, 0 s = 0 for p in wire: direction = p[0] step = int(p[1:]) if direction == 'D': for i in range(0, step): y -= 1 points.append((x,y)) s += 1 computeSteps(x, y, s, steps) elif direction == 'U': for i in range(0, step): y += 1 points.append((x,y)) s += 1 computeSteps(x, y, s, steps) elif direction == 'L': for i in range(0, step): x -= 1 points.append((x,y)) s += 1 computeSteps(x, y, s, steps) elif direction == 'R': for i in range(0, step): x += 1 points.append((x,y)) s += 1 computeSteps(x, y, s, steps) #end for return points with open(filepath) as fp: steps = {} port = (0,0) wire1 = fp.readline().strip().split(',') wire2 = fp.readline().strip().split(',') point1 = buildPoints(wire1, steps) point2 = buildPoints(wire2, steps) commonPoints = intersection(point1, point2) min = sys.maxsize for k in commonPoints: val = steps.get(k) if val < min: min = val print(min)
normal
{ "blob_id": "e9e119dd69f9416e007e748d7f494741140efc8e", "index": 8182, "step-1": "<mask token>\n\n\ndef intersection(list1, list2):\n return set(list1).intersection(list2)\n\n\ndef computeSteps(x, y, step, steps):\n curr = 0\n if (x, y) in steps:\n curr = steps.get((x, y))\n steps[x, y] = step + curr\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef intersection(list1, list2):\n return set(list1).intersection(list2)\n\n\ndef computeSteps(x, y, step, steps):\n curr = 0\n if (x, y) in steps:\n curr = steps.get((x, y))\n steps[x, y] = step + curr\n\n\ndef buildPoints(wire, steps):\n points = []\n x, y = 0, 0\n s = 0\n for p in wire:\n direction = p[0]\n step = int(p[1:])\n if direction == 'D':\n for i in range(0, step):\n y -= 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n elif direction == 'U':\n for i in range(0, step):\n y += 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n elif direction == 'L':\n for i in range(0, step):\n x -= 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n elif direction == 'R':\n for i in range(0, step):\n x += 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n return points\n\n\nwith open(filepath) as fp:\n steps = {}\n port = 0, 0\n wire1 = fp.readline().strip().split(',')\n wire2 = fp.readline().strip().split(',')\n point1 = buildPoints(wire1, steps)\n point2 = buildPoints(wire2, steps)\n commonPoints = intersection(point1, point2)\n min = sys.maxsize\n for k in commonPoints:\n val = steps.get(k)\n if val < min:\n min = val\n print(min)\n", "step-3": "<mask token>\nfilepath = 'input.txt'\n\n\ndef intersection(list1, list2):\n return set(list1).intersection(list2)\n\n\ndef computeSteps(x, y, step, steps):\n curr = 0\n if (x, y) in steps:\n curr = steps.get((x, y))\n steps[x, y] = step + curr\n\n\ndef buildPoints(wire, steps):\n points = []\n x, y = 0, 0\n s = 0\n for p in wire:\n direction = p[0]\n step = int(p[1:])\n if direction == 'D':\n for i in range(0, step):\n y -= 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n elif direction == 'U':\n for i in range(0, step):\n y += 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n elif direction == 'L':\n for i in range(0, step):\n x -= 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n elif direction == 'R':\n for i in range(0, step):\n x += 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n return points\n\n\nwith open(filepath) as fp:\n steps = {}\n port = 0, 0\n wire1 = fp.readline().strip().split(',')\n wire2 = fp.readline().strip().split(',')\n point1 = buildPoints(wire1, steps)\n point2 = buildPoints(wire2, steps)\n commonPoints = intersection(point1, point2)\n min = sys.maxsize\n for k in commonPoints:\n val = steps.get(k)\n if val < min:\n min = val\n print(min)\n", "step-4": "import sys\nfilepath = 'input.txt'\n\n\ndef intersection(list1, list2):\n return set(list1).intersection(list2)\n\n\ndef computeSteps(x, y, step, steps):\n curr = 0\n if (x, y) in steps:\n curr = steps.get((x, y))\n steps[x, y] = step + curr\n\n\ndef buildPoints(wire, steps):\n points = []\n x, y = 0, 0\n s = 0\n for p in wire:\n direction = p[0]\n step = int(p[1:])\n if direction == 'D':\n for i in range(0, step):\n y -= 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n elif direction == 'U':\n for i in range(0, step):\n y += 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n elif direction == 'L':\n for i in range(0, step):\n x -= 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n elif direction == 'R':\n for i in range(0, step):\n x += 1\n points.append((x, y))\n s += 1\n computeSteps(x, y, s, steps)\n return points\n\n\nwith open(filepath) as fp:\n steps = {}\n port = 0, 0\n wire1 = fp.readline().strip().split(',')\n wire2 = fp.readline().strip().split(',')\n point1 = buildPoints(wire1, steps)\n point2 = buildPoints(wire2, steps)\n commonPoints = intersection(point1, point2)\n min = sys.maxsize\n for k in commonPoints:\n val = steps.get(k)\n if val < min:\n min = val\n print(min)\n", "step-5": "import sys\r\nfilepath = 'input.txt' \r\n\r\ndef intersection(list1, list2): \r\n return set(list1).intersection(list2) \r\n\r\ndef computeSteps(x, y, step, steps):\r\n # build dictionary with steps for each point\r\n curr = 0\r\n if (x,y) in steps:\r\n curr = steps.get((x,y)) \r\n steps[(x,y)] = step + curr\r\n\r\n \r\ndef buildPoints(wire, steps):\r\n points = []\r\n x, y = 0, 0\r\n s = 0\r\n for p in wire:\r\n direction = p[0]\r\n step = int(p[1:])\r\n if direction == 'D':\r\n for i in range(0, step):\r\n y -= 1\r\n points.append((x,y)) \r\n s += 1 \r\n computeSteps(x, y, s, steps) \r\n elif direction == 'U':\r\n for i in range(0, step):\r\n y += 1\r\n points.append((x,y)) \r\n s += 1 \r\n computeSteps(x, y, s, steps) \r\n elif direction == 'L':\r\n for i in range(0, step):\r\n x -= 1\r\n points.append((x,y))\r\n s += 1 \r\n computeSteps(x, y, s, steps) \r\n elif direction == 'R':\r\n for i in range(0, step):\r\n x += 1\r\n points.append((x,y))\r\n s += 1 \r\n computeSteps(x, y, s, steps) \r\n \r\n #end for\r\n return points\r\n\r\nwith open(filepath) as fp: \t \r\n steps = {} \r\n port = (0,0)\r\n wire1 = fp.readline().strip().split(',')\r\n wire2 = fp.readline().strip().split(',')\r\n point1 = buildPoints(wire1, steps)\r\n point2 = buildPoints(wire2, steps)\r\n \r\n commonPoints = intersection(point1, point2)\r\n\r\n min = sys.maxsize\r\n for k in commonPoints:\r\n val = steps.get(k)\r\n if val < min:\r\n min = val\r\n \r\n print(min)\r\n \r\n", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
<|reserved_special_token_0|> def plot_loss(history): plt.plot(history.history['loss'], label='loss') plt.plot(history.history['val_loss'], label='val_loss') plt.ylim([0, 10]) plt.xlabel('Epoch') plt.ylabel('Error') plt.legend() plt.grid(True) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def plot_loss(history): plt.plot(history.history['loss'], label='loss') plt.plot(history.history['val_loss'], label='val_loss') plt.ylim([0, 10]) plt.xlabel('Epoch') plt.ylabel('Error') plt.legend() plt.grid(True) <|reserved_special_token_0|> with open( 'C:\\Users\\owenb\\Desktop\\experiment results\\agent3_data\\actions.csv', newline='') as csvfile: reader = csv.reader(csvfile, dialect='excel') for x in reader: outputs.append(x) with open( 'C:\\Users\\owenb\\Desktop\\experiment results\\agent3_data\\messages_3_2.csv' , newline='') as csvfile: reader = csv.reader(csvfile, dialect='excel') for x in reader: inputs.append(x) <|reserved_special_token_0|> del dataset[8500:] <|reserved_special_token_0|> for x in range(len(train_features)): train_features[x] = np.array(np.expand_dims([float(y) for y in train_features[x]], axis=0)) train_labels[x] = np.array(np.expand_dims([float(y) for y in train_labels[x]], axis=0)) <|reserved_special_token_0|> for x in range(len(test_features)): test_features[x] = np.array(np.expand_dims([float(y) for y in test_features[x]], axis=0)) test_labels[x] = np.array(np.expand_dims([float(y) for y in test_labels [x]], axis=0)) <|reserved_special_token_0|> normalizer.adapt(train_features) <|reserved_special_token_0|> linear_model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.001), loss='mean_absolute_error') <|reserved_special_token_0|> plot_loss(history) <|reserved_special_token_0|> print('agent 3-2 post train error=' + str(test_results)) linear_model.save('agent3-2.h5') <|reserved_special_token_1|> <|reserved_special_token_0|> def plot_loss(history): plt.plot(history.history['loss'], label='loss') plt.plot(history.history['val_loss'], label='val_loss') plt.ylim([0, 10]) plt.xlabel('Epoch') plt.ylabel('Error') plt.legend() plt.grid(True) outputs = [] inputs = [] with open( 'C:\\Users\\owenb\\Desktop\\experiment results\\agent3_data\\actions.csv', newline='') as csvfile: reader = csv.reader(csvfile, dialect='excel') for x in reader: outputs.append(x) with open( 'C:\\Users\\owenb\\Desktop\\experiment results\\agent3_data\\messages_3_2.csv' , newline='') as csvfile: reader = csv.reader(csvfile, dialect='excel') for x in reader: inputs.append(x) dataset = [[inputs[x], outputs[x]] for x in range(len(inputs))] del dataset[8500:] length = int(len(dataset) * 0.8) train_dataset = random.sample(dataset, length) test_dataset = [y for y in dataset if y not in train_dataset] train_features = [x[0] for x in train_dataset] train_labels = [x[1] for x in train_dataset] test_features = [x[0] for x in test_dataset] test_labels = [x[1] for x in test_dataset] for x in range(len(train_features)): train_features[x] = np.array(np.expand_dims([float(y) for y in train_features[x]], axis=0)) train_labels[x] = np.array(np.expand_dims([float(y) for y in train_labels[x]], axis=0)) train_features = np.array(train_features) train_labels = np.array(train_labels) for x in range(len(test_features)): test_features[x] = np.array(np.expand_dims([float(y) for y in test_features[x]], axis=0)) test_labels[x] = np.array(np.expand_dims([float(y) for y in test_labels [x]], axis=0)) test_features = np.array(test_features) test_labels = np.array(test_labels) normalizer = preprocessing.Normalization(input_shape=(1, 100)) normalizer.adapt(train_features) linear_model = tf.keras.Sequential([normalizer, tf.keras.layers.Dense(6)]) linear_model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.001), loss='mean_absolute_error') history = linear_model.fit(x=train_features, y=train_labels, epochs=100, verbose=0, validation_split=0.2) plot_loss(history) test_results = linear_model.evaluate(test_features, test_labels, verbose=1) print('agent 3-2 post train error=' + str(test_results)) linear_model.save('agent3-2.h5') <|reserved_special_token_1|> import tensorflow as tf import csv from tensorflow.keras import layers from tensorflow.keras.layers.experimental import preprocessing import pandas as pd import numpy as np import random import matplotlib.pyplot as plt import math def plot_loss(history): plt.plot(history.history['loss'], label='loss') plt.plot(history.history['val_loss'], label='val_loss') plt.ylim([0, 10]) plt.xlabel('Epoch') plt.ylabel('Error') plt.legend() plt.grid(True) outputs = [] inputs = [] with open( 'C:\\Users\\owenb\\Desktop\\experiment results\\agent3_data\\actions.csv', newline='') as csvfile: reader = csv.reader(csvfile, dialect='excel') for x in reader: outputs.append(x) with open( 'C:\\Users\\owenb\\Desktop\\experiment results\\agent3_data\\messages_3_2.csv' , newline='') as csvfile: reader = csv.reader(csvfile, dialect='excel') for x in reader: inputs.append(x) dataset = [[inputs[x], outputs[x]] for x in range(len(inputs))] del dataset[8500:] length = int(len(dataset) * 0.8) train_dataset = random.sample(dataset, length) test_dataset = [y for y in dataset if y not in train_dataset] train_features = [x[0] for x in train_dataset] train_labels = [x[1] for x in train_dataset] test_features = [x[0] for x in test_dataset] test_labels = [x[1] for x in test_dataset] for x in range(len(train_features)): train_features[x] = np.array(np.expand_dims([float(y) for y in train_features[x]], axis=0)) train_labels[x] = np.array(np.expand_dims([float(y) for y in train_labels[x]], axis=0)) train_features = np.array(train_features) train_labels = np.array(train_labels) for x in range(len(test_features)): test_features[x] = np.array(np.expand_dims([float(y) for y in test_features[x]], axis=0)) test_labels[x] = np.array(np.expand_dims([float(y) for y in test_labels [x]], axis=0)) test_features = np.array(test_features) test_labels = np.array(test_labels) normalizer = preprocessing.Normalization(input_shape=(1, 100)) normalizer.adapt(train_features) linear_model = tf.keras.Sequential([normalizer, tf.keras.layers.Dense(6)]) linear_model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.001), loss='mean_absolute_error') history = linear_model.fit(x=train_features, y=train_labels, epochs=100, verbose=0, validation_split=0.2) plot_loss(history) test_results = linear_model.evaluate(test_features, test_labels, verbose=1) print('agent 3-2 post train error=' + str(test_results)) linear_model.save('agent3-2.h5') <|reserved_special_token_1|> import tensorflow as tf import csv from tensorflow.keras import layers from tensorflow.keras.layers.experimental import preprocessing import pandas as pd import numpy as np import random import matplotlib.pyplot as plt import math def plot_loss(history): plt.plot(history.history['loss'], label='loss') plt.plot(history.history['val_loss'], label='val_loss') plt.ylim([0, 10]) plt.xlabel('Epoch') plt.ylabel('Error') plt.legend() plt.grid(True) #get data outputs=[] inputs=[] with open('C:\\Users\\owenb\\Desktop\\experiment results\\agent3_data\\actions.csv',newline='') as csvfile: reader=csv.reader(csvfile,dialect='excel') for x in reader: outputs.append(x) with open('C:\\Users\\owenb\\Desktop\\experiment results\\agent3_data\\messages_3_2.csv',newline='') as csvfile: reader=csv.reader(csvfile,dialect='excel') for x in reader: inputs.append(x) dataset=[[inputs[x],outputs[x]] for x in range(len(inputs))] del dataset[8500:] #process data length=int(len(dataset)*0.8) train_dataset=random.sample(dataset,length) test_dataset=[y for y in dataset if y not in train_dataset] train_features=[x[0] for x in train_dataset] train_labels=[x[1] for x in train_dataset] test_features=[x[0] for x in test_dataset] test_labels=[x[1] for x in test_dataset] for x in range(len(train_features)): train_features[x]=np.array(np.expand_dims([float(y) for y in train_features[x]], axis=0)) train_labels[x]=np.array(np.expand_dims([float(y) for y in train_labels[x]], axis=0)) train_features=np.array(train_features) train_labels=np.array(train_labels) for x in range(len(test_features)): test_features[x]=np.array(np.expand_dims([float(y) for y in test_features[x]], axis=0)) test_labels[x]=np.array(np.expand_dims([float(y) for y in test_labels[x]], axis=0)) test_features=np.array(test_features) test_labels=np.array(test_labels) #make model #message=tf.keras.Input(shape=(1,100)) #predictor_layer=tf.keras.layers.Dense(6,activation='relu',use_bias=True)(message) #linear_model=tf.keras.Model(inputs=message,outputs=predictor_layer) normalizer=preprocessing.Normalization(input_shape=(1, 100)) normalizer.adapt(train_features) linear_model=tf.keras.Sequential([normalizer,tf.keras.layers.Dense(6)]) linear_model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.001),loss='mean_absolute_error') #train model history = linear_model.fit(x=train_features, y=train_labels, epochs=100,verbose=0,validation_split = 0.2) plot_loss(history) #test model test_results = linear_model.evaluate(test_features, test_labels, verbose=1) print("agent 3-2 post train error="+str(test_results)) linear_model.save('agent3-2.h5')
flexible
{ "blob_id": "196147d7b2b0cf7176b5baa50d7e7618f88df493", "index": 7911, "step-1": "<mask token>\n\n\ndef plot_loss(history):\n plt.plot(history.history['loss'], label='loss')\n plt.plot(history.history['val_loss'], label='val_loss')\n plt.ylim([0, 10])\n plt.xlabel('Epoch')\n plt.ylabel('Error')\n plt.legend()\n plt.grid(True)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef plot_loss(history):\n plt.plot(history.history['loss'], label='loss')\n plt.plot(history.history['val_loss'], label='val_loss')\n plt.ylim([0, 10])\n plt.xlabel('Epoch')\n plt.ylabel('Error')\n plt.legend()\n plt.grid(True)\n\n\n<mask token>\nwith open(\n 'C:\\\\Users\\\\owenb\\\\Desktop\\\\experiment results\\\\agent3_data\\\\actions.csv',\n newline='') as csvfile:\n reader = csv.reader(csvfile, dialect='excel')\n for x in reader:\n outputs.append(x)\nwith open(\n 'C:\\\\Users\\\\owenb\\\\Desktop\\\\experiment results\\\\agent3_data\\\\messages_3_2.csv'\n , newline='') as csvfile:\n reader = csv.reader(csvfile, dialect='excel')\n for x in reader:\n inputs.append(x)\n<mask token>\ndel dataset[8500:]\n<mask token>\nfor x in range(len(train_features)):\n train_features[x] = np.array(np.expand_dims([float(y) for y in\n train_features[x]], axis=0))\n train_labels[x] = np.array(np.expand_dims([float(y) for y in\n train_labels[x]], axis=0))\n<mask token>\nfor x in range(len(test_features)):\n test_features[x] = np.array(np.expand_dims([float(y) for y in\n test_features[x]], axis=0))\n test_labels[x] = np.array(np.expand_dims([float(y) for y in test_labels\n [x]], axis=0))\n<mask token>\nnormalizer.adapt(train_features)\n<mask token>\nlinear_model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.001),\n loss='mean_absolute_error')\n<mask token>\nplot_loss(history)\n<mask token>\nprint('agent 3-2 post train error=' + str(test_results))\nlinear_model.save('agent3-2.h5')\n", "step-3": "<mask token>\n\n\ndef plot_loss(history):\n plt.plot(history.history['loss'], label='loss')\n plt.plot(history.history['val_loss'], label='val_loss')\n plt.ylim([0, 10])\n plt.xlabel('Epoch')\n plt.ylabel('Error')\n plt.legend()\n plt.grid(True)\n\n\noutputs = []\ninputs = []\nwith open(\n 'C:\\\\Users\\\\owenb\\\\Desktop\\\\experiment results\\\\agent3_data\\\\actions.csv',\n newline='') as csvfile:\n reader = csv.reader(csvfile, dialect='excel')\n for x in reader:\n outputs.append(x)\nwith open(\n 'C:\\\\Users\\\\owenb\\\\Desktop\\\\experiment results\\\\agent3_data\\\\messages_3_2.csv'\n , newline='') as csvfile:\n reader = csv.reader(csvfile, dialect='excel')\n for x in reader:\n inputs.append(x)\ndataset = [[inputs[x], outputs[x]] for x in range(len(inputs))]\ndel dataset[8500:]\nlength = int(len(dataset) * 0.8)\ntrain_dataset = random.sample(dataset, length)\ntest_dataset = [y for y in dataset if y not in train_dataset]\ntrain_features = [x[0] for x in train_dataset]\ntrain_labels = [x[1] for x in train_dataset]\ntest_features = [x[0] for x in test_dataset]\ntest_labels = [x[1] for x in test_dataset]\nfor x in range(len(train_features)):\n train_features[x] = np.array(np.expand_dims([float(y) for y in\n train_features[x]], axis=0))\n train_labels[x] = np.array(np.expand_dims([float(y) for y in\n train_labels[x]], axis=0))\ntrain_features = np.array(train_features)\ntrain_labels = np.array(train_labels)\nfor x in range(len(test_features)):\n test_features[x] = np.array(np.expand_dims([float(y) for y in\n test_features[x]], axis=0))\n test_labels[x] = np.array(np.expand_dims([float(y) for y in test_labels\n [x]], axis=0))\ntest_features = np.array(test_features)\ntest_labels = np.array(test_labels)\nnormalizer = preprocessing.Normalization(input_shape=(1, 100))\nnormalizer.adapt(train_features)\nlinear_model = tf.keras.Sequential([normalizer, tf.keras.layers.Dense(6)])\nlinear_model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.001),\n loss='mean_absolute_error')\nhistory = linear_model.fit(x=train_features, y=train_labels, epochs=100,\n verbose=0, validation_split=0.2)\nplot_loss(history)\ntest_results = linear_model.evaluate(test_features, test_labels, verbose=1)\nprint('agent 3-2 post train error=' + str(test_results))\nlinear_model.save('agent3-2.h5')\n", "step-4": "import tensorflow as tf\nimport csv\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers.experimental import preprocessing\nimport pandas as pd\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport math\n\n\ndef plot_loss(history):\n plt.plot(history.history['loss'], label='loss')\n plt.plot(history.history['val_loss'], label='val_loss')\n plt.ylim([0, 10])\n plt.xlabel('Epoch')\n plt.ylabel('Error')\n plt.legend()\n plt.grid(True)\n\n\noutputs = []\ninputs = []\nwith open(\n 'C:\\\\Users\\\\owenb\\\\Desktop\\\\experiment results\\\\agent3_data\\\\actions.csv',\n newline='') as csvfile:\n reader = csv.reader(csvfile, dialect='excel')\n for x in reader:\n outputs.append(x)\nwith open(\n 'C:\\\\Users\\\\owenb\\\\Desktop\\\\experiment results\\\\agent3_data\\\\messages_3_2.csv'\n , newline='') as csvfile:\n reader = csv.reader(csvfile, dialect='excel')\n for x in reader:\n inputs.append(x)\ndataset = [[inputs[x], outputs[x]] for x in range(len(inputs))]\ndel dataset[8500:]\nlength = int(len(dataset) * 0.8)\ntrain_dataset = random.sample(dataset, length)\ntest_dataset = [y for y in dataset if y not in train_dataset]\ntrain_features = [x[0] for x in train_dataset]\ntrain_labels = [x[1] for x in train_dataset]\ntest_features = [x[0] for x in test_dataset]\ntest_labels = [x[1] for x in test_dataset]\nfor x in range(len(train_features)):\n train_features[x] = np.array(np.expand_dims([float(y) for y in\n train_features[x]], axis=0))\n train_labels[x] = np.array(np.expand_dims([float(y) for y in\n train_labels[x]], axis=0))\ntrain_features = np.array(train_features)\ntrain_labels = np.array(train_labels)\nfor x in range(len(test_features)):\n test_features[x] = np.array(np.expand_dims([float(y) for y in\n test_features[x]], axis=0))\n test_labels[x] = np.array(np.expand_dims([float(y) for y in test_labels\n [x]], axis=0))\ntest_features = np.array(test_features)\ntest_labels = np.array(test_labels)\nnormalizer = preprocessing.Normalization(input_shape=(1, 100))\nnormalizer.adapt(train_features)\nlinear_model = tf.keras.Sequential([normalizer, tf.keras.layers.Dense(6)])\nlinear_model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.001),\n loss='mean_absolute_error')\nhistory = linear_model.fit(x=train_features, y=train_labels, epochs=100,\n verbose=0, validation_split=0.2)\nplot_loss(history)\ntest_results = linear_model.evaluate(test_features, test_labels, verbose=1)\nprint('agent 3-2 post train error=' + str(test_results))\nlinear_model.save('agent3-2.h5')\n", "step-5": "import tensorflow as tf\nimport csv\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers.experimental import preprocessing\nimport pandas as pd\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport math\n\ndef plot_loss(history):\n plt.plot(history.history['loss'], label='loss')\n plt.plot(history.history['val_loss'], label='val_loss')\n plt.ylim([0, 10])\n plt.xlabel('Epoch')\n plt.ylabel('Error')\n plt.legend()\n plt.grid(True)\n\n#get data\n\noutputs=[]\ninputs=[]\n\nwith open('C:\\\\Users\\\\owenb\\\\Desktop\\\\experiment results\\\\agent3_data\\\\actions.csv',newline='') as csvfile:\n reader=csv.reader(csvfile,dialect='excel')\n for x in reader:\n outputs.append(x)\n\nwith open('C:\\\\Users\\\\owenb\\\\Desktop\\\\experiment results\\\\agent3_data\\\\messages_3_2.csv',newline='') as csvfile:\n reader=csv.reader(csvfile,dialect='excel')\n for x in reader:\n inputs.append(x)\n\ndataset=[[inputs[x],outputs[x]] for x in range(len(inputs))]\n\ndel dataset[8500:]\n\n#process data\n\nlength=int(len(dataset)*0.8)\ntrain_dataset=random.sample(dataset,length)\ntest_dataset=[y for y in dataset if y not in train_dataset]\n\ntrain_features=[x[0] for x in train_dataset]\ntrain_labels=[x[1] for x in train_dataset]\n\ntest_features=[x[0] for x in test_dataset]\ntest_labels=[x[1] for x in test_dataset]\n\nfor x in range(len(train_features)):\n train_features[x]=np.array(np.expand_dims([float(y) for y in train_features[x]], axis=0))\n train_labels[x]=np.array(np.expand_dims([float(y) for y in train_labels[x]], axis=0))\n\ntrain_features=np.array(train_features)\ntrain_labels=np.array(train_labels)\n\nfor x in range(len(test_features)):\n test_features[x]=np.array(np.expand_dims([float(y) for y in test_features[x]], axis=0))\n test_labels[x]=np.array(np.expand_dims([float(y) for y in test_labels[x]], axis=0))\n\ntest_features=np.array(test_features)\ntest_labels=np.array(test_labels)\n\n#make model\n\n#message=tf.keras.Input(shape=(1,100))\n#predictor_layer=tf.keras.layers.Dense(6,activation='relu',use_bias=True)(message)\n#linear_model=tf.keras.Model(inputs=message,outputs=predictor_layer)\n\nnormalizer=preprocessing.Normalization(input_shape=(1, 100))\nnormalizer.adapt(train_features)\nlinear_model=tf.keras.Sequential([normalizer,tf.keras.layers.Dense(6)])\n\nlinear_model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.001),loss='mean_absolute_error')\n\n#train model\n\nhistory = linear_model.fit(x=train_features, y=train_labels, epochs=100,verbose=0,validation_split = 0.2)\n\nplot_loss(history)\n\n#test model\n\ntest_results = linear_model.evaluate(test_features, test_labels, verbose=1)\n\n\nprint(\"agent 3-2 post train error=\"+str(test_results))\nlinear_model.save('agent3-2.h5')\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class MyLoop(dopehr_loopmodel): <|reserved_special_token_0|> def select_loop_atoms(self): return selection(self.residue_range('218:', '231:')) <|reserved_special_token_1|> <|reserved_special_token_0|> class MyLoop(dopehr_loopmodel): def select_atoms(self): return selection(self.residue_range('218:', '231:')) def select_loop_atoms(self): return selection(self.residue_range('218:', '231:')) <|reserved_special_token_1|> from modeller import * from modeller.automodel import * class MyLoop(dopehr_loopmodel): def select_atoms(self): return selection(self.residue_range('218:', '231:')) def select_loop_atoms(self): return selection(self.residue_range('218:', '231:')) <|reserved_special_token_1|> from modeller import * from modeller.automodel import * # This part was within the script loop_modelling_2 # Here is is in a separate file for loop_modelling_3 so the script can be run in parallel class MyLoop(dopehr_loopmodel): def select_atoms(self): # Here only the second loop atoms are allowed to move so we do not mess with the first loop we have previously refined return selection(self.residue_range('218:', '231:')) def select_loop_atoms(self): return selection(self.residue_range('218:', '231:'))
flexible
{ "blob_id": "d058c3df8513e07e4ff7035aa5c5885819e43687", "index": 7295, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass MyLoop(dopehr_loopmodel):\n <mask token>\n\n def select_loop_atoms(self):\n return selection(self.residue_range('218:', '231:'))\n", "step-3": "<mask token>\n\n\nclass MyLoop(dopehr_loopmodel):\n\n def select_atoms(self):\n return selection(self.residue_range('218:', '231:'))\n\n def select_loop_atoms(self):\n return selection(self.residue_range('218:', '231:'))\n", "step-4": "from modeller import *\nfrom modeller.automodel import *\n\n\nclass MyLoop(dopehr_loopmodel):\n\n def select_atoms(self):\n return selection(self.residue_range('218:', '231:'))\n\n def select_loop_atoms(self):\n return selection(self.residue_range('218:', '231:'))\n", "step-5": "from modeller import *\nfrom modeller.automodel import * \n\n# This part was within the script loop_modelling_2\n# Here is is in a separate file for loop_modelling_3 so the script can be run in parallel\n\nclass MyLoop(dopehr_loopmodel):\n def select_atoms(self):\n\t # Here only the second loop atoms are allowed to move so we do not mess with the first loop we have previously refined\n return selection(self.residue_range('218:', '231:'))\n def select_loop_atoms(self):\n return selection(self.residue_range('218:', '231:'))\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
from Config_paar import * from Envelopefkt import * from Kinematik import * def A_m_n(M,N,x_plus,p_el,p_pos,k_photon,k_laser): def f1(p): return -(m*a0)/(pk(p)) * g(phi,sigma,Envelope) *( pe(1,p) * cos(ksi) * cos(phi) + pe(2,p) * sin(ksi) * sin(phi) ) def f2(p): return -(m*a0)**2/(2.*pk(p))*g(phi,sigma,Envelope)**2*((cos(ksi)*cos(phi))**2+(sin(ksi)*sin(phi))**2) def f(p): return f1(p)+f2(p) def f1_SVEA(p): return -(m*a0)/(pk(p))*g(phi,sigma,Envelope)*(pe(1,p)*cos(ksi)*sin(phi)-pe(2,p)*sin(ksi)*cos(phi)) def f2_SVEA(p): return -(m*a0)**2/(4.*pk(p))*(Int_g_2(phi,sigma,Envelope)+g(phi,sigma,Envelope)**2*cos(phi)*sin(phi)*(cos(ksi)**2-sin(ksi)**2)) def f_SVEA(p): return f1_SVEA(p)+f2_SVEA(p) pk = lambda imp: (imp * k_laser) pe = lambda l,imp: (imp * eps_laser(l)) P_ = p_pos.minus() + p_el.minus() - k_photon.minus() s = P_/k_laser.minus() phi = w_laser * x_plus H_plus = s*phi - f_SVEA(p_el) + f_SVEA(-p_pos) if M == 0: A = -1./s * (f(-p_pos) - f(p_el)) * exp(1j * H_plus) else: A = g(phi,sigma,Envelope)**M *exp( 1j* ( H_plus + N*phi)) return A def A_m_n_nSVEA(M,N,x_plus,p_el,p_pos,k_photon,k_laser): def f1(p): if Envelope == 'cos^2': fakt_a = sigma/(sigma-pi) fakt_b = sigma/(sigma+pi) Int_sin = -0.25 *( fakt_a * cos( phi/fakt_a ) + fakt_b * cos( phi/fakt_b ) +2.*cos(phi) ) Int_cos = 0.25 *( fakt_a * sin( phi/fakt_a ) + fakt_b * sin( phi/fakt_b ) +2.*sin(phi) ) return -(m*a0)/(pk(p)) *( pe(1,p) * cos(ksi) * Int_cos + pe(2,p) * sin(ksi) * Int_sin ) elif Envelope == 'cos^4': fakt_a = lambda n: ( 1. + n*pi/sigma ) fakt_b = lambda n: ( -1. + n*pi/sigma ) Int_sin = 0.25 *( ( - cos( fakt_a(2.)*phi ) / fakt_a(2.) + cos( fakt_b(2.)*phi ) / fakt_b(2.) ) * 0.25 \ - cos( fakt_a(1.)*phi ) / fakt_a(1.) + cos( fakt_b(1.)*phi ) / fakt_b(1.) - 3./2. * cos(phi) ) Int_cos = 0.25 *( ( sin( fakt_a(2.)*phi ) / fakt_a(2.) + sin( fakt_b(2.)*phi ) / fakt_b(2.) ) * 0.25 \ + sin( fakt_a(1.)*phi ) / fakt_a(1.) + sin( fakt_b(1.)*phi ) / fakt_b(1.) - 3./2. * sin(phi) ) return -(m*a0)/(pk(p)) * ( pe(1,p) * cos(ksi) * Int_cos + pe(2,p) * sin(ksi) * Int_sin ) elif Envelope == 'cosh': raise IOError,'cosh noch nicht implementiert -> benutze SEVA' else: raise IOError,'Nicht analytisch loesbar -> benutze SEVA' def f2(p): if Envelope == 'cos^2': a = pi/sigma/2. F = lambda l,n: ( l + n*a ) Int_cos = 1./8. *( 1.5*phi + 0.75*sin(2.*phi) + sin(F(0,4.)*phi)/F(0,8.) + sin(F(0,2.)*phi)/a \ + sin(F(-2.,4.)*phi)/F(-2.,4.)/4. + sin(F(2.,4.)*phi)/F(2.,4.)/4. \ + sin(F(-2.,2.)*phi)/F(-2.,2.) + sin(F(2.,2.)*phi)/F(2.,2.) ) Int_sin = 1./8. *( 1.5*phi - 0.75*sin(2.*phi) + sin(F(0,4.)*phi)/F(0,8.) + sin(F(0,2.)*phi)/a \ - sin(F(-2.,4.)*phi)/F(-2.,4.)/4. - sin(F(2.,4.)*phi)/F(2.,4.)/4. \ - sin(F(-2.,2.)*phi)/F(-2.,2.) - sin(F(2.,2.)*phi)/F(2.,2.) ) return -( m*a0 )**2 / (2.*pk(p)) * ( cos(ksi)**2 * Int_cos + sin(ksi)**2 * Int_sin ) elif Envelope == 'cos^4': Faktor = lambda l,n: ( l + n*pi/sigma ) Int_sin = 1./64. *( (- sin( Faktor(-2.,4.)*phi ) / Faktor(-2.,4.) - sin( Faktor(2.,4.)*phi ) / Faktor(2.,4.) ) / 8. \ - sin( Faktor(-2.,3.)*phi ) / Faktor(-2.,3.) - sin( Faktor(2.,3.)*phi ) / Faktor(2.,3.) \ -( sin( Faktor(-2.,2.)*phi ) / Faktor(-2.,2.) + sin( Faktor(2.,2.)*phi ) / Faktor(2.,2.) ) * 3.5 \ -( sin( Faktor(-2.,1.)*phi ) / Faktor(-2.,1.) + sin( Faktor(2.,1.)*phi ) / Faktor(2.,1.) ) * 7. \ + sin( Faktor( 0.,4.)*phi ) / Faktor(0.,16.) + sin( Faktor(0.,3.)*phi ) / Faktor(0.,1.5) \ +( sin( Faktor( 0.,2.)*phi ) / Faktor(0.,2.) + sin( Faktor(0.,1.)*phi ) / Faktor(0.,0.5)) * 7. \ + 35./4. * phi - 35./8. * sin( 2*phi ) ) Int_cos = 1./64. *( ( sin( Faktor(-2.,4.)*phi ) / Faktor(-2.,4.) + sin( Faktor(2.,4.)*phi ) / Faktor(2.,4.) ) / 8. \ + sin( Faktor(-2.,3.)*phi ) / Faktor(-2.,3.) + sin( Faktor(2.,3.)*phi ) / Faktor(2.,3.) \ +( sin( Faktor(-2.,2.)*phi ) / Faktor(-2.,2.) + sin( Faktor(2.,2.)*phi ) / Faktor(2.,2.) ) * 3.5 \ +( sin( Faktor(-2.,1.)*phi ) / Faktor(-2.,1.) + sin( Faktor(2.,1.)*phi ) / Faktor(2.,1.) ) * 7. \ + sin( Faktor( 0.,4.)*phi ) / Faktor(0.,16.) + sin( Faktor(0.,3.)*phi ) / Faktor(0.,1.5) \ +( sin( Faktor( 0.,2.)*phi ) / Faktor(0.,2.) + sin( Faktor(0.,1.)*phi ) / Faktor(0.,0.5)) * 7. \ + 35./4. * phi - 35./8. * sin( 2*phi ) ) return -( m*a0 )**2 / (2.*pk(p)) * ( cos(ksi)**2 * Int_cos + sin(ksi)**2 * Int_sin ) elif Envelope == 'cosh': raise IOError,'cosh noch nicht implementiert -> benutze SEVA' else: raise IOError,'Nicht analytisch loesbar -> benutze SEVA' def f(p): return f1(p)+f2(p) pk = lambda imp: (imp * k_laser) pe = lambda l,imp: (imp * eps_laser(l)) P_ = p_pos.minus() + p_el.minus() - k_photon.minus() s = P_/k_laser.minus() phi = w_laser * x_plus H_plus = s*phi - f(p_el) + f(-p_pos) A = g(phi,sigma,Envelope)**M *exp( 1j* ( H_plus + N*phi)) return A def A_0_0 (A11,A1_1,A20,A22,A2_2): p_pos,p_el,k_laser,k_photon,q_pos,eps_m,eps_p = kinematik() pk = lambda p: (p * k_laser) d_p = lambda p: m*a0 / ( 4.* pk(p) ) P_ = p_pos.minus() + p_el.minus() - k_photon.minus() s = P_/k_laser.minus() Wert = 2./s * ( ( d_p(p_pos)*p_pos*eps_m - d_p(p_el)*p_el*eps_m ) * A11 \ + ( d_p(p_pos)*p_pos*eps_p - d_p(p_el)*p_el*eps_p ) * A1_1 \ - k_laser*k_photon*d_p(p_pos)*d_p(p_el) \ * ( 2.*A20 + (cos(ksi)**2 - sin(ksi)**2) * (A22 + A2_2) ) ) return Wert
normal
{ "blob_id": "ad170f67e5b9f54d950ead91dd60cd4f3b753eca", "index": 6660, "step-1": "from Config_paar import *\nfrom Envelopefkt import *\nfrom Kinematik import *\n\n\ndef A_m_n(M,N,x_plus,p_el,p_pos,k_photon,k_laser):\n\n def f1(p):\n return -(m*a0)/(pk(p)) * g(phi,sigma,Envelope) *( pe(1,p) * cos(ksi) * cos(phi) + pe(2,p) * sin(ksi) * sin(phi) )\n \n def f2(p):\n return -(m*a0)**2/(2.*pk(p))*g(phi,sigma,Envelope)**2*((cos(ksi)*cos(phi))**2+(sin(ksi)*sin(phi))**2) \n \n def f(p):\n return f1(p)+f2(p)\n \n def f1_SVEA(p):\n return -(m*a0)/(pk(p))*g(phi,sigma,Envelope)*(pe(1,p)*cos(ksi)*sin(phi)-pe(2,p)*sin(ksi)*cos(phi))\n\n def f2_SVEA(p):\n return -(m*a0)**2/(4.*pk(p))*(Int_g_2(phi,sigma,Envelope)+g(phi,sigma,Envelope)**2*cos(phi)*sin(phi)*(cos(ksi)**2-sin(ksi)**2))\n\n def f_SVEA(p):\n return f1_SVEA(p)+f2_SVEA(p)\n\n pk = lambda imp: (imp * k_laser)\n pe = lambda l,imp: (imp * eps_laser(l))\n \n P_ = p_pos.minus() + p_el.minus() - k_photon.minus() \n s = P_/k_laser.minus()\n\n phi = w_laser * x_plus\n \n H_plus = s*phi - f_SVEA(p_el) + f_SVEA(-p_pos)\n\n if M == 0: \n A = -1./s * (f(-p_pos) - f(p_el)) * exp(1j * H_plus)\n \n else:\n A = g(phi,sigma,Envelope)**M *exp( 1j* ( H_plus + N*phi))\n \n return A \n\n\ndef A_m_n_nSVEA(M,N,x_plus,p_el,p_pos,k_photon,k_laser):\n \n def f1(p):\n \n if Envelope == 'cos^2':\n \n fakt_a = sigma/(sigma-pi)\n fakt_b = sigma/(sigma+pi)\n \n Int_sin = -0.25 *( fakt_a * cos( phi/fakt_a ) + fakt_b * cos( phi/fakt_b ) +2.*cos(phi) )\n Int_cos = 0.25 *( fakt_a * sin( phi/fakt_a ) + fakt_b * sin( phi/fakt_b ) +2.*sin(phi) )\n \n return -(m*a0)/(pk(p)) *( pe(1,p) * cos(ksi) * Int_cos + pe(2,p) * sin(ksi) * Int_sin )\n \n \n elif Envelope == 'cos^4':\n \n fakt_a = lambda n: ( 1. + n*pi/sigma )\n fakt_b = lambda n: ( -1. + n*pi/sigma )\n \n Int_sin = 0.25 *( ( - cos( fakt_a(2.)*phi ) / fakt_a(2.) + cos( fakt_b(2.)*phi ) / fakt_b(2.) ) * 0.25 \\\n - cos( fakt_a(1.)*phi ) / fakt_a(1.) + cos( fakt_b(1.)*phi ) / fakt_b(1.) - 3./2. * cos(phi) )\n \n Int_cos = 0.25 *( ( sin( fakt_a(2.)*phi ) / fakt_a(2.) + sin( fakt_b(2.)*phi ) / fakt_b(2.) ) * 0.25 \\\n + sin( fakt_a(1.)*phi ) / fakt_a(1.) + sin( fakt_b(1.)*phi ) / fakt_b(1.) - 3./2. * sin(phi) )\n \n return -(m*a0)/(pk(p)) * ( pe(1,p) * cos(ksi) * Int_cos + pe(2,p) * sin(ksi) * Int_sin )\n \n \n elif Envelope == 'cosh':\n raise IOError,'cosh noch nicht implementiert -> benutze SEVA'\n \n else:\n raise IOError,'Nicht analytisch loesbar -> benutze SEVA'\n \n \n \n def f2(p):\n if Envelope == 'cos^2':\n \n a = pi/sigma/2.\n F = lambda l,n: ( l + n*a )\n \n \n Int_cos = 1./8. *( 1.5*phi + 0.75*sin(2.*phi) + sin(F(0,4.)*phi)/F(0,8.) + sin(F(0,2.)*phi)/a \\\n + sin(F(-2.,4.)*phi)/F(-2.,4.)/4. + sin(F(2.,4.)*phi)/F(2.,4.)/4. \\\n + sin(F(-2.,2.)*phi)/F(-2.,2.) + sin(F(2.,2.)*phi)/F(2.,2.) )\n \n Int_sin = 1./8. *( 1.5*phi - 0.75*sin(2.*phi) + sin(F(0,4.)*phi)/F(0,8.) + sin(F(0,2.)*phi)/a \\\n - sin(F(-2.,4.)*phi)/F(-2.,4.)/4. - sin(F(2.,4.)*phi)/F(2.,4.)/4. \\\n - sin(F(-2.,2.)*phi)/F(-2.,2.) - sin(F(2.,2.)*phi)/F(2.,2.) )\n \n return -( m*a0 )**2 / (2.*pk(p)) * ( cos(ksi)**2 * Int_cos + sin(ksi)**2 * Int_sin ) \n \n elif Envelope == 'cos^4':\n \n \n Faktor = lambda l,n: ( l + n*pi/sigma )\n \n Int_sin = 1./64. *( (- sin( Faktor(-2.,4.)*phi ) / Faktor(-2.,4.) - sin( Faktor(2.,4.)*phi ) / Faktor(2.,4.) ) / 8. \\\n - sin( Faktor(-2.,3.)*phi ) / Faktor(-2.,3.) - sin( Faktor(2.,3.)*phi ) / Faktor(2.,3.) \\\n -( sin( Faktor(-2.,2.)*phi ) / Faktor(-2.,2.) + sin( Faktor(2.,2.)*phi ) / Faktor(2.,2.) ) * 3.5 \\\n -( sin( Faktor(-2.,1.)*phi ) / Faktor(-2.,1.) + sin( Faktor(2.,1.)*phi ) / Faktor(2.,1.) ) * 7. \\\n + sin( Faktor( 0.,4.)*phi ) / Faktor(0.,16.) + sin( Faktor(0.,3.)*phi ) / Faktor(0.,1.5) \\\n +( sin( Faktor( 0.,2.)*phi ) / Faktor(0.,2.) + sin( Faktor(0.,1.)*phi ) / Faktor(0.,0.5)) * 7. \\\n + 35./4. * phi - 35./8. * sin( 2*phi ) ) \n \n Int_cos = 1./64. *( ( sin( Faktor(-2.,4.)*phi ) / Faktor(-2.,4.) + sin( Faktor(2.,4.)*phi ) / Faktor(2.,4.) ) / 8. \\\n + sin( Faktor(-2.,3.)*phi ) / Faktor(-2.,3.) + sin( Faktor(2.,3.)*phi ) / Faktor(2.,3.) \\\n +( sin( Faktor(-2.,2.)*phi ) / Faktor(-2.,2.) + sin( Faktor(2.,2.)*phi ) / Faktor(2.,2.) ) * 3.5 \\\n +( sin( Faktor(-2.,1.)*phi ) / Faktor(-2.,1.) + sin( Faktor(2.,1.)*phi ) / Faktor(2.,1.) ) * 7. \\\n + sin( Faktor( 0.,4.)*phi ) / Faktor(0.,16.) + sin( Faktor(0.,3.)*phi ) / Faktor(0.,1.5) \\\n +( sin( Faktor( 0.,2.)*phi ) / Faktor(0.,2.) + sin( Faktor(0.,1.)*phi ) / Faktor(0.,0.5)) * 7. \\\n + 35./4. * phi - 35./8. * sin( 2*phi ) )\n \n return -( m*a0 )**2 / (2.*pk(p)) * ( cos(ksi)**2 * Int_cos + sin(ksi)**2 * Int_sin ) \n \n \n elif Envelope == 'cosh':\n raise IOError,'cosh noch nicht implementiert -> benutze SEVA'\n \n else:\n raise IOError,'Nicht analytisch loesbar -> benutze SEVA'\n \n def f(p):\n return f1(p)+f2(p)\n \n\n pk = lambda imp: (imp * k_laser)\n pe = lambda l,imp: (imp * eps_laser(l))\n \n P_ = p_pos.minus() + p_el.minus() - k_photon.minus() \n s = P_/k_laser.minus()\n \n \n \n phi = w_laser * x_plus\n \n H_plus = s*phi - f(p_el) + f(-p_pos)\n\n A = g(phi,sigma,Envelope)**M *exp( 1j* ( H_plus + N*phi))\n \n return A \n \n \ndef A_0_0 (A11,A1_1,A20,A22,A2_2):\n \n\n \n p_pos,p_el,k_laser,k_photon,q_pos,eps_m,eps_p = kinematik()\n \n pk = lambda p: (p * k_laser)\n d_p = lambda p: m*a0 / ( 4.* pk(p) ) \n \n P_ = p_pos.minus() + p_el.minus() - k_photon.minus() \n s = P_/k_laser.minus()\n \n Wert = 2./s * ( ( d_p(p_pos)*p_pos*eps_m - d_p(p_el)*p_el*eps_m ) * A11 \\\n + ( d_p(p_pos)*p_pos*eps_p - d_p(p_el)*p_el*eps_p ) * A1_1 \\\n - k_laser*k_photon*d_p(p_pos)*d_p(p_el) \\\n * ( 2.*A20 + (cos(ksi)**2 - sin(ksi)**2) * (A22 + A2_2) ) )\n \n return Wert\n\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from django.core import management from django.conf import settings def backup_cron(): if settings.DBBACKUP_STORAGE is not '': management.call_command('dbbackup')
normal
{ "blob_id": "ae9f1c4f70801dace0455c051ba4d4bfb7f3fe67", "index": 4813, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef backup_cron():\n if settings.DBBACKUP_STORAGE is not '':\n management.call_command('dbbackup')\n", "step-3": "from django.core import management\nfrom django.conf import settings\n\n\ndef backup_cron():\n if settings.DBBACKUP_STORAGE is not '':\n management.call_command('dbbackup')\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import os import inspect import pytest from ._common import copy_default_profile_collection, patch_first_startup_file from bluesky_queueserver.manager.profile_tools import global_user_namespace, load_devices_from_happi from bluesky_queueserver.manager.profile_ops import load_profile_collection def create_local_imports_files(tmp_path): path_dir = os.path.join(tmp_path, "dir_local_imports") fln_func = os.path.join(path_dir, "file_func.py") fln_gen = os.path.join(path_dir, "file_gen.py") os.makedirs(path_dir, exist_ok=True) # Create file1 code1 = """ from bluesky_queueserver.manager.profile_tools import set_user_ns # Function that has the parameter 'ipython' @set_user_ns def f1(some_value, user_ns, ipython): user_ns["func_was_called"] = "func_was_called" return (some_value, user_ns["v_from_namespace"], bool(ipython)) # Function that has no parameter 'ipython' @set_user_ns def f1a(some_value, user_ns): user_ns["func_A_was_called"] = "func_was_called" return (some_value, user_ns["v_from_namespace"]) """ with open(fln_func, "w") as f: f.writelines(code1) # Create file2 code2 = """ from bluesky_queueserver.manager.profile_tools import set_user_ns # Function that has the parameter 'ipython' @set_user_ns def f2(some_value, user_ns, ipython): user_ns["gen_was_called"] = "gen_was_called" yield (some_value, user_ns["v_from_namespace"], bool(ipython)) # Function that has no parameter 'ipython' @set_user_ns def f2a(some_value, user_ns): user_ns["gen_A_was_called"] = "gen_was_called" yield (some_value, user_ns["v_from_namespace"]) @set_user_ns def f3(some_value, user_ns, ipython): user_ns["value_f3"] = some_value f3(91) """ with open(fln_gen, "w") as f: f.writelines(code2) patch_code = """ from dir_local_imports.file_func import f1, f1a from dir_local_imports.file_gen import f2, f2a from bluesky_queueserver.manager.profile_tools import set_user_ns @set_user_ns def f4(some_value, user_ns, ipython): user_ns["value_f4"] = some_value f4(90) """ def test_set_user_ns_1(tmp_path): """ Tests for ``set_user_ns`` decorator. The functionality of the decorator is fully tested (only without IPython): - using ``global_user_namespace`` to pass values in and out of the function defined in the imported module (emulation of ``get_ipython().user_ns``). - checking if the function is executed from IPython (only for the function defined in the imported module). """ pc_path = copy_default_profile_collection(tmp_path) create_local_imports_files(pc_path) patch_first_startup_file(pc_path, patch_code) nspace = load_profile_collection(pc_path) assert len(nspace) > 0, "Failed to load the profile collection" assert "f1" in nspace, "Test for local imports failed" assert "f2" in nspace, "Test for local imports failed" # Test if the decorator `set_user_ns` does not change function type assert inspect.isgeneratorfunction(nspace["f1"]) is False assert inspect.isgeneratorfunction(nspace["f2"]) is True # Check if the extra arguments are removed from the function signature def check_signature(func): params = inspect.signature(func).parameters assert "user_ns" not in params assert "ipython" not in params check_signature(nspace["f1"]) check_signature(nspace["f1a"]) check_signature(nspace["f2"]) check_signature(nspace["f2a"]) assert nspace["value_f3"] == 91 assert nspace["value_f4"] == 90 # Test function global_user_namespace.set_user_namespace(user_ns=nspace, use_ipython=False) global_user_namespace.user_ns["v_from_namespace"] = "value-sent-to-func" assert nspace["v_from_namespace"] == "value-sent-to-func" result_func = nspace["f1"](60) assert nspace["func_was_called"] == "func_was_called" assert result_func[0] == 60 assert result_func[1] == "value-sent-to-func" assert result_func[2] is False result_func = nspace["f1a"](65) assert nspace["func_A_was_called"] == "func_was_called" assert result_func[0] == 65 assert result_func[1] == "value-sent-to-func" # Test generator global_user_namespace.user_ns["v_from_namespace"] = "value-sent-to-gen" result_func = list(nspace["f2"](110))[0] assert nspace["gen_was_called"] == "gen_was_called" assert result_func[0] == 110 assert result_func[1] == "value-sent-to-gen" assert result_func[2] is False result_func = list(nspace["f2a"](115))[0] assert nspace["gen_A_was_called"] == "gen_was_called" assert result_func[0] == 115 assert result_func[1] == "value-sent-to-gen" def test_global_user_namespace(): """ Basic test for ``global_user_namespace``. """ ns = {"ab": 1, "cd": 2} global_user_namespace.set_user_namespace(user_ns=ns) assert global_user_namespace.user_ns == ns assert global_user_namespace.use_ipython is False global_user_namespace.set_user_namespace(user_ns={}, use_ipython=True) assert global_user_namespace.user_ns == {} assert global_user_namespace.use_ipython is True global_user_namespace.set_user_namespace(user_ns=ns, use_ipython=False) assert global_user_namespace.user_ns == ns assert global_user_namespace.use_ipython is False _happi_json_db_1 = """ { "det": { "_id": "det", "active": true, "args": [], "device_class": "ophyd.sim.DetWithCountTime", "documentation": null, "kwargs": { "name": "{{name}}" }, "name": "det", "type": "OphydItem" }, "motor": { "_id": "motor", "active": true, "args": [], "device_class": "ophyd.sim.SynAxisNoPosition", "documentation": null, "kwargs": { "name": "{{name}}" }, "name": "motor", "type": "OphydItem" }, "motor1": { "_id": "motor1", "active": true, "args": [], "device_class": "ophyd.sim.SynAxisNoHints", "documentation": null, "kwargs": { "name": "{{name}}" }, "name": "motor1", "type": "OphydItem" }, "tst_motor2": { "_id": "tst_motor2", "active": true, "args": [], "device_class": "ophyd.sim.SynAxisNoHints", "documentation": null, "kwargs": { "name": "{{name}}" }, "name": "tst_motor2", "type": "OphydItem" }, "motor3": { "_id": "motor3", "active": true, "args": [], "device_class": "ophyd.sim.SynAxis", "documentation": null, "kwargs": { "name": "{{name}}" }, "name": "motor3", "type": "OphydItem" }, "motor3_duplicate_error": { "_id": "motor3", "active": false, "args": [], "device_class": "ophyd.sim.SynAxis", "documentation": null, "kwargs": { "name": "{{name}}" }, "name": "motor3", "type": "OphydItem" } } """ def _configure_happi(tmp_path, monkeypatch, json_devices): path_json = os.path.join(tmp_path, "sim_devices.json") path_ini = os.path.join(tmp_path, "happi.ini") happi_ini_text = f"[DEFAULT]\nbackend=json\npath={path_json}" with open(path_ini, "w") as f: f.write(happi_ini_text) with open(path_json, "w") as f: f.write(json_devices) monkeypatch.setenv("HAPPI_CFG", path_ini) # fmt: off @pytest.mark.parametrize("device_names, loaded_names, kw_args, success, errmsg", [ ([], [], {}, True, ""), # No devices are loaded if the list of devices is empty (("det", "motor"), ("det", "motor"), {}, True, ""), (["det", "motor"], ("det", "motor"), {}, True, ""), ((("det", ""), ["motor", ""]), ("det", "motor"), {}, True, ""), (("det", ["motor", ""]), ("det", "motor"), {}, True, ""), (("det", ("motor", ""), ("tst_motor2", "motor2")), ("det", "motor", "motor2"), {}, True, ""), # This is not typical use case, but the same device may be loaded multiple times # with different names if needed. ((("motor1", "motor1_copy1"), ("motor1", "motor1_copy2")), ("motor1_copy1", "motor1_copy2"), {}, True, ""), # Incorrect type of the device list (10, ("det", "motor"), {}, False, "Parameter 'device_names' value must be a tuple or a list"), ("string", ("det", "motor"), {}, False, "Parameter 'device_names' value must be a tuple or a list"), # Incorrecty type or form of a device list element (("det", 10), ("det", "motor"), {}, False, "Parameter 'device_names': element .* must be str, tuple or list"), ((10, "motor"), ("det", "motor"), {}, False, "Parameter 'device_names': element .* must be str, tuple or list"), (("det", (10, "motor2")), ("det", "motor"), {}, False, "element .* is expected to be in the form"), (("det", ("tst_motor2", 10)), ("det", "motor"), {}, False, "element .* is expected to be in the form"), (("det", ("tst_motor2", "motor2", 10)), ("det", "motor"), {}, False, "element .* is expected to be in the form"), # No device found (("det", "motor10"), ("det", "motor10"), {}, False, "No devices with name"), # Multiple devices found (search for "motor3" yields multile devices, this is database issue) (("det", "motor3"), ("det", "motor3"), {}, False, "Multiple devices with name"), # Use additional search parameters. (Two entries for "motor3" differ in the value of `active` field. # A single entry for `det` has `active==True`.) (("det", "motor3"), ("det", "motor3"), {"active": True}, True, ""), (("det", "motor3"), ("det", "motor3"), {"active": False}, False, "No devices with name 'det' were found in Happi database."), (("motor3",), ("motor3",), {"active": False}, True, ""), # Verify that valid device names are accepted (("det", ["motor", "motor3_new"]), ("det", "motor3_new"), {}, True, ""), # Invalid new device name (("det", ["motor", "Motor"]), ("det", "motor"), {}, False, "may consist of lowercase letters, numbers"), (("det", ["motor", "moTor"]), ("det", "motor"), {}, False, "may consist of lowercase letters, numbers"), (("det", ["motor", "_motor"]), ("det", "motor"), {}, False, "may consist of lowercase letters, numbers"), (("det", ["motor", " motor"]), ("det", "motor"), {}, False, "may consist of lowercase letters, numbers"), (("det", ["motor", "motor "]), ("det", "motor"), {}, False, "may consist of lowercase letters, numbers"), (("det", ["motor", "motor new"]), ("det", "motor"), {}, False, "may consist of lowercase letters, numbers"), (("det", ["motor", "motor_$new"]), ("det", "motor"), {}, False, "may consist of lowercase letters, numbers"), (("det", ["motor", "2motor_$new"]), ("det", "motor"), {}, False, "may consist of lowercase letters, numbers"), ]) # fmt: on def test_load_devices_from_happi_1(tmp_path, monkeypatch, device_names, loaded_names, kw_args, success, errmsg): """ Tests for ``load_devices_from_happi``. """ _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1) # Load as a dictionary if success: ns = {} dlist = load_devices_from_happi(device_names, namespace=ns, **kw_args) assert len(ns) == len(loaded_names), str(ns) for d in loaded_names: assert d in ns assert set(dlist) == set(loaded_names) else: with pytest.raises(Exception, match=errmsg): ns = {} load_devices_from_happi(device_names, namespace=ns, **kw_args) # Load in local namespace def _test_loading(device_names, loaded_names): if success: load_devices_from_happi(device_names, namespace=locals(), **kw_args) for d in loaded_names: assert d in locals() else: with pytest.raises(Exception, match=errmsg): load_devices_from_happi(device_names, namespace=locals(), **kw_args) _test_loading(device_names=device_names, loaded_names=loaded_names) def test_load_devices_from_happi_2_fail(tmp_path, monkeypatch): """ Function ``load_devices_from_happi``: parameter ``namespace`` is required and must be of type ``dict``. """ _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1) # Missing 'namespace' parameter with pytest.raises(TypeError, match="missing 1 required keyword-only argument: 'namespace'"): load_devices_from_happi(["det", "motor"]) # Incorrect type of 'namespace' parameter with pytest.raises(TypeError, match="Parameter 'namespace' must be a dictionary"): load_devices_from_happi(["det", "motor"], namespace=[1, 2, 3])
normal
{ "blob_id": "ad1ec5dd8fae290ab6cb73b17c5522e062261359", "index": 6698, "step-1": "<mask token>\n\n\ndef create_local_imports_files(tmp_path):\n path_dir = os.path.join(tmp_path, 'dir_local_imports')\n fln_func = os.path.join(path_dir, 'file_func.py')\n fln_gen = os.path.join(path_dir, 'file_gen.py')\n os.makedirs(path_dir, exist_ok=True)\n code1 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f1(some_value, user_ns, ipython):\n user_ns[\"func_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f1a(some_value, user_ns):\n user_ns[\"func_A_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"])\n\n\"\"\"\n with open(fln_func, 'w') as f:\n f.writelines(code1)\n code2 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f2(some_value, user_ns, ipython):\n user_ns[\"gen_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f2a(some_value, user_ns):\n user_ns[\"gen_A_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"])\n\n@set_user_ns\ndef f3(some_value, user_ns, ipython):\n user_ns[\"value_f3\"] = some_value\n\nf3(91)\n\n\"\"\"\n with open(fln_gen, 'w') as f:\n f.writelines(code2)\n\n\n<mask token>\n\n\ndef test_set_user_ns_1(tmp_path):\n \"\"\"\n Tests for ``set_user_ns`` decorator. The functionality of the decorator\n is fully tested (only without IPython):\n - using ``global_user_namespace`` to pass values in and out of the function\n defined in the imported module (emulation of ``get_ipython().user_ns``).\n - checking if the function is executed from IPython (only for the function\n defined in the imported module).\n \"\"\"\n pc_path = copy_default_profile_collection(tmp_path)\n create_local_imports_files(pc_path)\n patch_first_startup_file(pc_path, patch_code)\n nspace = load_profile_collection(pc_path)\n assert len(nspace) > 0, 'Failed to load the profile collection'\n assert 'f1' in nspace, 'Test for local imports failed'\n assert 'f2' in nspace, 'Test for local imports failed'\n assert inspect.isgeneratorfunction(nspace['f1']) is False\n assert inspect.isgeneratorfunction(nspace['f2']) is True\n\n def check_signature(func):\n params = inspect.signature(func).parameters\n assert 'user_ns' not in params\n assert 'ipython' not in params\n check_signature(nspace['f1'])\n check_signature(nspace['f1a'])\n check_signature(nspace['f2'])\n check_signature(nspace['f2a'])\n assert nspace['value_f3'] == 91\n assert nspace['value_f4'] == 90\n global_user_namespace.set_user_namespace(user_ns=nspace, use_ipython=False)\n global_user_namespace.user_ns['v_from_namespace'] = 'value-sent-to-func'\n assert nspace['v_from_namespace'] == 'value-sent-to-func'\n result_func = nspace['f1'](60)\n assert nspace['func_was_called'] == 'func_was_called'\n assert result_func[0] == 60\n assert result_func[1] == 'value-sent-to-func'\n assert result_func[2] is False\n result_func = nspace['f1a'](65)\n assert nspace['func_A_was_called'] == 'func_was_called'\n assert result_func[0] == 65\n assert result_func[1] == 'value-sent-to-func'\n global_user_namespace.user_ns['v_from_namespace'] = 'value-sent-to-gen'\n result_func = list(nspace['f2'](110))[0]\n assert nspace['gen_was_called'] == 'gen_was_called'\n assert result_func[0] == 110\n assert result_func[1] == 'value-sent-to-gen'\n assert result_func[2] is False\n result_func = list(nspace['f2a'](115))[0]\n assert nspace['gen_A_was_called'] == 'gen_was_called'\n assert result_func[0] == 115\n assert result_func[1] == 'value-sent-to-gen'\n\n\ndef test_global_user_namespace():\n \"\"\"\n Basic test for ``global_user_namespace``.\n \"\"\"\n ns = {'ab': 1, 'cd': 2}\n global_user_namespace.set_user_namespace(user_ns=ns)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n global_user_namespace.set_user_namespace(user_ns={}, use_ipython=True)\n assert global_user_namespace.user_ns == {}\n assert global_user_namespace.use_ipython is True\n global_user_namespace.set_user_namespace(user_ns=ns, use_ipython=False)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n\n\n<mask token>\n\n\n@pytest.mark.parametrize('device_names, loaded_names, kw_args, success, errmsg'\n , [([], [], {}, True, ''), (('det', 'motor'), ('det', 'motor'), {}, \n True, ''), (['det', 'motor'], ('det', 'motor'), {}, True, ''), ((('det',\n ''), ['motor', '']), ('det', 'motor'), {}, True, ''), (('det', ['motor',\n '']), ('det', 'motor'), {}, True, ''), (('det', ('motor', ''), (\n 'tst_motor2', 'motor2')), ('det', 'motor', 'motor2'), {}, True, ''), ((\n ('motor1', 'motor1_copy1'), ('motor1', 'motor1_copy2')), (\n 'motor1_copy1', 'motor1_copy2'), {}, True, ''), (10, ('det', 'motor'),\n {}, False, \"Parameter 'device_names' value must be a tuple or a list\"),\n ('string', ('det', 'motor'), {}, False,\n \"Parameter 'device_names' value must be a tuple or a list\"), (('det', \n 10), ('det', 'motor'), {}, False,\n \"Parameter 'device_names': element .* must be str, tuple or list\"), ((\n 10, 'motor'), ('det', 'motor'), {}, False,\n \"Parameter 'device_names': element .* must be str, tuple or list\"), ((\n 'det', (10, 'motor2')), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', ('tst_motor2', 10\n )), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', ('tst_motor2',\n 'motor2', 10)), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', 'motor10'), (\n 'det', 'motor10'), {}, False, 'No devices with name'), (('det',\n 'motor3'), ('det', 'motor3'), {}, False, 'Multiple devices with name'),\n (('det', 'motor3'), ('det', 'motor3'), {'active': True}, True, ''), ((\n 'det', 'motor3'), ('det', 'motor3'), {'active': False}, False,\n \"No devices with name 'det' were found in Happi database.\"), (('motor3'\n ,), ('motor3',), {'active': False}, True, ''), (('det', ['motor',\n 'motor3_new']), ('det', 'motor3_new'), {}, True, ''), (('det', ['motor',\n 'Motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'moTor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n '_motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n ' motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor ']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor_$new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n '2motor_$new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers')])\ndef test_load_devices_from_happi_1(tmp_path, monkeypatch, device_names,\n loaded_names, kw_args, success, errmsg):\n \"\"\"\n Tests for ``load_devices_from_happi``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n if success:\n ns = {}\n dlist = load_devices_from_happi(device_names, namespace=ns, **kw_args)\n assert len(ns) == len(loaded_names), str(ns)\n for d in loaded_names:\n assert d in ns\n assert set(dlist) == set(loaded_names)\n else:\n with pytest.raises(Exception, match=errmsg):\n ns = {}\n load_devices_from_happi(device_names, namespace=ns, **kw_args)\n\n def _test_loading(device_names, loaded_names):\n if success:\n load_devices_from_happi(device_names, namespace=locals(), **kw_args\n )\n for d in loaded_names:\n assert d in locals()\n else:\n with pytest.raises(Exception, match=errmsg):\n load_devices_from_happi(device_names, namespace=locals(),\n **kw_args)\n _test_loading(device_names=device_names, loaded_names=loaded_names)\n\n\ndef test_load_devices_from_happi_2_fail(tmp_path, monkeypatch):\n \"\"\"\n Function ``load_devices_from_happi``: parameter ``namespace`` is required and must be of type ``dict``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n with pytest.raises(TypeError, match=\n \"missing 1 required keyword-only argument: 'namespace'\"):\n load_devices_from_happi(['det', 'motor'])\n with pytest.raises(TypeError, match=\n \"Parameter 'namespace' must be a dictionary\"):\n load_devices_from_happi(['det', 'motor'], namespace=[1, 2, 3])\n", "step-2": "<mask token>\n\n\ndef create_local_imports_files(tmp_path):\n path_dir = os.path.join(tmp_path, 'dir_local_imports')\n fln_func = os.path.join(path_dir, 'file_func.py')\n fln_gen = os.path.join(path_dir, 'file_gen.py')\n os.makedirs(path_dir, exist_ok=True)\n code1 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f1(some_value, user_ns, ipython):\n user_ns[\"func_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f1a(some_value, user_ns):\n user_ns[\"func_A_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"])\n\n\"\"\"\n with open(fln_func, 'w') as f:\n f.writelines(code1)\n code2 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f2(some_value, user_ns, ipython):\n user_ns[\"gen_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f2a(some_value, user_ns):\n user_ns[\"gen_A_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"])\n\n@set_user_ns\ndef f3(some_value, user_ns, ipython):\n user_ns[\"value_f3\"] = some_value\n\nf3(91)\n\n\"\"\"\n with open(fln_gen, 'w') as f:\n f.writelines(code2)\n\n\n<mask token>\n\n\ndef test_set_user_ns_1(tmp_path):\n \"\"\"\n Tests for ``set_user_ns`` decorator. The functionality of the decorator\n is fully tested (only without IPython):\n - using ``global_user_namespace`` to pass values in and out of the function\n defined in the imported module (emulation of ``get_ipython().user_ns``).\n - checking if the function is executed from IPython (only for the function\n defined in the imported module).\n \"\"\"\n pc_path = copy_default_profile_collection(tmp_path)\n create_local_imports_files(pc_path)\n patch_first_startup_file(pc_path, patch_code)\n nspace = load_profile_collection(pc_path)\n assert len(nspace) > 0, 'Failed to load the profile collection'\n assert 'f1' in nspace, 'Test for local imports failed'\n assert 'f2' in nspace, 'Test for local imports failed'\n assert inspect.isgeneratorfunction(nspace['f1']) is False\n assert inspect.isgeneratorfunction(nspace['f2']) is True\n\n def check_signature(func):\n params = inspect.signature(func).parameters\n assert 'user_ns' not in params\n assert 'ipython' not in params\n check_signature(nspace['f1'])\n check_signature(nspace['f1a'])\n check_signature(nspace['f2'])\n check_signature(nspace['f2a'])\n assert nspace['value_f3'] == 91\n assert nspace['value_f4'] == 90\n global_user_namespace.set_user_namespace(user_ns=nspace, use_ipython=False)\n global_user_namespace.user_ns['v_from_namespace'] = 'value-sent-to-func'\n assert nspace['v_from_namespace'] == 'value-sent-to-func'\n result_func = nspace['f1'](60)\n assert nspace['func_was_called'] == 'func_was_called'\n assert result_func[0] == 60\n assert result_func[1] == 'value-sent-to-func'\n assert result_func[2] is False\n result_func = nspace['f1a'](65)\n assert nspace['func_A_was_called'] == 'func_was_called'\n assert result_func[0] == 65\n assert result_func[1] == 'value-sent-to-func'\n global_user_namespace.user_ns['v_from_namespace'] = 'value-sent-to-gen'\n result_func = list(nspace['f2'](110))[0]\n assert nspace['gen_was_called'] == 'gen_was_called'\n assert result_func[0] == 110\n assert result_func[1] == 'value-sent-to-gen'\n assert result_func[2] is False\n result_func = list(nspace['f2a'](115))[0]\n assert nspace['gen_A_was_called'] == 'gen_was_called'\n assert result_func[0] == 115\n assert result_func[1] == 'value-sent-to-gen'\n\n\ndef test_global_user_namespace():\n \"\"\"\n Basic test for ``global_user_namespace``.\n \"\"\"\n ns = {'ab': 1, 'cd': 2}\n global_user_namespace.set_user_namespace(user_ns=ns)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n global_user_namespace.set_user_namespace(user_ns={}, use_ipython=True)\n assert global_user_namespace.user_ns == {}\n assert global_user_namespace.use_ipython is True\n global_user_namespace.set_user_namespace(user_ns=ns, use_ipython=False)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n\n\n<mask token>\n\n\ndef _configure_happi(tmp_path, monkeypatch, json_devices):\n path_json = os.path.join(tmp_path, 'sim_devices.json')\n path_ini = os.path.join(tmp_path, 'happi.ini')\n happi_ini_text = f'[DEFAULT]\\nbackend=json\\npath={path_json}'\n with open(path_ini, 'w') as f:\n f.write(happi_ini_text)\n with open(path_json, 'w') as f:\n f.write(json_devices)\n monkeypatch.setenv('HAPPI_CFG', path_ini)\n\n\n@pytest.mark.parametrize('device_names, loaded_names, kw_args, success, errmsg'\n , [([], [], {}, True, ''), (('det', 'motor'), ('det', 'motor'), {}, \n True, ''), (['det', 'motor'], ('det', 'motor'), {}, True, ''), ((('det',\n ''), ['motor', '']), ('det', 'motor'), {}, True, ''), (('det', ['motor',\n '']), ('det', 'motor'), {}, True, ''), (('det', ('motor', ''), (\n 'tst_motor2', 'motor2')), ('det', 'motor', 'motor2'), {}, True, ''), ((\n ('motor1', 'motor1_copy1'), ('motor1', 'motor1_copy2')), (\n 'motor1_copy1', 'motor1_copy2'), {}, True, ''), (10, ('det', 'motor'),\n {}, False, \"Parameter 'device_names' value must be a tuple or a list\"),\n ('string', ('det', 'motor'), {}, False,\n \"Parameter 'device_names' value must be a tuple or a list\"), (('det', \n 10), ('det', 'motor'), {}, False,\n \"Parameter 'device_names': element .* must be str, tuple or list\"), ((\n 10, 'motor'), ('det', 'motor'), {}, False,\n \"Parameter 'device_names': element .* must be str, tuple or list\"), ((\n 'det', (10, 'motor2')), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', ('tst_motor2', 10\n )), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', ('tst_motor2',\n 'motor2', 10)), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', 'motor10'), (\n 'det', 'motor10'), {}, False, 'No devices with name'), (('det',\n 'motor3'), ('det', 'motor3'), {}, False, 'Multiple devices with name'),\n (('det', 'motor3'), ('det', 'motor3'), {'active': True}, True, ''), ((\n 'det', 'motor3'), ('det', 'motor3'), {'active': False}, False,\n \"No devices with name 'det' were found in Happi database.\"), (('motor3'\n ,), ('motor3',), {'active': False}, True, ''), (('det', ['motor',\n 'motor3_new']), ('det', 'motor3_new'), {}, True, ''), (('det', ['motor',\n 'Motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'moTor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n '_motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n ' motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor ']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor_$new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n '2motor_$new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers')])\ndef test_load_devices_from_happi_1(tmp_path, monkeypatch, device_names,\n loaded_names, kw_args, success, errmsg):\n \"\"\"\n Tests for ``load_devices_from_happi``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n if success:\n ns = {}\n dlist = load_devices_from_happi(device_names, namespace=ns, **kw_args)\n assert len(ns) == len(loaded_names), str(ns)\n for d in loaded_names:\n assert d in ns\n assert set(dlist) == set(loaded_names)\n else:\n with pytest.raises(Exception, match=errmsg):\n ns = {}\n load_devices_from_happi(device_names, namespace=ns, **kw_args)\n\n def _test_loading(device_names, loaded_names):\n if success:\n load_devices_from_happi(device_names, namespace=locals(), **kw_args\n )\n for d in loaded_names:\n assert d in locals()\n else:\n with pytest.raises(Exception, match=errmsg):\n load_devices_from_happi(device_names, namespace=locals(),\n **kw_args)\n _test_loading(device_names=device_names, loaded_names=loaded_names)\n\n\ndef test_load_devices_from_happi_2_fail(tmp_path, monkeypatch):\n \"\"\"\n Function ``load_devices_from_happi``: parameter ``namespace`` is required and must be of type ``dict``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n with pytest.raises(TypeError, match=\n \"missing 1 required keyword-only argument: 'namespace'\"):\n load_devices_from_happi(['det', 'motor'])\n with pytest.raises(TypeError, match=\n \"Parameter 'namespace' must be a dictionary\"):\n load_devices_from_happi(['det', 'motor'], namespace=[1, 2, 3])\n", "step-3": "<mask token>\n\n\ndef create_local_imports_files(tmp_path):\n path_dir = os.path.join(tmp_path, 'dir_local_imports')\n fln_func = os.path.join(path_dir, 'file_func.py')\n fln_gen = os.path.join(path_dir, 'file_gen.py')\n os.makedirs(path_dir, exist_ok=True)\n code1 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f1(some_value, user_ns, ipython):\n user_ns[\"func_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f1a(some_value, user_ns):\n user_ns[\"func_A_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"])\n\n\"\"\"\n with open(fln_func, 'w') as f:\n f.writelines(code1)\n code2 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f2(some_value, user_ns, ipython):\n user_ns[\"gen_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f2a(some_value, user_ns):\n user_ns[\"gen_A_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"])\n\n@set_user_ns\ndef f3(some_value, user_ns, ipython):\n user_ns[\"value_f3\"] = some_value\n\nf3(91)\n\n\"\"\"\n with open(fln_gen, 'w') as f:\n f.writelines(code2)\n\n\npatch_code = \"\"\"\nfrom dir_local_imports.file_func import f1, f1a\nfrom dir_local_imports.file_gen import f2, f2a\n\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n@set_user_ns\ndef f4(some_value, user_ns, ipython):\n user_ns[\"value_f4\"] = some_value\n\nf4(90)\n\n\"\"\"\n\n\ndef test_set_user_ns_1(tmp_path):\n \"\"\"\n Tests for ``set_user_ns`` decorator. The functionality of the decorator\n is fully tested (only without IPython):\n - using ``global_user_namespace`` to pass values in and out of the function\n defined in the imported module (emulation of ``get_ipython().user_ns``).\n - checking if the function is executed from IPython (only for the function\n defined in the imported module).\n \"\"\"\n pc_path = copy_default_profile_collection(tmp_path)\n create_local_imports_files(pc_path)\n patch_first_startup_file(pc_path, patch_code)\n nspace = load_profile_collection(pc_path)\n assert len(nspace) > 0, 'Failed to load the profile collection'\n assert 'f1' in nspace, 'Test for local imports failed'\n assert 'f2' in nspace, 'Test for local imports failed'\n assert inspect.isgeneratorfunction(nspace['f1']) is False\n assert inspect.isgeneratorfunction(nspace['f2']) is True\n\n def check_signature(func):\n params = inspect.signature(func).parameters\n assert 'user_ns' not in params\n assert 'ipython' not in params\n check_signature(nspace['f1'])\n check_signature(nspace['f1a'])\n check_signature(nspace['f2'])\n check_signature(nspace['f2a'])\n assert nspace['value_f3'] == 91\n assert nspace['value_f4'] == 90\n global_user_namespace.set_user_namespace(user_ns=nspace, use_ipython=False)\n global_user_namespace.user_ns['v_from_namespace'] = 'value-sent-to-func'\n assert nspace['v_from_namespace'] == 'value-sent-to-func'\n result_func = nspace['f1'](60)\n assert nspace['func_was_called'] == 'func_was_called'\n assert result_func[0] == 60\n assert result_func[1] == 'value-sent-to-func'\n assert result_func[2] is False\n result_func = nspace['f1a'](65)\n assert nspace['func_A_was_called'] == 'func_was_called'\n assert result_func[0] == 65\n assert result_func[1] == 'value-sent-to-func'\n global_user_namespace.user_ns['v_from_namespace'] = 'value-sent-to-gen'\n result_func = list(nspace['f2'](110))[0]\n assert nspace['gen_was_called'] == 'gen_was_called'\n assert result_func[0] == 110\n assert result_func[1] == 'value-sent-to-gen'\n assert result_func[2] is False\n result_func = list(nspace['f2a'](115))[0]\n assert nspace['gen_A_was_called'] == 'gen_was_called'\n assert result_func[0] == 115\n assert result_func[1] == 'value-sent-to-gen'\n\n\ndef test_global_user_namespace():\n \"\"\"\n Basic test for ``global_user_namespace``.\n \"\"\"\n ns = {'ab': 1, 'cd': 2}\n global_user_namespace.set_user_namespace(user_ns=ns)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n global_user_namespace.set_user_namespace(user_ns={}, use_ipython=True)\n assert global_user_namespace.user_ns == {}\n assert global_user_namespace.use_ipython is True\n global_user_namespace.set_user_namespace(user_ns=ns, use_ipython=False)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n\n\n_happi_json_db_1 = \"\"\"\n{\n \"det\": {\n \"_id\": \"det\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.DetWithCountTime\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"det\",\n \"type\": \"OphydItem\"\n },\n \"motor\": {\n \"_id\": \"motor\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxisNoPosition\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor\",\n \"type\": \"OphydItem\"\n },\n \"motor1\": {\n \"_id\": \"motor1\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxisNoHints\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor1\",\n \"type\": \"OphydItem\"\n },\n \"tst_motor2\": {\n \"_id\": \"tst_motor2\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxisNoHints\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"tst_motor2\",\n \"type\": \"OphydItem\"\n },\n \"motor3\": {\n \"_id\": \"motor3\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxis\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor3\",\n \"type\": \"OphydItem\"\n },\n \"motor3_duplicate_error\": {\n \"_id\": \"motor3\",\n \"active\": false,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxis\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor3\",\n \"type\": \"OphydItem\"\n }\n}\n\"\"\"\n\n\ndef _configure_happi(tmp_path, monkeypatch, json_devices):\n path_json = os.path.join(tmp_path, 'sim_devices.json')\n path_ini = os.path.join(tmp_path, 'happi.ini')\n happi_ini_text = f'[DEFAULT]\\nbackend=json\\npath={path_json}'\n with open(path_ini, 'w') as f:\n f.write(happi_ini_text)\n with open(path_json, 'w') as f:\n f.write(json_devices)\n monkeypatch.setenv('HAPPI_CFG', path_ini)\n\n\n@pytest.mark.parametrize('device_names, loaded_names, kw_args, success, errmsg'\n , [([], [], {}, True, ''), (('det', 'motor'), ('det', 'motor'), {}, \n True, ''), (['det', 'motor'], ('det', 'motor'), {}, True, ''), ((('det',\n ''), ['motor', '']), ('det', 'motor'), {}, True, ''), (('det', ['motor',\n '']), ('det', 'motor'), {}, True, ''), (('det', ('motor', ''), (\n 'tst_motor2', 'motor2')), ('det', 'motor', 'motor2'), {}, True, ''), ((\n ('motor1', 'motor1_copy1'), ('motor1', 'motor1_copy2')), (\n 'motor1_copy1', 'motor1_copy2'), {}, True, ''), (10, ('det', 'motor'),\n {}, False, \"Parameter 'device_names' value must be a tuple or a list\"),\n ('string', ('det', 'motor'), {}, False,\n \"Parameter 'device_names' value must be a tuple or a list\"), (('det', \n 10), ('det', 'motor'), {}, False,\n \"Parameter 'device_names': element .* must be str, tuple or list\"), ((\n 10, 'motor'), ('det', 'motor'), {}, False,\n \"Parameter 'device_names': element .* must be str, tuple or list\"), ((\n 'det', (10, 'motor2')), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', ('tst_motor2', 10\n )), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', ('tst_motor2',\n 'motor2', 10)), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', 'motor10'), (\n 'det', 'motor10'), {}, False, 'No devices with name'), (('det',\n 'motor3'), ('det', 'motor3'), {}, False, 'Multiple devices with name'),\n (('det', 'motor3'), ('det', 'motor3'), {'active': True}, True, ''), ((\n 'det', 'motor3'), ('det', 'motor3'), {'active': False}, False,\n \"No devices with name 'det' were found in Happi database.\"), (('motor3'\n ,), ('motor3',), {'active': False}, True, ''), (('det', ['motor',\n 'motor3_new']), ('det', 'motor3_new'), {}, True, ''), (('det', ['motor',\n 'Motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'moTor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n '_motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n ' motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor ']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor_$new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n '2motor_$new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers')])\ndef test_load_devices_from_happi_1(tmp_path, monkeypatch, device_names,\n loaded_names, kw_args, success, errmsg):\n \"\"\"\n Tests for ``load_devices_from_happi``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n if success:\n ns = {}\n dlist = load_devices_from_happi(device_names, namespace=ns, **kw_args)\n assert len(ns) == len(loaded_names), str(ns)\n for d in loaded_names:\n assert d in ns\n assert set(dlist) == set(loaded_names)\n else:\n with pytest.raises(Exception, match=errmsg):\n ns = {}\n load_devices_from_happi(device_names, namespace=ns, **kw_args)\n\n def _test_loading(device_names, loaded_names):\n if success:\n load_devices_from_happi(device_names, namespace=locals(), **kw_args\n )\n for d in loaded_names:\n assert d in locals()\n else:\n with pytest.raises(Exception, match=errmsg):\n load_devices_from_happi(device_names, namespace=locals(),\n **kw_args)\n _test_loading(device_names=device_names, loaded_names=loaded_names)\n\n\ndef test_load_devices_from_happi_2_fail(tmp_path, monkeypatch):\n \"\"\"\n Function ``load_devices_from_happi``: parameter ``namespace`` is required and must be of type ``dict``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n with pytest.raises(TypeError, match=\n \"missing 1 required keyword-only argument: 'namespace'\"):\n load_devices_from_happi(['det', 'motor'])\n with pytest.raises(TypeError, match=\n \"Parameter 'namespace' must be a dictionary\"):\n load_devices_from_happi(['det', 'motor'], namespace=[1, 2, 3])\n", "step-4": "import os\nimport inspect\nimport pytest\nfrom ._common import copy_default_profile_collection, patch_first_startup_file\nfrom bluesky_queueserver.manager.profile_tools import global_user_namespace, load_devices_from_happi\nfrom bluesky_queueserver.manager.profile_ops import load_profile_collection\n\n\ndef create_local_imports_files(tmp_path):\n path_dir = os.path.join(tmp_path, 'dir_local_imports')\n fln_func = os.path.join(path_dir, 'file_func.py')\n fln_gen = os.path.join(path_dir, 'file_gen.py')\n os.makedirs(path_dir, exist_ok=True)\n code1 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f1(some_value, user_ns, ipython):\n user_ns[\"func_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f1a(some_value, user_ns):\n user_ns[\"func_A_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"])\n\n\"\"\"\n with open(fln_func, 'w') as f:\n f.writelines(code1)\n code2 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f2(some_value, user_ns, ipython):\n user_ns[\"gen_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f2a(some_value, user_ns):\n user_ns[\"gen_A_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"])\n\n@set_user_ns\ndef f3(some_value, user_ns, ipython):\n user_ns[\"value_f3\"] = some_value\n\nf3(91)\n\n\"\"\"\n with open(fln_gen, 'w') as f:\n f.writelines(code2)\n\n\npatch_code = \"\"\"\nfrom dir_local_imports.file_func import f1, f1a\nfrom dir_local_imports.file_gen import f2, f2a\n\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n@set_user_ns\ndef f4(some_value, user_ns, ipython):\n user_ns[\"value_f4\"] = some_value\n\nf4(90)\n\n\"\"\"\n\n\ndef test_set_user_ns_1(tmp_path):\n \"\"\"\n Tests for ``set_user_ns`` decorator. The functionality of the decorator\n is fully tested (only without IPython):\n - using ``global_user_namespace`` to pass values in and out of the function\n defined in the imported module (emulation of ``get_ipython().user_ns``).\n - checking if the function is executed from IPython (only for the function\n defined in the imported module).\n \"\"\"\n pc_path = copy_default_profile_collection(tmp_path)\n create_local_imports_files(pc_path)\n patch_first_startup_file(pc_path, patch_code)\n nspace = load_profile_collection(pc_path)\n assert len(nspace) > 0, 'Failed to load the profile collection'\n assert 'f1' in nspace, 'Test for local imports failed'\n assert 'f2' in nspace, 'Test for local imports failed'\n assert inspect.isgeneratorfunction(nspace['f1']) is False\n assert inspect.isgeneratorfunction(nspace['f2']) is True\n\n def check_signature(func):\n params = inspect.signature(func).parameters\n assert 'user_ns' not in params\n assert 'ipython' not in params\n check_signature(nspace['f1'])\n check_signature(nspace['f1a'])\n check_signature(nspace['f2'])\n check_signature(nspace['f2a'])\n assert nspace['value_f3'] == 91\n assert nspace['value_f4'] == 90\n global_user_namespace.set_user_namespace(user_ns=nspace, use_ipython=False)\n global_user_namespace.user_ns['v_from_namespace'] = 'value-sent-to-func'\n assert nspace['v_from_namespace'] == 'value-sent-to-func'\n result_func = nspace['f1'](60)\n assert nspace['func_was_called'] == 'func_was_called'\n assert result_func[0] == 60\n assert result_func[1] == 'value-sent-to-func'\n assert result_func[2] is False\n result_func = nspace['f1a'](65)\n assert nspace['func_A_was_called'] == 'func_was_called'\n assert result_func[0] == 65\n assert result_func[1] == 'value-sent-to-func'\n global_user_namespace.user_ns['v_from_namespace'] = 'value-sent-to-gen'\n result_func = list(nspace['f2'](110))[0]\n assert nspace['gen_was_called'] == 'gen_was_called'\n assert result_func[0] == 110\n assert result_func[1] == 'value-sent-to-gen'\n assert result_func[2] is False\n result_func = list(nspace['f2a'](115))[0]\n assert nspace['gen_A_was_called'] == 'gen_was_called'\n assert result_func[0] == 115\n assert result_func[1] == 'value-sent-to-gen'\n\n\ndef test_global_user_namespace():\n \"\"\"\n Basic test for ``global_user_namespace``.\n \"\"\"\n ns = {'ab': 1, 'cd': 2}\n global_user_namespace.set_user_namespace(user_ns=ns)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n global_user_namespace.set_user_namespace(user_ns={}, use_ipython=True)\n assert global_user_namespace.user_ns == {}\n assert global_user_namespace.use_ipython is True\n global_user_namespace.set_user_namespace(user_ns=ns, use_ipython=False)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n\n\n_happi_json_db_1 = \"\"\"\n{\n \"det\": {\n \"_id\": \"det\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.DetWithCountTime\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"det\",\n \"type\": \"OphydItem\"\n },\n \"motor\": {\n \"_id\": \"motor\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxisNoPosition\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor\",\n \"type\": \"OphydItem\"\n },\n \"motor1\": {\n \"_id\": \"motor1\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxisNoHints\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor1\",\n \"type\": \"OphydItem\"\n },\n \"tst_motor2\": {\n \"_id\": \"tst_motor2\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxisNoHints\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"tst_motor2\",\n \"type\": \"OphydItem\"\n },\n \"motor3\": {\n \"_id\": \"motor3\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxis\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor3\",\n \"type\": \"OphydItem\"\n },\n \"motor3_duplicate_error\": {\n \"_id\": \"motor3\",\n \"active\": false,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxis\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor3\",\n \"type\": \"OphydItem\"\n }\n}\n\"\"\"\n\n\ndef _configure_happi(tmp_path, monkeypatch, json_devices):\n path_json = os.path.join(tmp_path, 'sim_devices.json')\n path_ini = os.path.join(tmp_path, 'happi.ini')\n happi_ini_text = f'[DEFAULT]\\nbackend=json\\npath={path_json}'\n with open(path_ini, 'w') as f:\n f.write(happi_ini_text)\n with open(path_json, 'w') as f:\n f.write(json_devices)\n monkeypatch.setenv('HAPPI_CFG', path_ini)\n\n\n@pytest.mark.parametrize('device_names, loaded_names, kw_args, success, errmsg'\n , [([], [], {}, True, ''), (('det', 'motor'), ('det', 'motor'), {}, \n True, ''), (['det', 'motor'], ('det', 'motor'), {}, True, ''), ((('det',\n ''), ['motor', '']), ('det', 'motor'), {}, True, ''), (('det', ['motor',\n '']), ('det', 'motor'), {}, True, ''), (('det', ('motor', ''), (\n 'tst_motor2', 'motor2')), ('det', 'motor', 'motor2'), {}, True, ''), ((\n ('motor1', 'motor1_copy1'), ('motor1', 'motor1_copy2')), (\n 'motor1_copy1', 'motor1_copy2'), {}, True, ''), (10, ('det', 'motor'),\n {}, False, \"Parameter 'device_names' value must be a tuple or a list\"),\n ('string', ('det', 'motor'), {}, False,\n \"Parameter 'device_names' value must be a tuple or a list\"), (('det', \n 10), ('det', 'motor'), {}, False,\n \"Parameter 'device_names': element .* must be str, tuple or list\"), ((\n 10, 'motor'), ('det', 'motor'), {}, False,\n \"Parameter 'device_names': element .* must be str, tuple or list\"), ((\n 'det', (10, 'motor2')), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', ('tst_motor2', 10\n )), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', ('tst_motor2',\n 'motor2', 10)), ('det', 'motor'), {}, False,\n 'element .* is expected to be in the form'), (('det', 'motor10'), (\n 'det', 'motor10'), {}, False, 'No devices with name'), (('det',\n 'motor3'), ('det', 'motor3'), {}, False, 'Multiple devices with name'),\n (('det', 'motor3'), ('det', 'motor3'), {'active': True}, True, ''), ((\n 'det', 'motor3'), ('det', 'motor3'), {'active': False}, False,\n \"No devices with name 'det' were found in Happi database.\"), (('motor3'\n ,), ('motor3',), {'active': False}, True, ''), (('det', ['motor',\n 'motor3_new']), ('det', 'motor3_new'), {}, True, ''), (('det', ['motor',\n 'Motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'moTor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n '_motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n ' motor']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor ']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n 'motor_$new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers'), (('det', ['motor',\n '2motor_$new']), ('det', 'motor'), {}, False,\n 'may consist of lowercase letters, numbers')])\ndef test_load_devices_from_happi_1(tmp_path, monkeypatch, device_names,\n loaded_names, kw_args, success, errmsg):\n \"\"\"\n Tests for ``load_devices_from_happi``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n if success:\n ns = {}\n dlist = load_devices_from_happi(device_names, namespace=ns, **kw_args)\n assert len(ns) == len(loaded_names), str(ns)\n for d in loaded_names:\n assert d in ns\n assert set(dlist) == set(loaded_names)\n else:\n with pytest.raises(Exception, match=errmsg):\n ns = {}\n load_devices_from_happi(device_names, namespace=ns, **kw_args)\n\n def _test_loading(device_names, loaded_names):\n if success:\n load_devices_from_happi(device_names, namespace=locals(), **kw_args\n )\n for d in loaded_names:\n assert d in locals()\n else:\n with pytest.raises(Exception, match=errmsg):\n load_devices_from_happi(device_names, namespace=locals(),\n **kw_args)\n _test_loading(device_names=device_names, loaded_names=loaded_names)\n\n\ndef test_load_devices_from_happi_2_fail(tmp_path, monkeypatch):\n \"\"\"\n Function ``load_devices_from_happi``: parameter ``namespace`` is required and must be of type ``dict``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n with pytest.raises(TypeError, match=\n \"missing 1 required keyword-only argument: 'namespace'\"):\n load_devices_from_happi(['det', 'motor'])\n with pytest.raises(TypeError, match=\n \"Parameter 'namespace' must be a dictionary\"):\n load_devices_from_happi(['det', 'motor'], namespace=[1, 2, 3])\n", "step-5": "import os\nimport inspect\nimport pytest\n\nfrom ._common import copy_default_profile_collection, patch_first_startup_file\nfrom bluesky_queueserver.manager.profile_tools import global_user_namespace, load_devices_from_happi\nfrom bluesky_queueserver.manager.profile_ops import load_profile_collection\n\n\ndef create_local_imports_files(tmp_path):\n path_dir = os.path.join(tmp_path, \"dir_local_imports\")\n fln_func = os.path.join(path_dir, \"file_func.py\")\n fln_gen = os.path.join(path_dir, \"file_gen.py\")\n\n os.makedirs(path_dir, exist_ok=True)\n\n # Create file1\n code1 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f1(some_value, user_ns, ipython):\n user_ns[\"func_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f1a(some_value, user_ns):\n user_ns[\"func_A_was_called\"] = \"func_was_called\"\n return (some_value, user_ns[\"v_from_namespace\"])\n\n\"\"\"\n with open(fln_func, \"w\") as f:\n f.writelines(code1)\n\n # Create file2\n code2 = \"\"\"\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n# Function that has the parameter 'ipython'\n@set_user_ns\ndef f2(some_value, user_ns, ipython):\n user_ns[\"gen_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"], bool(ipython))\n\n# Function that has no parameter 'ipython'\n@set_user_ns\ndef f2a(some_value, user_ns):\n user_ns[\"gen_A_was_called\"] = \"gen_was_called\"\n yield (some_value, user_ns[\"v_from_namespace\"])\n\n@set_user_ns\ndef f3(some_value, user_ns, ipython):\n user_ns[\"value_f3\"] = some_value\n\nf3(91)\n\n\"\"\"\n with open(fln_gen, \"w\") as f:\n f.writelines(code2)\n\n\npatch_code = \"\"\"\nfrom dir_local_imports.file_func import f1, f1a\nfrom dir_local_imports.file_gen import f2, f2a\n\nfrom bluesky_queueserver.manager.profile_tools import set_user_ns\n\n@set_user_ns\ndef f4(some_value, user_ns, ipython):\n user_ns[\"value_f4\"] = some_value\n\nf4(90)\n\n\"\"\"\n\n\ndef test_set_user_ns_1(tmp_path):\n \"\"\"\n Tests for ``set_user_ns`` decorator. The functionality of the decorator\n is fully tested (only without IPython):\n - using ``global_user_namespace`` to pass values in and out of the function\n defined in the imported module (emulation of ``get_ipython().user_ns``).\n - checking if the function is executed from IPython (only for the function\n defined in the imported module).\n \"\"\"\n pc_path = copy_default_profile_collection(tmp_path)\n\n create_local_imports_files(pc_path)\n patch_first_startup_file(pc_path, patch_code)\n\n nspace = load_profile_collection(pc_path)\n assert len(nspace) > 0, \"Failed to load the profile collection\"\n assert \"f1\" in nspace, \"Test for local imports failed\"\n assert \"f2\" in nspace, \"Test for local imports failed\"\n\n # Test if the decorator `set_user_ns` does not change function type\n assert inspect.isgeneratorfunction(nspace[\"f1\"]) is False\n assert inspect.isgeneratorfunction(nspace[\"f2\"]) is True\n\n # Check if the extra arguments are removed from the function signature\n def check_signature(func):\n params = inspect.signature(func).parameters\n assert \"user_ns\" not in params\n assert \"ipython\" not in params\n\n check_signature(nspace[\"f1\"])\n check_signature(nspace[\"f1a\"])\n check_signature(nspace[\"f2\"])\n check_signature(nspace[\"f2a\"])\n\n assert nspace[\"value_f3\"] == 91\n assert nspace[\"value_f4\"] == 90\n\n # Test function\n global_user_namespace.set_user_namespace(user_ns=nspace, use_ipython=False)\n global_user_namespace.user_ns[\"v_from_namespace\"] = \"value-sent-to-func\"\n assert nspace[\"v_from_namespace\"] == \"value-sent-to-func\"\n\n result_func = nspace[\"f1\"](60)\n assert nspace[\"func_was_called\"] == \"func_was_called\"\n assert result_func[0] == 60\n assert result_func[1] == \"value-sent-to-func\"\n assert result_func[2] is False\n\n result_func = nspace[\"f1a\"](65)\n assert nspace[\"func_A_was_called\"] == \"func_was_called\"\n assert result_func[0] == 65\n assert result_func[1] == \"value-sent-to-func\"\n\n # Test generator\n global_user_namespace.user_ns[\"v_from_namespace\"] = \"value-sent-to-gen\"\n result_func = list(nspace[\"f2\"](110))[0]\n assert nspace[\"gen_was_called\"] == \"gen_was_called\"\n assert result_func[0] == 110\n assert result_func[1] == \"value-sent-to-gen\"\n assert result_func[2] is False\n\n result_func = list(nspace[\"f2a\"](115))[0]\n assert nspace[\"gen_A_was_called\"] == \"gen_was_called\"\n assert result_func[0] == 115\n assert result_func[1] == \"value-sent-to-gen\"\n\n\ndef test_global_user_namespace():\n \"\"\"\n Basic test for ``global_user_namespace``.\n \"\"\"\n ns = {\"ab\": 1, \"cd\": 2}\n global_user_namespace.set_user_namespace(user_ns=ns)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n\n global_user_namespace.set_user_namespace(user_ns={}, use_ipython=True)\n assert global_user_namespace.user_ns == {}\n assert global_user_namespace.use_ipython is True\n\n global_user_namespace.set_user_namespace(user_ns=ns, use_ipython=False)\n assert global_user_namespace.user_ns == ns\n assert global_user_namespace.use_ipython is False\n\n\n_happi_json_db_1 = \"\"\"\n{\n \"det\": {\n \"_id\": \"det\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.DetWithCountTime\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"det\",\n \"type\": \"OphydItem\"\n },\n \"motor\": {\n \"_id\": \"motor\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxisNoPosition\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor\",\n \"type\": \"OphydItem\"\n },\n \"motor1\": {\n \"_id\": \"motor1\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxisNoHints\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor1\",\n \"type\": \"OphydItem\"\n },\n \"tst_motor2\": {\n \"_id\": \"tst_motor2\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxisNoHints\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"tst_motor2\",\n \"type\": \"OphydItem\"\n },\n \"motor3\": {\n \"_id\": \"motor3\",\n \"active\": true,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxis\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor3\",\n \"type\": \"OphydItem\"\n },\n \"motor3_duplicate_error\": {\n \"_id\": \"motor3\",\n \"active\": false,\n \"args\": [],\n \"device_class\": \"ophyd.sim.SynAxis\",\n \"documentation\": null,\n \"kwargs\": {\n \"name\": \"{{name}}\"\n },\n \"name\": \"motor3\",\n \"type\": \"OphydItem\"\n }\n}\n\"\"\"\n\n\ndef _configure_happi(tmp_path, monkeypatch, json_devices):\n path_json = os.path.join(tmp_path, \"sim_devices.json\")\n path_ini = os.path.join(tmp_path, \"happi.ini\")\n\n happi_ini_text = f\"[DEFAULT]\\nbackend=json\\npath={path_json}\"\n\n with open(path_ini, \"w\") as f:\n f.write(happi_ini_text)\n\n with open(path_json, \"w\") as f:\n f.write(json_devices)\n\n monkeypatch.setenv(\"HAPPI_CFG\", path_ini)\n\n\n# fmt: off\n@pytest.mark.parametrize(\"device_names, loaded_names, kw_args, success, errmsg\", [\n ([], [], {}, True, \"\"), # No devices are loaded if the list of devices is empty\n ((\"det\", \"motor\"), (\"det\", \"motor\"), {}, True, \"\"),\n ([\"det\", \"motor\"], (\"det\", \"motor\"), {}, True, \"\"),\n (((\"det\", \"\"), [\"motor\", \"\"]), (\"det\", \"motor\"), {}, True, \"\"),\n ((\"det\", [\"motor\", \"\"]), (\"det\", \"motor\"), {}, True, \"\"),\n ((\"det\", (\"motor\", \"\"), (\"tst_motor2\", \"motor2\")), (\"det\", \"motor\", \"motor2\"), {}, True, \"\"),\n # This is not typical use case, but the same device may be loaded multiple times\n # with different names if needed.\n (((\"motor1\", \"motor1_copy1\"), (\"motor1\", \"motor1_copy2\")), (\"motor1_copy1\", \"motor1_copy2\"), {}, True, \"\"),\n # Incorrect type of the device list\n (10, (\"det\", \"motor\"), {}, False, \"Parameter 'device_names' value must be a tuple or a list\"),\n (\"string\", (\"det\", \"motor\"), {}, False, \"Parameter 'device_names' value must be a tuple or a list\"),\n # Incorrecty type or form of a device list element\n ((\"det\", 10), (\"det\", \"motor\"), {}, False, \"Parameter 'device_names': element .* must be str, tuple or list\"),\n ((10, \"motor\"), (\"det\", \"motor\"), {}, False,\n \"Parameter 'device_names': element .* must be str, tuple or list\"),\n ((\"det\", (10, \"motor2\")), (\"det\", \"motor\"), {}, False, \"element .* is expected to be in the form\"),\n ((\"det\", (\"tst_motor2\", 10)), (\"det\", \"motor\"), {}, False, \"element .* is expected to be in the form\"),\n ((\"det\", (\"tst_motor2\", \"motor2\", 10)), (\"det\", \"motor\"), {}, False,\n \"element .* is expected to be in the form\"),\n # No device found\n ((\"det\", \"motor10\"), (\"det\", \"motor10\"), {}, False, \"No devices with name\"),\n # Multiple devices found (search for \"motor3\" yields multile devices, this is database issue)\n ((\"det\", \"motor3\"), (\"det\", \"motor3\"), {}, False, \"Multiple devices with name\"),\n # Use additional search parameters. (Two entries for \"motor3\" differ in the value of `active` field.\n # A single entry for `det` has `active==True`.)\n ((\"det\", \"motor3\"), (\"det\", \"motor3\"), {\"active\": True}, True, \"\"),\n ((\"det\", \"motor3\"), (\"det\", \"motor3\"), {\"active\": False}, False,\n \"No devices with name 'det' were found in Happi database.\"),\n ((\"motor3\",), (\"motor3\",), {\"active\": False}, True, \"\"),\n # Verify that valid device names are accepted\n ((\"det\", [\"motor\", \"motor3_new\"]), (\"det\", \"motor3_new\"), {}, True, \"\"),\n # Invalid new device name\n ((\"det\", [\"motor\", \"Motor\"]), (\"det\", \"motor\"), {}, False, \"may consist of lowercase letters, numbers\"),\n ((\"det\", [\"motor\", \"moTor\"]), (\"det\", \"motor\"), {}, False, \"may consist of lowercase letters, numbers\"),\n ((\"det\", [\"motor\", \"_motor\"]), (\"det\", \"motor\"), {}, False, \"may consist of lowercase letters, numbers\"),\n ((\"det\", [\"motor\", \" motor\"]), (\"det\", \"motor\"), {}, False, \"may consist of lowercase letters, numbers\"),\n ((\"det\", [\"motor\", \"motor \"]), (\"det\", \"motor\"), {}, False, \"may consist of lowercase letters, numbers\"),\n ((\"det\", [\"motor\", \"motor new\"]), (\"det\", \"motor\"), {}, False, \"may consist of lowercase letters, numbers\"),\n ((\"det\", [\"motor\", \"motor_$new\"]), (\"det\", \"motor\"), {}, False, \"may consist of lowercase letters, numbers\"),\n ((\"det\", [\"motor\", \"2motor_$new\"]), (\"det\", \"motor\"), {}, False, \"may consist of lowercase letters, numbers\"),\n])\n# fmt: on\ndef test_load_devices_from_happi_1(tmp_path, monkeypatch, device_names, loaded_names, kw_args, success, errmsg):\n \"\"\"\n Tests for ``load_devices_from_happi``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n\n # Load as a dictionary\n if success:\n ns = {}\n dlist = load_devices_from_happi(device_names, namespace=ns, **kw_args)\n assert len(ns) == len(loaded_names), str(ns)\n for d in loaded_names:\n assert d in ns\n assert set(dlist) == set(loaded_names)\n else:\n with pytest.raises(Exception, match=errmsg):\n ns = {}\n load_devices_from_happi(device_names, namespace=ns, **kw_args)\n\n # Load in local namespace\n def _test_loading(device_names, loaded_names):\n if success:\n load_devices_from_happi(device_names, namespace=locals(), **kw_args)\n for d in loaded_names:\n assert d in locals()\n else:\n with pytest.raises(Exception, match=errmsg):\n load_devices_from_happi(device_names, namespace=locals(), **kw_args)\n\n _test_loading(device_names=device_names, loaded_names=loaded_names)\n\n\ndef test_load_devices_from_happi_2_fail(tmp_path, monkeypatch):\n \"\"\"\n Function ``load_devices_from_happi``: parameter ``namespace`` is required and must be of type ``dict``.\n \"\"\"\n _configure_happi(tmp_path, monkeypatch, json_devices=_happi_json_db_1)\n\n # Missing 'namespace' parameter\n with pytest.raises(TypeError, match=\"missing 1 required keyword-only argument: 'namespace'\"):\n load_devices_from_happi([\"det\", \"motor\"])\n\n # Incorrect type of 'namespace' parameter\n with pytest.raises(TypeError, match=\"Parameter 'namespace' must be a dictionary\"):\n load_devices_from_happi([\"det\", \"motor\"], namespace=[1, 2, 3])\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
import RPi.GPIO as GPIO import time from datetime import datetime led1 = [('g', 40), ('f', 38), ('a', 36), ('b', 32), ('e', 26), ('d', 24), ('c', 22)] led2 = [('g', 19), ('f', 15), ('a', 13), ('b', 11), ('e', 7), ('d', 5), ('c', 3)] numbers = [ ('a', 'b', 'c', 'd', 'e', 'f'), ('b', 'c'), ('a', 'b', 'g', 'e', 'd'), ('a', 'b', 'g', 'c', 'd'), ('f', 'g', 'b', 'c'), ('a', 'f', 'g', 'c', 'd'), ('a', 'f', 'g', 'c', 'd', 'e'), ('a', 'b', 'c'), ('a', 'b', 'c', 'd', 'e', 'f', 'g'), ('a', 'b', 'c', 'd', 'f', 'g') ] reset = 12 minus = 16 more = 18 GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(reset, GPIO.IN) GPIO.setup(minus, GPIO.IN) GPIO.setup(more, GPIO.IN) def setupLed1(): for port in led1: GPIO.setup(port[1], GPIO.OUT) def setupLed2(): for port in led2: GPIO.setup(port[1], GPIO.OUT) def statusLed(port, status): GPIO.output(port, status) def turnOnAllLeds(): for led in led1: statusLed(led[1], True) for led in led2: statusLed(led[1], True) def turnOffAllLeds(): for led in led1: statusLed(led[1], False) for led in led2: statusLed(led[1], False) def turnOffOneLed(led): for port in led: statusLed(port[1], False) def createNumber(ledNumber, number): turnOffOneLed(ledNumber) for i in range(10): if number == i: for letter in numbers[i]: for led in ledNumber: if led[0] == letter: statusLed(led[1], True) def createNumber2Leds(led1, led2, number): if number < 10: createNumber(led1, 0) createNumber(led2, number) else: decenas = number / 10 unidades = number % 10 createNumber(led1, decenas) createNumber(led2, unidades) def titileoNumber2Leds(led1, led2, number): for i in range(3): turnOffAllLeds() time.sleep(0.25) createNumber2Leds(led1, led2, number) time.sleep(0.25) def digiTurno(): contador = 0 titileoNumber2Leds(led1, led2, contador) while True: if GPIO.input(reset): contador = 0 print("-"*20+" RESET "+"-"*20) print(datetime.now()) titileoNumber2Leds(led1, led2, contador) print("Numero actual = "+str(contador)) time.sleep(.3) if GPIO.input(more): if contador < 99: contador += 1 else: print(datetime.now()) contador = 0 print("Numero actual = "+str(contador)) createNumber2Leds(led1, led2, contador) time.sleep(.3) if GPIO.input(minus): if contador == 0: contador = 99 else: contador = contador-1 print("Numero actual = "+str(contador)) createNumber2Leds(led1, led2, contador) time.sleep(.3) def main(): setupLed1() setupLed2() turnOffAllLeds() try: print("Presione un boton para continuar") digiTurno() except (KeyboardInterrupt, SystemExit): GPIO.cleanup() if __name__ == "__main__": main()
normal
{ "blob_id": "0d022291f9ace02ef1ee5c462657ea6376a0e6a4", "index": 9436, "step-1": "<mask token>\n\n\ndef setupLed1():\n for port in led1:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef setupLed2():\n for port in led2:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef statusLed(port, status):\n GPIO.output(port, status)\n\n\ndef turnOnAllLeds():\n for led in led1:\n statusLed(led[1], True)\n for led in led2:\n statusLed(led[1], True)\n\n\ndef turnOffAllLeds():\n for led in led1:\n statusLed(led[1], False)\n for led in led2:\n statusLed(led[1], False)\n\n\ndef turnOffOneLed(led):\n for port in led:\n statusLed(port[1], False)\n\n\n<mask token>\n\n\ndef createNumber2Leds(led1, led2, number):\n if number < 10:\n createNumber(led1, 0)\n createNumber(led2, number)\n else:\n decenas = number / 10\n unidades = number % 10\n createNumber(led1, decenas)\n createNumber(led2, unidades)\n\n\ndef titileoNumber2Leds(led1, led2, number):\n for i in range(3):\n turnOffAllLeds()\n time.sleep(0.25)\n createNumber2Leds(led1, led2, number)\n time.sleep(0.25)\n\n\ndef digiTurno():\n contador = 0\n titileoNumber2Leds(led1, led2, contador)\n while True:\n if GPIO.input(reset):\n contador = 0\n print('-' * 20 + ' RESET ' + '-' * 20)\n print(datetime.now())\n titileoNumber2Leds(led1, led2, contador)\n print('Numero actual = ' + str(contador))\n time.sleep(0.3)\n if GPIO.input(more):\n if contador < 99:\n contador += 1\n else:\n print(datetime.now())\n contador = 0\n print('Numero actual = ' + str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(0.3)\n if GPIO.input(minus):\n if contador == 0:\n contador = 99\n else:\n contador = contador - 1\n print('Numero actual = ' + str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(0.3)\n\n\ndef main():\n setupLed1()\n setupLed2()\n turnOffAllLeds()\n try:\n print('Presione un boton para continuar')\n digiTurno()\n except (KeyboardInterrupt, SystemExit):\n GPIO.cleanup()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef setupLed1():\n for port in led1:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef setupLed2():\n for port in led2:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef statusLed(port, status):\n GPIO.output(port, status)\n\n\ndef turnOnAllLeds():\n for led in led1:\n statusLed(led[1], True)\n for led in led2:\n statusLed(led[1], True)\n\n\ndef turnOffAllLeds():\n for led in led1:\n statusLed(led[1], False)\n for led in led2:\n statusLed(led[1], False)\n\n\ndef turnOffOneLed(led):\n for port in led:\n statusLed(port[1], False)\n\n\ndef createNumber(ledNumber, number):\n turnOffOneLed(ledNumber)\n for i in range(10):\n if number == i:\n for letter in numbers[i]:\n for led in ledNumber:\n if led[0] == letter:\n statusLed(led[1], True)\n\n\ndef createNumber2Leds(led1, led2, number):\n if number < 10:\n createNumber(led1, 0)\n createNumber(led2, number)\n else:\n decenas = number / 10\n unidades = number % 10\n createNumber(led1, decenas)\n createNumber(led2, unidades)\n\n\ndef titileoNumber2Leds(led1, led2, number):\n for i in range(3):\n turnOffAllLeds()\n time.sleep(0.25)\n createNumber2Leds(led1, led2, number)\n time.sleep(0.25)\n\n\ndef digiTurno():\n contador = 0\n titileoNumber2Leds(led1, led2, contador)\n while True:\n if GPIO.input(reset):\n contador = 0\n print('-' * 20 + ' RESET ' + '-' * 20)\n print(datetime.now())\n titileoNumber2Leds(led1, led2, contador)\n print('Numero actual = ' + str(contador))\n time.sleep(0.3)\n if GPIO.input(more):\n if contador < 99:\n contador += 1\n else:\n print(datetime.now())\n contador = 0\n print('Numero actual = ' + str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(0.3)\n if GPIO.input(minus):\n if contador == 0:\n contador = 99\n else:\n contador = contador - 1\n print('Numero actual = ' + str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(0.3)\n\n\ndef main():\n setupLed1()\n setupLed2()\n turnOffAllLeds()\n try:\n print('Presione un boton para continuar')\n digiTurno()\n except (KeyboardInterrupt, SystemExit):\n GPIO.cleanup()\n\n\n<mask token>\n", "step-3": "<mask token>\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\nGPIO.setup(reset, GPIO.IN)\nGPIO.setup(minus, GPIO.IN)\nGPIO.setup(more, GPIO.IN)\n\n\ndef setupLed1():\n for port in led1:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef setupLed2():\n for port in led2:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef statusLed(port, status):\n GPIO.output(port, status)\n\n\ndef turnOnAllLeds():\n for led in led1:\n statusLed(led[1], True)\n for led in led2:\n statusLed(led[1], True)\n\n\ndef turnOffAllLeds():\n for led in led1:\n statusLed(led[1], False)\n for led in led2:\n statusLed(led[1], False)\n\n\ndef turnOffOneLed(led):\n for port in led:\n statusLed(port[1], False)\n\n\ndef createNumber(ledNumber, number):\n turnOffOneLed(ledNumber)\n for i in range(10):\n if number == i:\n for letter in numbers[i]:\n for led in ledNumber:\n if led[0] == letter:\n statusLed(led[1], True)\n\n\ndef createNumber2Leds(led1, led2, number):\n if number < 10:\n createNumber(led1, 0)\n createNumber(led2, number)\n else:\n decenas = number / 10\n unidades = number % 10\n createNumber(led1, decenas)\n createNumber(led2, unidades)\n\n\ndef titileoNumber2Leds(led1, led2, number):\n for i in range(3):\n turnOffAllLeds()\n time.sleep(0.25)\n createNumber2Leds(led1, led2, number)\n time.sleep(0.25)\n\n\ndef digiTurno():\n contador = 0\n titileoNumber2Leds(led1, led2, contador)\n while True:\n if GPIO.input(reset):\n contador = 0\n print('-' * 20 + ' RESET ' + '-' * 20)\n print(datetime.now())\n titileoNumber2Leds(led1, led2, contador)\n print('Numero actual = ' + str(contador))\n time.sleep(0.3)\n if GPIO.input(more):\n if contador < 99:\n contador += 1\n else:\n print(datetime.now())\n contador = 0\n print('Numero actual = ' + str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(0.3)\n if GPIO.input(minus):\n if contador == 0:\n contador = 99\n else:\n contador = contador - 1\n print('Numero actual = ' + str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(0.3)\n\n\ndef main():\n setupLed1()\n setupLed2()\n turnOffAllLeds()\n try:\n print('Presione un boton para continuar')\n digiTurno()\n except (KeyboardInterrupt, SystemExit):\n GPIO.cleanup()\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "<mask token>\nled1 = [('g', 40), ('f', 38), ('a', 36), ('b', 32), ('e', 26), ('d', 24), (\n 'c', 22)]\nled2 = [('g', 19), ('f', 15), ('a', 13), ('b', 11), ('e', 7), ('d', 5), (\n 'c', 3)]\nnumbers = [('a', 'b', 'c', 'd', 'e', 'f'), ('b', 'c'), ('a', 'b', 'g', 'e',\n 'd'), ('a', 'b', 'g', 'c', 'd'), ('f', 'g', 'b', 'c'), ('a', 'f', 'g',\n 'c', 'd'), ('a', 'f', 'g', 'c', 'd', 'e'), ('a', 'b', 'c'), ('a', 'b',\n 'c', 'd', 'e', 'f', 'g'), ('a', 'b', 'c', 'd', 'f', 'g')]\nreset = 12\nminus = 16\nmore = 18\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\nGPIO.setup(reset, GPIO.IN)\nGPIO.setup(minus, GPIO.IN)\nGPIO.setup(more, GPIO.IN)\n\n\ndef setupLed1():\n for port in led1:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef setupLed2():\n for port in led2:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef statusLed(port, status):\n GPIO.output(port, status)\n\n\ndef turnOnAllLeds():\n for led in led1:\n statusLed(led[1], True)\n for led in led2:\n statusLed(led[1], True)\n\n\ndef turnOffAllLeds():\n for led in led1:\n statusLed(led[1], False)\n for led in led2:\n statusLed(led[1], False)\n\n\ndef turnOffOneLed(led):\n for port in led:\n statusLed(port[1], False)\n\n\ndef createNumber(ledNumber, number):\n turnOffOneLed(ledNumber)\n for i in range(10):\n if number == i:\n for letter in numbers[i]:\n for led in ledNumber:\n if led[0] == letter:\n statusLed(led[1], True)\n\n\ndef createNumber2Leds(led1, led2, number):\n if number < 10:\n createNumber(led1, 0)\n createNumber(led2, number)\n else:\n decenas = number / 10\n unidades = number % 10\n createNumber(led1, decenas)\n createNumber(led2, unidades)\n\n\ndef titileoNumber2Leds(led1, led2, number):\n for i in range(3):\n turnOffAllLeds()\n time.sleep(0.25)\n createNumber2Leds(led1, led2, number)\n time.sleep(0.25)\n\n\ndef digiTurno():\n contador = 0\n titileoNumber2Leds(led1, led2, contador)\n while True:\n if GPIO.input(reset):\n contador = 0\n print('-' * 20 + ' RESET ' + '-' * 20)\n print(datetime.now())\n titileoNumber2Leds(led1, led2, contador)\n print('Numero actual = ' + str(contador))\n time.sleep(0.3)\n if GPIO.input(more):\n if contador < 99:\n contador += 1\n else:\n print(datetime.now())\n contador = 0\n print('Numero actual = ' + str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(0.3)\n if GPIO.input(minus):\n if contador == 0:\n contador = 99\n else:\n contador = contador - 1\n print('Numero actual = ' + str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(0.3)\n\n\ndef main():\n setupLed1()\n setupLed2()\n turnOffAllLeds()\n try:\n print('Presione un boton para continuar')\n digiTurno()\n except (KeyboardInterrupt, SystemExit):\n GPIO.cleanup()\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import RPi.GPIO as GPIO\nimport time\nfrom datetime import datetime\n\nled1 = [('g', 40), ('f', 38), ('a', 36), ('b', 32),\n ('e', 26), ('d', 24), ('c', 22)]\nled2 = [('g', 19), ('f', 15), ('a', 13),\n ('b', 11), ('e', 7), ('d', 5), ('c', 3)]\nnumbers = [\n ('a', 'b', 'c', 'd', 'e', 'f'),\n ('b', 'c'),\n ('a', 'b', 'g', 'e', 'd'),\n ('a', 'b', 'g', 'c', 'd'),\n ('f', 'g', 'b', 'c'),\n ('a', 'f', 'g', 'c', 'd'),\n ('a', 'f', 'g', 'c', 'd', 'e'),\n ('a', 'b', 'c'),\n ('a', 'b', 'c', 'd', 'e', 'f', 'g'),\n ('a', 'b', 'c', 'd', 'f', 'g')\n]\n\nreset = 12\nminus = 16\nmore = 18\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\nGPIO.setup(reset, GPIO.IN)\nGPIO.setup(minus, GPIO.IN)\nGPIO.setup(more, GPIO.IN)\n\n\ndef setupLed1():\n for port in led1:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef setupLed2():\n for port in led2:\n GPIO.setup(port[1], GPIO.OUT)\n\n\ndef statusLed(port, status):\n GPIO.output(port, status)\n\n\ndef turnOnAllLeds():\n for led in led1:\n statusLed(led[1], True)\n for led in led2:\n statusLed(led[1], True)\n\n\ndef turnOffAllLeds():\n for led in led1:\n statusLed(led[1], False)\n for led in led2:\n statusLed(led[1], False)\n\n\ndef turnOffOneLed(led):\n for port in led:\n statusLed(port[1], False)\n\n\ndef createNumber(ledNumber, number):\n turnOffOneLed(ledNumber)\n for i in range(10):\n if number == i:\n for letter in numbers[i]:\n for led in ledNumber:\n if led[0] == letter:\n statusLed(led[1], True)\n\n\ndef createNumber2Leds(led1, led2, number):\n if number < 10:\n createNumber(led1, 0)\n createNumber(led2, number)\n else:\n decenas = number / 10\n unidades = number % 10\n createNumber(led1, decenas)\n createNumber(led2, unidades)\n\n\ndef titileoNumber2Leds(led1, led2, number):\n for i in range(3):\n turnOffAllLeds()\n time.sleep(0.25)\n createNumber2Leds(led1, led2, number)\n time.sleep(0.25)\n\n\ndef digiTurno():\n contador = 0\n titileoNumber2Leds(led1, led2, contador)\n while True:\n if GPIO.input(reset):\n contador = 0\n print(\"-\"*20+\" RESET \"+\"-\"*20)\n print(datetime.now())\n titileoNumber2Leds(led1, led2, contador)\n print(\"Numero actual = \"+str(contador))\n time.sleep(.3)\n if GPIO.input(more):\n if contador < 99:\n contador += 1\n else:\n print(datetime.now())\n contador = 0\n print(\"Numero actual = \"+str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(.3)\n if GPIO.input(minus):\n if contador == 0:\n contador = 99\n else:\n contador = contador-1\n print(\"Numero actual = \"+str(contador))\n createNumber2Leds(led1, led2, contador)\n time.sleep(.3)\n\n\ndef main():\n setupLed1()\n setupLed2()\n turnOffAllLeds()\n try:\n print(\"Presione un boton para continuar\")\n digiTurno()\n except (KeyboardInterrupt, SystemExit):\n GPIO.cleanup()\n\n\nif __name__ == \"__main__\":\n main()\n", "step-ids": [ 10, 11, 12, 13, 15 ] }
[ 10, 11, 12, 13, 15 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('app1', '0002_property_details')] operations = [migrations.AlterField(model_name='property_details', name ='flat_type', field=models.CharField(choices=[('1', '1BHK'), ('2', '2BHK'), ('3', '3BHK')], max_length=20)), migrations.AlterField( model_name='property_details', name='possession', field=models. CharField(choices=[('1', 'ready to move'), ('2', 'work on progress' )], max_length=20)), migrations.AlterField(model_name= 'property_details', name='price_range', field=models.CharField( choices=[('1', '$5000'), ('2', '$15,000'), ('3', '$25,000'), ('4', '$40,000'), ('5', '$50,000')], max_length=50))] <|reserved_special_token_1|> from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('app1', '0002_property_details')] operations = [migrations.AlterField(model_name='property_details', name ='flat_type', field=models.CharField(choices=[('1', '1BHK'), ('2', '2BHK'), ('3', '3BHK')], max_length=20)), migrations.AlterField( model_name='property_details', name='possession', field=models. CharField(choices=[('1', 'ready to move'), ('2', 'work on progress' )], max_length=20)), migrations.AlterField(model_name= 'property_details', name='price_range', field=models.CharField( choices=[('1', '$5000'), ('2', '$15,000'), ('3', '$25,000'), ('4', '$40,000'), ('5', '$50,000')], max_length=50))] <|reserved_special_token_1|> # Generated by Django 2.2.3 on 2019-07-11 22:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app1', '0002_property_details'), ] operations = [ migrations.AlterField( model_name='property_details', name='flat_type', field=models.CharField(choices=[('1', '1BHK'), ('2', '2BHK'), ('3', '3BHK')], max_length=20), ), migrations.AlterField( model_name='property_details', name='possession', field=models.CharField(choices=[('1', 'ready to move'), ('2', 'work on progress')], max_length=20), ), migrations.AlterField( model_name='property_details', name='price_range', field=models.CharField(choices=[('1', '$5000'), ('2', '$15,000'), ('3', '$25,000'), ('4', '$40,000'), ('5', '$50,000')], max_length=50), ), ]
flexible
{ "blob_id": "8cdd7646dbf23259e160186f332b5cb02b67291b", "index": 5121, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('app1', '0002_property_details')]\n operations = [migrations.AlterField(model_name='property_details', name\n ='flat_type', field=models.CharField(choices=[('1', '1BHK'), ('2',\n '2BHK'), ('3', '3BHK')], max_length=20)), migrations.AlterField(\n model_name='property_details', name='possession', field=models.\n CharField(choices=[('1', 'ready to move'), ('2', 'work on progress'\n )], max_length=20)), migrations.AlterField(model_name=\n 'property_details', name='price_range', field=models.CharField(\n choices=[('1', '$5000'), ('2', '$15,000'), ('3', '$25,000'), ('4',\n '$40,000'), ('5', '$50,000')], max_length=50))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('app1', '0002_property_details')]\n operations = [migrations.AlterField(model_name='property_details', name\n ='flat_type', field=models.CharField(choices=[('1', '1BHK'), ('2',\n '2BHK'), ('3', '3BHK')], max_length=20)), migrations.AlterField(\n model_name='property_details', name='possession', field=models.\n CharField(choices=[('1', 'ready to move'), ('2', 'work on progress'\n )], max_length=20)), migrations.AlterField(model_name=\n 'property_details', name='price_range', field=models.CharField(\n choices=[('1', '$5000'), ('2', '$15,000'), ('3', '$25,000'), ('4',\n '$40,000'), ('5', '$50,000')], max_length=50))]\n", "step-5": "# Generated by Django 2.2.3 on 2019-07-11 22:04\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app1', '0002_property_details'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='property_details',\n name='flat_type',\n field=models.CharField(choices=[('1', '1BHK'), ('2', '2BHK'), ('3', '3BHK')], max_length=20),\n ),\n migrations.AlterField(\n model_name='property_details',\n name='possession',\n field=models.CharField(choices=[('1', 'ready to move'), ('2', 'work on progress')], max_length=20),\n ),\n migrations.AlterField(\n model_name='property_details',\n name='price_range',\n field=models.CharField(choices=[('1', '$5000'), ('2', '$15,000'), ('3', '$25,000'), ('4', '$40,000'), ('5', '$50,000')], max_length=50),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ModD(Soppa): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ModD(Soppa): needs = ['test_project.modf'] something = 1 <|reserved_special_token_1|> from soppa.contrib import * class ModD(Soppa): needs = ['test_project.modf'] something = 1
flexible
{ "blob_id": "13da16ba89e4743b12d9b8e24929864747f8bbf2", "index": 1308, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ModD(Soppa):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass ModD(Soppa):\n needs = ['test_project.modf']\n something = 1\n", "step-4": "from soppa.contrib import *\n\n\nclass ModD(Soppa):\n needs = ['test_project.modf']\n something = 1\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
''' This program will simulate leveling a DnD character, showing their ending HP, and stats. ''' import argparse import csv import json import re import time from openpyxl import load_workbook from pandas import DataFrame from src import classes, util def import_race_data(file_path): ''' This method imports data from the inputed CSV and returns a dictionary containing all of the data formated by race and subrace Arguments: :param import_data: (str) The filepath to the data Returns: dict: The dictionary of all of the data ''' retval = {} # Open csv file and read in all data with open(file_path) as csv_file: reader = csv.DictReader(csv_file) for row in reader: race = row['Race'] subrace = row['Subrace'] if(subrace): if(race in retval): if('Subraces' not in retval[race]): retval[race]['Subraces'] = {} retval[race]['Subraces'][subrace] = row else: retval[race] = {'Subraces':{}} retval[race]['Subraces'][subrace] = row else: retval[race] = row return retval def update_mode(args): ''' This method is the main method for running this program in Update mode. Update mode takes in a specifically formated XLSX file and outputs a JSON file containing all of the data for races and subraces needed by the program in run mode Arguments: :param args: (dict) A dictionary containing the needed arguments Returns: bool: Whether or not the update completed successfully or not ''' # Lets first open the workbook try: workbook = load_workbook(args['xlsx_file']) except: return False # Now turn the Race sheet into a dataframe df = DataFrame() for name in workbook.sheetnames: if('Race' in name): df = DataFrame(workbook[name].values) # If we find nothing, return failure if(df.empty): return False # Lets remove the title row df.drop(0, axis=0, inplace=True) df.reset_index(inplace=True, drop=True) # Now lets get the headers, find the last column, and remove this row end_col = (df.iloc[0, :].values == None).argmax() df.drop(df.iloc[:, end_col:], axis=1, inplace=True) df.columns = list(df.iloc[0, :]) df.drop(0, axis=0, inplace=True) df.reset_index(inplace=True, drop=True) # Now lets resize this dataframe to only contain the information we want # We first scroll down the rows to find the first blank cell, that is the # end of the rows end_row = (df.iloc[:, 0].values == None).argmax() df.drop(df[end_row:].index, axis=0, inplace=True) # Now let's get the race names and source names hyperlink_re = re.compile(r'(?<=,")(.+)(?=")') df['Race'] = df['Race'].apply( lambda x: x if hyperlink_re.search(x) is None else hyperlink_re.search(x).group(1) ) df['Source'] = df['Source'].apply( lambda x: x if hyperlink_re.search(x) is None else hyperlink_re.search(x).group(1) ) # Now make sure the stat fields are correct integers # Loop through dataframe so we can assemble the json in the format we want data = {} asi_re = re.compile(r'ASI: ([+-]\d) \(x(\d)\)(?:\s{1}\((.+)\))?') for index, row in df.iterrows(): # First lets index this record into the correct spot in the array row = dict(row) race = row['Race'] subrace = row['Subrace'] if(subrace): if(race in data): if('Subraces' not in data[race]): data[race]['Subraces'] = {} data[race]['Subraces'][subrace] = row else: data[race] = {'Subraces':{}} data[race]['Subraces'][subrace] = row else: data[race] = row # Now that we have added this row, check if there are any special ASI rules to note if(row['Additional'] is not None): matches = asi_re.search(row['Additional']) if(matches): # We found something asi = {'size': matches.group(1), 'number': matches.group(2)} # Check if we have restrictions if(matches.group(3)): # We either can put the point into a number of options, or not # into one stat if('-' in matches.group(3)): # We cannot use this stat asi['not_allowed'] = matches.group(3).split('-')[1] if('|' in matches.group(3)): # We can only use one or the other asi['allowed'] = [x.capitalize() for x in matches.group(3).split(' | ')] # Now add this to the row of data if(subrace): data[race]['Subraces'][subrace]['ASI'] = asi else: data[race]['ASI'] = asi # Done! Let's dump this file with open('race_data.json', 'w') as fp: json.dump(data, fp, indent=2) return True def run_mode(args): ''' This method is the main method for running this program in Run mode. This mode goes through the character simulation Arguments: :param args: (dict) A dictionary containing the needed arguments ''' char = classes.Character( "Human", None, ['Str','Dex','Con','Int','Wis','Cha'], classes.StatSelection.ROLL_4D6_DROP_ONE, classes.HPSelection.ROLL_HP, classes.ASISelection.STRICT_FOCUS ) print(char.id) print(char.stats) char = classes.Character( "Human", "Variant", ['Str','Dex','Con','Int','Wis','Cha'], classes.StatSelection.ROLL_3D6, classes.HPSelection.ROLL_HP, classes.ASISelection.FOCUS_ODD_TO_EVEN ) print(char.id) print(char.stats) if __name__ == "__main__": # Setup argument parsers and parse arguments main_parser = argparse.ArgumentParser(description='Character Simulator') subparsers = main_parser.add_subparsers(help='Mode Help') update_parser = subparsers.add_parser('update', help='Update Help') update_parser.add_argument('xlsx_file', type=str, help='Path to the .xlsx race file') run_parser = subparsers.add_parser('run', help='Run Help') args = vars(main_parser.parse_args()) # If we are in update mode, update the json file if('xlsx_file' in args): update_mode(args) else: run_mode(args)
normal
{ "blob_id": "022c8d6c31ad5494b03bfe93d17396eac25b011e", "index": 8706, "step-1": "<mask token>\n\n\ndef update_mode(args):\n \"\"\"\n This method is the main method for running this program in Update mode.\n\n Update mode takes in a specifically formated XLSX file and outputs a JSON\n file containing all of the data for races and subraces needed by the\n program in run mode\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n\n Returns:\n bool: Whether or not the update completed successfully or not\n \"\"\"\n try:\n workbook = load_workbook(args['xlsx_file'])\n except:\n return False\n df = DataFrame()\n for name in workbook.sheetnames:\n if 'Race' in name:\n df = DataFrame(workbook[name].values)\n if df.empty:\n return False\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n end_col = (df.iloc[0, :].values == None).argmax()\n df.drop(df.iloc[:, end_col:], axis=1, inplace=True)\n df.columns = list(df.iloc[0, :])\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n end_row = (df.iloc[:, 0].values == None).argmax()\n df.drop(df[end_row:].index, axis=0, inplace=True)\n hyperlink_re = re.compile('(?<=,\")(.+)(?=\")')\n df['Race'] = df['Race'].apply(lambda x: x if hyperlink_re.search(x) is\n None else hyperlink_re.search(x).group(1))\n df['Source'] = df['Source'].apply(lambda x: x if hyperlink_re.search(x) is\n None else hyperlink_re.search(x).group(1))\n data = {}\n asi_re = re.compile('ASI: ([+-]\\\\d) \\\\(x(\\\\d)\\\\)(?:\\\\s{1}\\\\((.+)\\\\))?')\n for index, row in df.iterrows():\n row = dict(row)\n race = row['Race']\n subrace = row['Subrace']\n if subrace:\n if race in data:\n if 'Subraces' not in data[race]:\n data[race]['Subraces'] = {}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = {'Subraces': {}}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = row\n if row['Additional'] is not None:\n matches = asi_re.search(row['Additional'])\n if matches:\n asi = {'size': matches.group(1), 'number': matches.group(2)}\n if matches.group(3):\n if '-' in matches.group(3):\n asi['not_allowed'] = matches.group(3).split('-')[1]\n if '|' in matches.group(3):\n asi['allowed'] = [x.capitalize() for x in matches.\n group(3).split(' | ')]\n if subrace:\n data[race]['Subraces'][subrace]['ASI'] = asi\n else:\n data[race]['ASI'] = asi\n with open('race_data.json', 'w') as fp:\n json.dump(data, fp, indent=2)\n return True\n\n\ndef run_mode(args):\n \"\"\"\n This method is the main method for running this program in Run mode.\n\n This mode goes through the character simulation\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n \"\"\"\n char = classes.Character('Human', None, ['Str', 'Dex', 'Con', 'Int',\n 'Wis', 'Cha'], classes.StatSelection.ROLL_4D6_DROP_ONE, classes.\n HPSelection.ROLL_HP, classes.ASISelection.STRICT_FOCUS)\n print(char.id)\n print(char.stats)\n char = classes.Character('Human', 'Variant', ['Str', 'Dex', 'Con',\n 'Int', 'Wis', 'Cha'], classes.StatSelection.ROLL_3D6, classes.\n HPSelection.ROLL_HP, classes.ASISelection.FOCUS_ODD_TO_EVEN)\n print(char.id)\n print(char.stats)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef import_race_data(file_path):\n \"\"\"\n This method imports data from the inputed CSV and returns a dictionary containing\n all of the data formated by race and subrace\n\n Arguments:\n :param import_data: (str) The filepath to the data\n\n Returns:\n dict: The dictionary of all of the data\n \"\"\"\n retval = {}\n with open(file_path) as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n race = row['Race']\n subrace = row['Subrace']\n if subrace:\n if race in retval:\n if 'Subraces' not in retval[race]:\n retval[race]['Subraces'] = {}\n retval[race]['Subraces'][subrace] = row\n else:\n retval[race] = {'Subraces': {}}\n retval[race]['Subraces'][subrace] = row\n else:\n retval[race] = row\n return retval\n\n\ndef update_mode(args):\n \"\"\"\n This method is the main method for running this program in Update mode.\n\n Update mode takes in a specifically formated XLSX file and outputs a JSON\n file containing all of the data for races and subraces needed by the\n program in run mode\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n\n Returns:\n bool: Whether or not the update completed successfully or not\n \"\"\"\n try:\n workbook = load_workbook(args['xlsx_file'])\n except:\n return False\n df = DataFrame()\n for name in workbook.sheetnames:\n if 'Race' in name:\n df = DataFrame(workbook[name].values)\n if df.empty:\n return False\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n end_col = (df.iloc[0, :].values == None).argmax()\n df.drop(df.iloc[:, end_col:], axis=1, inplace=True)\n df.columns = list(df.iloc[0, :])\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n end_row = (df.iloc[:, 0].values == None).argmax()\n df.drop(df[end_row:].index, axis=0, inplace=True)\n hyperlink_re = re.compile('(?<=,\")(.+)(?=\")')\n df['Race'] = df['Race'].apply(lambda x: x if hyperlink_re.search(x) is\n None else hyperlink_re.search(x).group(1))\n df['Source'] = df['Source'].apply(lambda x: x if hyperlink_re.search(x) is\n None else hyperlink_re.search(x).group(1))\n data = {}\n asi_re = re.compile('ASI: ([+-]\\\\d) \\\\(x(\\\\d)\\\\)(?:\\\\s{1}\\\\((.+)\\\\))?')\n for index, row in df.iterrows():\n row = dict(row)\n race = row['Race']\n subrace = row['Subrace']\n if subrace:\n if race in data:\n if 'Subraces' not in data[race]:\n data[race]['Subraces'] = {}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = {'Subraces': {}}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = row\n if row['Additional'] is not None:\n matches = asi_re.search(row['Additional'])\n if matches:\n asi = {'size': matches.group(1), 'number': matches.group(2)}\n if matches.group(3):\n if '-' in matches.group(3):\n asi['not_allowed'] = matches.group(3).split('-')[1]\n if '|' in matches.group(3):\n asi['allowed'] = [x.capitalize() for x in matches.\n group(3).split(' | ')]\n if subrace:\n data[race]['Subraces'][subrace]['ASI'] = asi\n else:\n data[race]['ASI'] = asi\n with open('race_data.json', 'w') as fp:\n json.dump(data, fp, indent=2)\n return True\n\n\ndef run_mode(args):\n \"\"\"\n This method is the main method for running this program in Run mode.\n\n This mode goes through the character simulation\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n \"\"\"\n char = classes.Character('Human', None, ['Str', 'Dex', 'Con', 'Int',\n 'Wis', 'Cha'], classes.StatSelection.ROLL_4D6_DROP_ONE, classes.\n HPSelection.ROLL_HP, classes.ASISelection.STRICT_FOCUS)\n print(char.id)\n print(char.stats)\n char = classes.Character('Human', 'Variant', ['Str', 'Dex', 'Con',\n 'Int', 'Wis', 'Cha'], classes.StatSelection.ROLL_3D6, classes.\n HPSelection.ROLL_HP, classes.ASISelection.FOCUS_ODD_TO_EVEN)\n print(char.id)\n print(char.stats)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef import_race_data(file_path):\n \"\"\"\n This method imports data from the inputed CSV and returns a dictionary containing\n all of the data formated by race and subrace\n\n Arguments:\n :param import_data: (str) The filepath to the data\n\n Returns:\n dict: The dictionary of all of the data\n \"\"\"\n retval = {}\n with open(file_path) as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n race = row['Race']\n subrace = row['Subrace']\n if subrace:\n if race in retval:\n if 'Subraces' not in retval[race]:\n retval[race]['Subraces'] = {}\n retval[race]['Subraces'][subrace] = row\n else:\n retval[race] = {'Subraces': {}}\n retval[race]['Subraces'][subrace] = row\n else:\n retval[race] = row\n return retval\n\n\ndef update_mode(args):\n \"\"\"\n This method is the main method for running this program in Update mode.\n\n Update mode takes in a specifically formated XLSX file and outputs a JSON\n file containing all of the data for races and subraces needed by the\n program in run mode\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n\n Returns:\n bool: Whether or not the update completed successfully or not\n \"\"\"\n try:\n workbook = load_workbook(args['xlsx_file'])\n except:\n return False\n df = DataFrame()\n for name in workbook.sheetnames:\n if 'Race' in name:\n df = DataFrame(workbook[name].values)\n if df.empty:\n return False\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n end_col = (df.iloc[0, :].values == None).argmax()\n df.drop(df.iloc[:, end_col:], axis=1, inplace=True)\n df.columns = list(df.iloc[0, :])\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n end_row = (df.iloc[:, 0].values == None).argmax()\n df.drop(df[end_row:].index, axis=0, inplace=True)\n hyperlink_re = re.compile('(?<=,\")(.+)(?=\")')\n df['Race'] = df['Race'].apply(lambda x: x if hyperlink_re.search(x) is\n None else hyperlink_re.search(x).group(1))\n df['Source'] = df['Source'].apply(lambda x: x if hyperlink_re.search(x) is\n None else hyperlink_re.search(x).group(1))\n data = {}\n asi_re = re.compile('ASI: ([+-]\\\\d) \\\\(x(\\\\d)\\\\)(?:\\\\s{1}\\\\((.+)\\\\))?')\n for index, row in df.iterrows():\n row = dict(row)\n race = row['Race']\n subrace = row['Subrace']\n if subrace:\n if race in data:\n if 'Subraces' not in data[race]:\n data[race]['Subraces'] = {}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = {'Subraces': {}}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = row\n if row['Additional'] is not None:\n matches = asi_re.search(row['Additional'])\n if matches:\n asi = {'size': matches.group(1), 'number': matches.group(2)}\n if matches.group(3):\n if '-' in matches.group(3):\n asi['not_allowed'] = matches.group(3).split('-')[1]\n if '|' in matches.group(3):\n asi['allowed'] = [x.capitalize() for x in matches.\n group(3).split(' | ')]\n if subrace:\n data[race]['Subraces'][subrace]['ASI'] = asi\n else:\n data[race]['ASI'] = asi\n with open('race_data.json', 'w') as fp:\n json.dump(data, fp, indent=2)\n return True\n\n\ndef run_mode(args):\n \"\"\"\n This method is the main method for running this program in Run mode.\n\n This mode goes through the character simulation\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n \"\"\"\n char = classes.Character('Human', None, ['Str', 'Dex', 'Con', 'Int',\n 'Wis', 'Cha'], classes.StatSelection.ROLL_4D6_DROP_ONE, classes.\n HPSelection.ROLL_HP, classes.ASISelection.STRICT_FOCUS)\n print(char.id)\n print(char.stats)\n char = classes.Character('Human', 'Variant', ['Str', 'Dex', 'Con',\n 'Int', 'Wis', 'Cha'], classes.StatSelection.ROLL_3D6, classes.\n HPSelection.ROLL_HP, classes.ASISelection.FOCUS_ODD_TO_EVEN)\n print(char.id)\n print(char.stats)\n\n\nif __name__ == '__main__':\n main_parser = argparse.ArgumentParser(description='Character Simulator')\n subparsers = main_parser.add_subparsers(help='Mode Help')\n update_parser = subparsers.add_parser('update', help='Update Help')\n update_parser.add_argument('xlsx_file', type=str, help=\n 'Path to the .xlsx race file')\n run_parser = subparsers.add_parser('run', help='Run Help')\n args = vars(main_parser.parse_args())\n if 'xlsx_file' in args:\n update_mode(args)\n else:\n run_mode(args)\n", "step-4": "<mask token>\nimport argparse\nimport csv\nimport json\nimport re\nimport time\nfrom openpyxl import load_workbook\nfrom pandas import DataFrame\nfrom src import classes, util\n\n\ndef import_race_data(file_path):\n \"\"\"\n This method imports data from the inputed CSV and returns a dictionary containing\n all of the data formated by race and subrace\n\n Arguments:\n :param import_data: (str) The filepath to the data\n\n Returns:\n dict: The dictionary of all of the data\n \"\"\"\n retval = {}\n with open(file_path) as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n race = row['Race']\n subrace = row['Subrace']\n if subrace:\n if race in retval:\n if 'Subraces' not in retval[race]:\n retval[race]['Subraces'] = {}\n retval[race]['Subraces'][subrace] = row\n else:\n retval[race] = {'Subraces': {}}\n retval[race]['Subraces'][subrace] = row\n else:\n retval[race] = row\n return retval\n\n\ndef update_mode(args):\n \"\"\"\n This method is the main method for running this program in Update mode.\n\n Update mode takes in a specifically formated XLSX file and outputs a JSON\n file containing all of the data for races and subraces needed by the\n program in run mode\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n\n Returns:\n bool: Whether or not the update completed successfully or not\n \"\"\"\n try:\n workbook = load_workbook(args['xlsx_file'])\n except:\n return False\n df = DataFrame()\n for name in workbook.sheetnames:\n if 'Race' in name:\n df = DataFrame(workbook[name].values)\n if df.empty:\n return False\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n end_col = (df.iloc[0, :].values == None).argmax()\n df.drop(df.iloc[:, end_col:], axis=1, inplace=True)\n df.columns = list(df.iloc[0, :])\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n end_row = (df.iloc[:, 0].values == None).argmax()\n df.drop(df[end_row:].index, axis=0, inplace=True)\n hyperlink_re = re.compile('(?<=,\")(.+)(?=\")')\n df['Race'] = df['Race'].apply(lambda x: x if hyperlink_re.search(x) is\n None else hyperlink_re.search(x).group(1))\n df['Source'] = df['Source'].apply(lambda x: x if hyperlink_re.search(x) is\n None else hyperlink_re.search(x).group(1))\n data = {}\n asi_re = re.compile('ASI: ([+-]\\\\d) \\\\(x(\\\\d)\\\\)(?:\\\\s{1}\\\\((.+)\\\\))?')\n for index, row in df.iterrows():\n row = dict(row)\n race = row['Race']\n subrace = row['Subrace']\n if subrace:\n if race in data:\n if 'Subraces' not in data[race]:\n data[race]['Subraces'] = {}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = {'Subraces': {}}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = row\n if row['Additional'] is not None:\n matches = asi_re.search(row['Additional'])\n if matches:\n asi = {'size': matches.group(1), 'number': matches.group(2)}\n if matches.group(3):\n if '-' in matches.group(3):\n asi['not_allowed'] = matches.group(3).split('-')[1]\n if '|' in matches.group(3):\n asi['allowed'] = [x.capitalize() for x in matches.\n group(3).split(' | ')]\n if subrace:\n data[race]['Subraces'][subrace]['ASI'] = asi\n else:\n data[race]['ASI'] = asi\n with open('race_data.json', 'w') as fp:\n json.dump(data, fp, indent=2)\n return True\n\n\ndef run_mode(args):\n \"\"\"\n This method is the main method for running this program in Run mode.\n\n This mode goes through the character simulation\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n \"\"\"\n char = classes.Character('Human', None, ['Str', 'Dex', 'Con', 'Int',\n 'Wis', 'Cha'], classes.StatSelection.ROLL_4D6_DROP_ONE, classes.\n HPSelection.ROLL_HP, classes.ASISelection.STRICT_FOCUS)\n print(char.id)\n print(char.stats)\n char = classes.Character('Human', 'Variant', ['Str', 'Dex', 'Con',\n 'Int', 'Wis', 'Cha'], classes.StatSelection.ROLL_3D6, classes.\n HPSelection.ROLL_HP, classes.ASISelection.FOCUS_ODD_TO_EVEN)\n print(char.id)\n print(char.stats)\n\n\nif __name__ == '__main__':\n main_parser = argparse.ArgumentParser(description='Character Simulator')\n subparsers = main_parser.add_subparsers(help='Mode Help')\n update_parser = subparsers.add_parser('update', help='Update Help')\n update_parser.add_argument('xlsx_file', type=str, help=\n 'Path to the .xlsx race file')\n run_parser = subparsers.add_parser('run', help='Run Help')\n args = vars(main_parser.parse_args())\n if 'xlsx_file' in args:\n update_mode(args)\n else:\n run_mode(args)\n", "step-5": "'''\nThis program will simulate leveling a DnD character, showing their ending HP, and stats.\n'''\nimport argparse\nimport csv\nimport json\nimport re\nimport time\nfrom openpyxl import load_workbook\nfrom pandas import DataFrame\nfrom src import classes, util\n\n\ndef import_race_data(file_path):\n '''\n This method imports data from the inputed CSV and returns a dictionary containing\n all of the data formated by race and subrace\n\n Arguments:\n :param import_data: (str) The filepath to the data\n\n Returns:\n dict: The dictionary of all of the data\n '''\n retval = {}\n\n # Open csv file and read in all data\n with open(file_path) as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n race = row['Race']\n subrace = row['Subrace']\n\n if(subrace):\n if(race in retval):\n if('Subraces' not in retval[race]):\n retval[race]['Subraces'] = {}\n retval[race]['Subraces'][subrace] = row\n else:\n retval[race] = {'Subraces':{}}\n retval[race]['Subraces'][subrace] = row\n else:\n retval[race] = row\n\n return retval\n\ndef update_mode(args):\n '''\n This method is the main method for running this program in Update mode.\n\n Update mode takes in a specifically formated XLSX file and outputs a JSON\n file containing all of the data for races and subraces needed by the\n program in run mode\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n\n Returns:\n bool: Whether or not the update completed successfully or not\n '''\n # Lets first open the workbook\n try:\n workbook = load_workbook(args['xlsx_file'])\n except:\n return False\n\n # Now turn the Race sheet into a dataframe\n df = DataFrame()\n for name in workbook.sheetnames:\n if('Race' in name):\n df = DataFrame(workbook[name].values)\n\n # If we find nothing, return failure\n if(df.empty):\n return False\n\n # Lets remove the title row\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n\n # Now lets get the headers, find the last column, and remove this row\n end_col = (df.iloc[0, :].values == None).argmax()\n df.drop(df.iloc[:, end_col:], axis=1, inplace=True)\n df.columns = list(df.iloc[0, :])\n df.drop(0, axis=0, inplace=True)\n df.reset_index(inplace=True, drop=True)\n\n # Now lets resize this dataframe to only contain the information we want\n # We first scroll down the rows to find the first blank cell, that is the\n # end of the rows\n end_row = (df.iloc[:, 0].values == None).argmax()\n df.drop(df[end_row:].index, axis=0, inplace=True)\n\n # Now let's get the race names and source names\n hyperlink_re = re.compile(r'(?<=,\")(.+)(?=\")')\n df['Race'] = df['Race'].apply(\n lambda x: x if hyperlink_re.search(x) is None else hyperlink_re.search(x).group(1)\n )\n df['Source'] = df['Source'].apply(\n lambda x: x if hyperlink_re.search(x) is None else hyperlink_re.search(x).group(1)\n )\n\n # Now make sure the stat fields are correct integers\n\n # Loop through dataframe so we can assemble the json in the format we want\n data = {}\n asi_re = re.compile(r'ASI: ([+-]\\d) \\(x(\\d)\\)(?:\\s{1}\\((.+)\\))?')\n for index, row in df.iterrows():\n # First lets index this record into the correct spot in the array\n row = dict(row)\n race = row['Race']\n subrace = row['Subrace']\n\n if(subrace):\n if(race in data):\n if('Subraces' not in data[race]):\n data[race]['Subraces'] = {}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = {'Subraces':{}}\n data[race]['Subraces'][subrace] = row\n else:\n data[race] = row\n\n # Now that we have added this row, check if there are any special ASI rules to note\n if(row['Additional'] is not None):\n matches = asi_re.search(row['Additional'])\n if(matches):\n # We found something\n asi = {'size': matches.group(1), 'number': matches.group(2)}\n\n # Check if we have restrictions\n if(matches.group(3)):\n # We either can put the point into a number of options, or not\n # into one stat\n if('-' in matches.group(3)):\n # We cannot use this stat\n asi['not_allowed'] = matches.group(3).split('-')[1]\n\n if('|' in matches.group(3)):\n # We can only use one or the other\n asi['allowed'] = [x.capitalize() for x in matches.group(3).split(' | ')]\n \n # Now add this to the row of data\n if(subrace):\n data[race]['Subraces'][subrace]['ASI'] = asi\n else:\n data[race]['ASI'] = asi\n\n # Done! Let's dump this file\n with open('race_data.json', 'w') as fp:\n json.dump(data, fp, indent=2)\n\n return True\n\ndef run_mode(args):\n '''\n This method is the main method for running this program in Run mode.\n\n This mode goes through the character simulation\n\n Arguments:\n :param args: (dict) A dictionary containing the needed arguments\n '''\n char = classes.Character(\n \"Human\", None, ['Str','Dex','Con','Int','Wis','Cha'], \n classes.StatSelection.ROLL_4D6_DROP_ONE, classes.HPSelection.ROLL_HP,\n classes.ASISelection.STRICT_FOCUS\n )\n print(char.id)\n print(char.stats)\n char = classes.Character(\n \"Human\", \"Variant\", ['Str','Dex','Con','Int','Wis','Cha'], \n classes.StatSelection.ROLL_3D6, classes.HPSelection.ROLL_HP,\n classes.ASISelection.FOCUS_ODD_TO_EVEN\n )\n print(char.id)\n print(char.stats)\n\n\nif __name__ == \"__main__\":\n # Setup argument parsers and parse arguments\n main_parser = argparse.ArgumentParser(description='Character Simulator')\n subparsers = main_parser.add_subparsers(help='Mode Help')\n\n update_parser = subparsers.add_parser('update', help='Update Help')\n update_parser.add_argument('xlsx_file', type=str, help='Path to the .xlsx race file')\n\n run_parser = subparsers.add_parser('run', help='Run Help')\n\n args = vars(main_parser.parse_args())\n\n # If we are in update mode, update the json file\n if('xlsx_file' in args):\n update_mode(args)\n else:\n run_mode(args)", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Messages(SQLMixin, SQLBase): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Messages(SQLMixin, SQLBase): __tablename__ = 'Messages' title = Column(Unicode(50), nullable=False) content = Column(UnicodeText, nullable=False) sender_id = Column(Integer, nullable=False) receiver_id = Column(Integer, nullable=False) <|reserved_special_token_1|> import time from sqlalchemy import Column, Unicode, UnicodeText, Integer from models.base_model import SQLMixin, db, SQLBase class Messages(SQLMixin, SQLBase): __tablename__ = 'Messages' title = Column(Unicode(50), nullable=False) content = Column(UnicodeText, nullable=False) sender_id = Column(Integer, nullable=False) receiver_id = Column(Integer, nullable=False)
flexible
{ "blob_id": "6fbf64e2dc2836a54e54ee009be1d0d8d7c7037a", "index": 1688, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Messages(SQLMixin, SQLBase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Messages(SQLMixin, SQLBase):\n __tablename__ = 'Messages'\n title = Column(Unicode(50), nullable=False)\n content = Column(UnicodeText, nullable=False)\n sender_id = Column(Integer, nullable=False)\n receiver_id = Column(Integer, nullable=False)\n", "step-4": "import time\nfrom sqlalchemy import Column, Unicode, UnicodeText, Integer\nfrom models.base_model import SQLMixin, db, SQLBase\n\n\nclass Messages(SQLMixin, SQLBase):\n __tablename__ = 'Messages'\n title = Column(Unicode(50), nullable=False)\n content = Column(UnicodeText, nullable=False)\n sender_id = Column(Integer, nullable=False)\n receiver_id = Column(Integer, nullable=False)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import re, os, nltk, pymorphy2, sys from suffix_trees.STree import STree def make_rules(folder): rules_dictionary = {} try: path = os.path.join(os.getcwd(), 'rules', 'data', folder) files = os.listdir(path) except: path = os.path.join(os.getcwd(), 'data', folder) files = os.listdir(path) short_files_rule = re.compile('.txt') for file in files: if short_files_rule.search(file) != None: class_name = re.sub('_', ' ', re.sub('\.txt', '', file)) current_file = open(os.path.join(path, file), 'r', encoding='utf-8').read() affixes = current_file.split(', ') rules_dictionary[class_name] = affixes return(rules_dictionary) def find_affixes(rules_noun, lemma, word_possible_stress): for stress_type, affixes in rules_noun.items(): for affix in affixes: affix_type = '' if re.search('^[а-яё]+\-$', affix) != None: regexp = '^'+affix[:-1] affix_type = 'preffix' elif re.search('^\-[а-яё]+$', affix) != None: regexp = affix[1:]+'$' affix_type = 'suffix' elif re.search('^[а-яё]+\-\.\.\.\-[а-яё]+$', affix) != None: regexp = '^'+re.sub('\-\.\.\.\-', '.+', affix)+'$' affix_type = 'combination' if re.search(regexp, lemma) != None: if stress_type in word_possible_stress: word_possible_stress[stress_type].append((affix, affix_type)) else: word_possible_stress[stress_type] = [(affix, affix_type)] return(word_possible_stress) def find_biggest_affixes(word_possible_stress): biggest_len_suffix, biggest_len_prefix = 0, 0 biggest_suffix, biggest_prefix = '', '' if 'all suffixes' in word_possible_stress: for suffix in word_possible_stress['all suffixes']: if len(suffix[0]) > biggest_len_suffix: biggest_suffix = suffix[0] biggest_len_suffix = len(suffix[0]) del word_possible_stress['all suffixes'] if 'all prefixes' in word_possible_stress: for prefix in word_possible_stress['all prefixes']: if len(prefix[0]) > biggest_len_prefix: biggest_prefix = prefix[0] biggest_len_prefix = len(prefix[0]) del word_possible_stress['all prefixes'] return(biggest_prefix, biggest_suffix, word_possible_stress) def find_possible_types(word_possible_stress, biggest_suffix, biggest_prefix): possible_types = [] for stress_type, affixes in word_possible_stress.items(): for affix in affixes: if affix[1] == 'suffix': if affix[0] == biggest_suffix: possible_types.append(stress_type) elif affix[1] == 'prefix': if affix[0] == biggest_prefix: possible_types.append(stress_type) elif affix[1] == 'combination': possible_types = [] pair = affix[0].split('...') if pair[0] == biggest_prefix and pair[1] == biggest_suffix: possible_types.append(stress_type) return(possible_types) def make_stressed_word(possible_types, token, lemma, biggest_suffix, original_token): if possible_types[0] == 'prefix' or possible_types[0] == 'first vowel': stressed_word = re.sub('^([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', '\g<1>\'', token) #print(token, stressed_word, lemma, biggest_prefix, biggest_suffix) elif possible_types[0] == 'suffix' or possible_types[0] == 'suffix 1': stem = STree([token, lemma]).lcs() stem_cutted = re.sub(re.sub('-', '', biggest_suffix)+'$', '', stem) for num in range(1,5): if stem == stem_cutted: stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num]+'$', '', stem) stressed_word = re.sub('^('+stem_cutted+'[^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', '\g<1>\'', token) elif possible_types[0] == 'suffix 2': stem = STree([token, lemma]).lcs() stem_cutted = re.sub(re.sub('-', '', biggest_suffix)+'$', '', stem) for num in range(1,5): if stem == stem_cutted: stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num]+'$', '', stem) stressed_word = re.sub('^('+stem_cutted+'([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){2})', '\g<1>\'', token) elif possible_types[0] == 'suffix 3': stem = STree([token, lemma]).lcs() stem_cutted = re.sub(re.sub('-', '', biggest_suffix)+'$', '', stem) for num in range(1,5): if stem == stem_cutted: stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num]+'$', '', stem) stressed_word = re.sub('^('+stem_cutted+'([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){3})', '\g<1>\'', token) elif possible_types[0] == 'presuffix': stem = STree([token, lemma]).lcs() stem_cutted = re.sub(re.sub('-', '', biggest_suffix)+'$', '', stem) for num in range(1,5): if stem == stem_cutted: stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num]+'$', '', stem) suffixes = re.sub(stem_cutted, '', stem) stressed_word = re.sub('([уеыаоэяиюёУЕЫАОЭЯИЮЁ])([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*'+suffixes+'.{,5})$', '\g<1>\'\g<2>', token) elif possible_types[0] == 'type B': stressed_word = re.sub('^(.+[уеыаоэяиюё])([^уеыаоэяиюё]*)$', '\g<1>\'\g<2>', token) try: parts = stressed_word.split('\'') stressed_word = original_token[:len(parts[0])]+'\''+original_token[len(parts[0]):] except: stressed_word = original_token return(stressed_word) def process_stresses(part_of_speech, rules, pos, lemma, token, original_token, word_possible_stress, current_file): stressed_word, biggest_suffix, possible_types = '', '', [''] if part_of_speech in pos: word_possible_stress = find_affixes(rules, lemma, word_possible_stress) if word_possible_stress != {} and list(word_possible_stress.keys()) != ['all prefixes', 'all suffixes'] and \ list(word_possible_stress.keys()) != ['all suffixes'] and list(word_possible_stress.keys()) != ['all prefixes']: biggest_prefix, biggest_suffix, word_possible_stress = find_biggest_affixes(word_possible_stress) possible_types = find_possible_types(word_possible_stress, biggest_suffix, biggest_prefix) if len(possible_types) == 1: stressed_word = make_stressed_word(possible_types, token, lemma, biggest_suffix, original_token) current_file = re.sub(original_token, stressed_word, current_file) ## if pos == 'VERB': ## print(pos, lemma, token, stressed_word, biggest_suffix, possible_types[0]) if possible_types == []: possible_types = [''] return(current_file, stressed_word, biggest_suffix, possible_types[0]) def initialize(current_file): morph = pymorphy2.MorphAnalyzer() rules_noun = make_rules('NOUN') rules_adj = make_rules('ADJ') rules_verb = make_rules('VERB') all_tokens = nltk.word_tokenize(current_file) stressed_words, biggest_suffixes, stress_types, poses = [], [], [], [] for token in all_tokens: stressed_word, biggest_suffix, stress_type = token, '', '' original_token = token token = token.lower() word_possible_stress = {} if re.search('^[А-ЯЁа-яё\-]+$', token) != None and token != '-': token = re.sub('^-', '', token) pos = morph.parse(token)[0].tag.POS #pos = nltk.pos_tag(token, lang='rus') lemma = morph.parse(token)[0].normal_form if pos != None: current_file, stressed_word, biggest_suffix, stress_type = process_stresses('NOUN', rules_noun, pos, lemma, token, original_token, word_possible_stress, current_file) if biggest_suffix == '': current_file,stressed_word, biggest_suffix, stress_type = process_stresses('ADJF', rules_adj, pos, lemma, token, original_token, word_possible_stress, current_file) if biggest_suffix == '': current_file, stressed_word, biggest_suffix, stress_type = process_stresses('VERB', rules_verb, pos, lemma, token, original_token, word_possible_stress, current_file) if stressed_word == '': stressed_word = original_token stressed_words.append(stressed_word) biggest_suffixes.append(biggest_suffix) stress_types.append(stress_type) poses.append(pos) return(current_file, stressed_words, biggest_suffixes, stress_types, poses)
normal
{ "blob_id": "1bf9785135f6105301d02602e54cbbcbdd249144", "index": 9283, "step-1": "<mask token>\n\n\ndef make_rules(folder):\n rules_dictionary = {}\n try:\n path = os.path.join(os.getcwd(), 'rules', 'data', folder)\n files = os.listdir(path)\n except:\n path = os.path.join(os.getcwd(), 'data', folder)\n files = os.listdir(path)\n short_files_rule = re.compile('.txt')\n for file in files:\n if short_files_rule.search(file) != None:\n class_name = re.sub('_', ' ', re.sub('\\\\.txt', '', file))\n current_file = open(os.path.join(path, file), 'r', encoding='utf-8'\n ).read()\n affixes = current_file.split(', ')\n rules_dictionary[class_name] = affixes\n return rules_dictionary\n\n\ndef find_affixes(rules_noun, lemma, word_possible_stress):\n for stress_type, affixes in rules_noun.items():\n for affix in affixes:\n affix_type = ''\n if re.search('^[а-яё]+\\\\-$', affix) != None:\n regexp = '^' + affix[:-1]\n affix_type = 'preffix'\n elif re.search('^\\\\-[а-яё]+$', affix) != None:\n regexp = affix[1:] + '$'\n affix_type = 'suffix'\n elif re.search('^[а-яё]+\\\\-\\\\.\\\\.\\\\.\\\\-[а-яё]+$', affix) != None:\n regexp = '^' + re.sub('\\\\-\\\\.\\\\.\\\\.\\\\-', '.+', affix) + '$'\n affix_type = 'combination'\n if re.search(regexp, lemma) != None:\n if stress_type in word_possible_stress:\n word_possible_stress[stress_type].append((affix,\n affix_type))\n else:\n word_possible_stress[stress_type] = [(affix, affix_type)]\n return word_possible_stress\n\n\n<mask token>\n\n\ndef find_possible_types(word_possible_stress, biggest_suffix, biggest_prefix):\n possible_types = []\n for stress_type, affixes in word_possible_stress.items():\n for affix in affixes:\n if affix[1] == 'suffix':\n if affix[0] == biggest_suffix:\n possible_types.append(stress_type)\n elif affix[1] == 'prefix':\n if affix[0] == biggest_prefix:\n possible_types.append(stress_type)\n elif affix[1] == 'combination':\n possible_types = []\n pair = affix[0].split('...')\n if pair[0] == biggest_prefix and pair[1] == biggest_suffix:\n possible_types.append(stress_type)\n return possible_types\n\n\ndef make_stressed_word(possible_types, token, lemma, biggest_suffix,\n original_token):\n if possible_types[0] == 'prefix' or possible_types[0] == 'first vowel':\n stressed_word = re.sub(\n '^([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', \"\\\\g<1>'\",\n token)\n elif possible_types[0] == 'suffix' or possible_types[0] == 'suffix 1':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '[^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', \"\\\\g<1>'\", token\n )\n elif possible_types[0] == 'suffix 2':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){2})',\n \"\\\\g<1>'\", token)\n elif possible_types[0] == 'suffix 3':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){3})',\n \"\\\\g<1>'\", token)\n elif possible_types[0] == 'presuffix':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n suffixes = re.sub(stem_cutted, '', stem)\n stressed_word = re.sub(\n '([уеыаоэяиюёУЕЫАОЭЯИЮЁ])([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*' + suffixes +\n '.{,5})$', \"\\\\g<1>'\\\\g<2>\", token)\n elif possible_types[0] == 'type B':\n stressed_word = re.sub('^(.+[уеыаоэяиюё])([^уеыаоэяиюё]*)$',\n \"\\\\g<1>'\\\\g<2>\", token)\n try:\n parts = stressed_word.split(\"'\")\n stressed_word = original_token[:len(parts[0])] + \"'\" + original_token[\n len(parts[0]):]\n except:\n stressed_word = original_token\n return stressed_word\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef make_rules(folder):\n rules_dictionary = {}\n try:\n path = os.path.join(os.getcwd(), 'rules', 'data', folder)\n files = os.listdir(path)\n except:\n path = os.path.join(os.getcwd(), 'data', folder)\n files = os.listdir(path)\n short_files_rule = re.compile('.txt')\n for file in files:\n if short_files_rule.search(file) != None:\n class_name = re.sub('_', ' ', re.sub('\\\\.txt', '', file))\n current_file = open(os.path.join(path, file), 'r', encoding='utf-8'\n ).read()\n affixes = current_file.split(', ')\n rules_dictionary[class_name] = affixes\n return rules_dictionary\n\n\ndef find_affixes(rules_noun, lemma, word_possible_stress):\n for stress_type, affixes in rules_noun.items():\n for affix in affixes:\n affix_type = ''\n if re.search('^[а-яё]+\\\\-$', affix) != None:\n regexp = '^' + affix[:-1]\n affix_type = 'preffix'\n elif re.search('^\\\\-[а-яё]+$', affix) != None:\n regexp = affix[1:] + '$'\n affix_type = 'suffix'\n elif re.search('^[а-яё]+\\\\-\\\\.\\\\.\\\\.\\\\-[а-яё]+$', affix) != None:\n regexp = '^' + re.sub('\\\\-\\\\.\\\\.\\\\.\\\\-', '.+', affix) + '$'\n affix_type = 'combination'\n if re.search(regexp, lemma) != None:\n if stress_type in word_possible_stress:\n word_possible_stress[stress_type].append((affix,\n affix_type))\n else:\n word_possible_stress[stress_type] = [(affix, affix_type)]\n return word_possible_stress\n\n\n<mask token>\n\n\ndef find_possible_types(word_possible_stress, biggest_suffix, biggest_prefix):\n possible_types = []\n for stress_type, affixes in word_possible_stress.items():\n for affix in affixes:\n if affix[1] == 'suffix':\n if affix[0] == biggest_suffix:\n possible_types.append(stress_type)\n elif affix[1] == 'prefix':\n if affix[0] == biggest_prefix:\n possible_types.append(stress_type)\n elif affix[1] == 'combination':\n possible_types = []\n pair = affix[0].split('...')\n if pair[0] == biggest_prefix and pair[1] == biggest_suffix:\n possible_types.append(stress_type)\n return possible_types\n\n\ndef make_stressed_word(possible_types, token, lemma, biggest_suffix,\n original_token):\n if possible_types[0] == 'prefix' or possible_types[0] == 'first vowel':\n stressed_word = re.sub(\n '^([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', \"\\\\g<1>'\",\n token)\n elif possible_types[0] == 'suffix' or possible_types[0] == 'suffix 1':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '[^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', \"\\\\g<1>'\", token\n )\n elif possible_types[0] == 'suffix 2':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){2})',\n \"\\\\g<1>'\", token)\n elif possible_types[0] == 'suffix 3':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){3})',\n \"\\\\g<1>'\", token)\n elif possible_types[0] == 'presuffix':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n suffixes = re.sub(stem_cutted, '', stem)\n stressed_word = re.sub(\n '([уеыаоэяиюёУЕЫАОЭЯИЮЁ])([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*' + suffixes +\n '.{,5})$', \"\\\\g<1>'\\\\g<2>\", token)\n elif possible_types[0] == 'type B':\n stressed_word = re.sub('^(.+[уеыаоэяиюё])([^уеыаоэяиюё]*)$',\n \"\\\\g<1>'\\\\g<2>\", token)\n try:\n parts = stressed_word.split(\"'\")\n stressed_word = original_token[:len(parts[0])] + \"'\" + original_token[\n len(parts[0]):]\n except:\n stressed_word = original_token\n return stressed_word\n\n\ndef process_stresses(part_of_speech, rules, pos, lemma, token,\n original_token, word_possible_stress, current_file):\n stressed_word, biggest_suffix, possible_types = '', '', ['']\n if part_of_speech in pos:\n word_possible_stress = find_affixes(rules, lemma, word_possible_stress)\n if word_possible_stress != {} and list(word_possible_stress.keys()\n ) != ['all prefixes', 'all suffixes'] and list(word_possible_stress\n .keys()) != ['all suffixes'] and list(word_possible_stress.keys()\n ) != ['all prefixes']:\n biggest_prefix, biggest_suffix, word_possible_stress = (\n find_biggest_affixes(word_possible_stress))\n possible_types = find_possible_types(word_possible_stress,\n biggest_suffix, biggest_prefix)\n if len(possible_types) == 1:\n stressed_word = make_stressed_word(possible_types, token,\n lemma, biggest_suffix, original_token)\n current_file = re.sub(original_token, stressed_word,\n current_file)\n if possible_types == []:\n possible_types = ['']\n return current_file, stressed_word, biggest_suffix, possible_types[0]\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef make_rules(folder):\n rules_dictionary = {}\n try:\n path = os.path.join(os.getcwd(), 'rules', 'data', folder)\n files = os.listdir(path)\n except:\n path = os.path.join(os.getcwd(), 'data', folder)\n files = os.listdir(path)\n short_files_rule = re.compile('.txt')\n for file in files:\n if short_files_rule.search(file) != None:\n class_name = re.sub('_', ' ', re.sub('\\\\.txt', '', file))\n current_file = open(os.path.join(path, file), 'r', encoding='utf-8'\n ).read()\n affixes = current_file.split(', ')\n rules_dictionary[class_name] = affixes\n return rules_dictionary\n\n\ndef find_affixes(rules_noun, lemma, word_possible_stress):\n for stress_type, affixes in rules_noun.items():\n for affix in affixes:\n affix_type = ''\n if re.search('^[а-яё]+\\\\-$', affix) != None:\n regexp = '^' + affix[:-1]\n affix_type = 'preffix'\n elif re.search('^\\\\-[а-яё]+$', affix) != None:\n regexp = affix[1:] + '$'\n affix_type = 'suffix'\n elif re.search('^[а-яё]+\\\\-\\\\.\\\\.\\\\.\\\\-[а-яё]+$', affix) != None:\n regexp = '^' + re.sub('\\\\-\\\\.\\\\.\\\\.\\\\-', '.+', affix) + '$'\n affix_type = 'combination'\n if re.search(regexp, lemma) != None:\n if stress_type in word_possible_stress:\n word_possible_stress[stress_type].append((affix,\n affix_type))\n else:\n word_possible_stress[stress_type] = [(affix, affix_type)]\n return word_possible_stress\n\n\ndef find_biggest_affixes(word_possible_stress):\n biggest_len_suffix, biggest_len_prefix = 0, 0\n biggest_suffix, biggest_prefix = '', ''\n if 'all suffixes' in word_possible_stress:\n for suffix in word_possible_stress['all suffixes']:\n if len(suffix[0]) > biggest_len_suffix:\n biggest_suffix = suffix[0]\n biggest_len_suffix = len(suffix[0])\n del word_possible_stress['all suffixes']\n if 'all prefixes' in word_possible_stress:\n for prefix in word_possible_stress['all prefixes']:\n if len(prefix[0]) > biggest_len_prefix:\n biggest_prefix = prefix[0]\n biggest_len_prefix = len(prefix[0])\n del word_possible_stress['all prefixes']\n return biggest_prefix, biggest_suffix, word_possible_stress\n\n\ndef find_possible_types(word_possible_stress, biggest_suffix, biggest_prefix):\n possible_types = []\n for stress_type, affixes in word_possible_stress.items():\n for affix in affixes:\n if affix[1] == 'suffix':\n if affix[0] == biggest_suffix:\n possible_types.append(stress_type)\n elif affix[1] == 'prefix':\n if affix[0] == biggest_prefix:\n possible_types.append(stress_type)\n elif affix[1] == 'combination':\n possible_types = []\n pair = affix[0].split('...')\n if pair[0] == biggest_prefix and pair[1] == biggest_suffix:\n possible_types.append(stress_type)\n return possible_types\n\n\ndef make_stressed_word(possible_types, token, lemma, biggest_suffix,\n original_token):\n if possible_types[0] == 'prefix' or possible_types[0] == 'first vowel':\n stressed_word = re.sub(\n '^([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', \"\\\\g<1>'\",\n token)\n elif possible_types[0] == 'suffix' or possible_types[0] == 'suffix 1':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '[^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', \"\\\\g<1>'\", token\n )\n elif possible_types[0] == 'suffix 2':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){2})',\n \"\\\\g<1>'\", token)\n elif possible_types[0] == 'suffix 3':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){3})',\n \"\\\\g<1>'\", token)\n elif possible_types[0] == 'presuffix':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n suffixes = re.sub(stem_cutted, '', stem)\n stressed_word = re.sub(\n '([уеыаоэяиюёУЕЫАОЭЯИЮЁ])([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*' + suffixes +\n '.{,5})$', \"\\\\g<1>'\\\\g<2>\", token)\n elif possible_types[0] == 'type B':\n stressed_word = re.sub('^(.+[уеыаоэяиюё])([^уеыаоэяиюё]*)$',\n \"\\\\g<1>'\\\\g<2>\", token)\n try:\n parts = stressed_word.split(\"'\")\n stressed_word = original_token[:len(parts[0])] + \"'\" + original_token[\n len(parts[0]):]\n except:\n stressed_word = original_token\n return stressed_word\n\n\ndef process_stresses(part_of_speech, rules, pos, lemma, token,\n original_token, word_possible_stress, current_file):\n stressed_word, biggest_suffix, possible_types = '', '', ['']\n if part_of_speech in pos:\n word_possible_stress = find_affixes(rules, lemma, word_possible_stress)\n if word_possible_stress != {} and list(word_possible_stress.keys()\n ) != ['all prefixes', 'all suffixes'] and list(word_possible_stress\n .keys()) != ['all suffixes'] and list(word_possible_stress.keys()\n ) != ['all prefixes']:\n biggest_prefix, biggest_suffix, word_possible_stress = (\n find_biggest_affixes(word_possible_stress))\n possible_types = find_possible_types(word_possible_stress,\n biggest_suffix, biggest_prefix)\n if len(possible_types) == 1:\n stressed_word = make_stressed_word(possible_types, token,\n lemma, biggest_suffix, original_token)\n current_file = re.sub(original_token, stressed_word,\n current_file)\n if possible_types == []:\n possible_types = ['']\n return current_file, stressed_word, biggest_suffix, possible_types[0]\n\n\ndef initialize(current_file):\n morph = pymorphy2.MorphAnalyzer()\n rules_noun = make_rules('NOUN')\n rules_adj = make_rules('ADJ')\n rules_verb = make_rules('VERB')\n all_tokens = nltk.word_tokenize(current_file)\n stressed_words, biggest_suffixes, stress_types, poses = [], [], [], []\n for token in all_tokens:\n stressed_word, biggest_suffix, stress_type = token, '', ''\n original_token = token\n token = token.lower()\n word_possible_stress = {}\n if re.search('^[А-ЯЁа-яё\\\\-]+$', token) != None and token != '-':\n token = re.sub('^-', '', token)\n pos = morph.parse(token)[0].tag.POS\n lemma = morph.parse(token)[0].normal_form\n if pos != None:\n (current_file, stressed_word, biggest_suffix, stress_type) = (\n process_stresses('NOUN', rules_noun, pos, lemma, token,\n original_token, word_possible_stress, current_file))\n if biggest_suffix == '':\n (current_file, stressed_word, biggest_suffix, stress_type\n ) = (process_stresses('ADJF', rules_adj, pos, lemma,\n token, original_token, word_possible_stress,\n current_file))\n if biggest_suffix == '':\n (current_file, stressed_word, biggest_suffix,\n stress_type) = (process_stresses('VERB',\n rules_verb, pos, lemma, token, original_token,\n word_possible_stress, current_file))\n if stressed_word == '':\n stressed_word = original_token\n stressed_words.append(stressed_word)\n biggest_suffixes.append(biggest_suffix)\n stress_types.append(stress_type)\n poses.append(pos)\n return current_file, stressed_words, biggest_suffixes, stress_types, poses\n", "step-4": "import re, os, nltk, pymorphy2, sys\nfrom suffix_trees.STree import STree\n\n\ndef make_rules(folder):\n rules_dictionary = {}\n try:\n path = os.path.join(os.getcwd(), 'rules', 'data', folder)\n files = os.listdir(path)\n except:\n path = os.path.join(os.getcwd(), 'data', folder)\n files = os.listdir(path)\n short_files_rule = re.compile('.txt')\n for file in files:\n if short_files_rule.search(file) != None:\n class_name = re.sub('_', ' ', re.sub('\\\\.txt', '', file))\n current_file = open(os.path.join(path, file), 'r', encoding='utf-8'\n ).read()\n affixes = current_file.split(', ')\n rules_dictionary[class_name] = affixes\n return rules_dictionary\n\n\ndef find_affixes(rules_noun, lemma, word_possible_stress):\n for stress_type, affixes in rules_noun.items():\n for affix in affixes:\n affix_type = ''\n if re.search('^[а-яё]+\\\\-$', affix) != None:\n regexp = '^' + affix[:-1]\n affix_type = 'preffix'\n elif re.search('^\\\\-[а-яё]+$', affix) != None:\n regexp = affix[1:] + '$'\n affix_type = 'suffix'\n elif re.search('^[а-яё]+\\\\-\\\\.\\\\.\\\\.\\\\-[а-яё]+$', affix) != None:\n regexp = '^' + re.sub('\\\\-\\\\.\\\\.\\\\.\\\\-', '.+', affix) + '$'\n affix_type = 'combination'\n if re.search(regexp, lemma) != None:\n if stress_type in word_possible_stress:\n word_possible_stress[stress_type].append((affix,\n affix_type))\n else:\n word_possible_stress[stress_type] = [(affix, affix_type)]\n return word_possible_stress\n\n\ndef find_biggest_affixes(word_possible_stress):\n biggest_len_suffix, biggest_len_prefix = 0, 0\n biggest_suffix, biggest_prefix = '', ''\n if 'all suffixes' in word_possible_stress:\n for suffix in word_possible_stress['all suffixes']:\n if len(suffix[0]) > biggest_len_suffix:\n biggest_suffix = suffix[0]\n biggest_len_suffix = len(suffix[0])\n del word_possible_stress['all suffixes']\n if 'all prefixes' in word_possible_stress:\n for prefix in word_possible_stress['all prefixes']:\n if len(prefix[0]) > biggest_len_prefix:\n biggest_prefix = prefix[0]\n biggest_len_prefix = len(prefix[0])\n del word_possible_stress['all prefixes']\n return biggest_prefix, biggest_suffix, word_possible_stress\n\n\ndef find_possible_types(word_possible_stress, biggest_suffix, biggest_prefix):\n possible_types = []\n for stress_type, affixes in word_possible_stress.items():\n for affix in affixes:\n if affix[1] == 'suffix':\n if affix[0] == biggest_suffix:\n possible_types.append(stress_type)\n elif affix[1] == 'prefix':\n if affix[0] == biggest_prefix:\n possible_types.append(stress_type)\n elif affix[1] == 'combination':\n possible_types = []\n pair = affix[0].split('...')\n if pair[0] == biggest_prefix and pair[1] == biggest_suffix:\n possible_types.append(stress_type)\n return possible_types\n\n\ndef make_stressed_word(possible_types, token, lemma, biggest_suffix,\n original_token):\n if possible_types[0] == 'prefix' or possible_types[0] == 'first vowel':\n stressed_word = re.sub(\n '^([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', \"\\\\g<1>'\",\n token)\n elif possible_types[0] == 'suffix' or possible_types[0] == 'suffix 1':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '[^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', \"\\\\g<1>'\", token\n )\n elif possible_types[0] == 'suffix 2':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){2})',\n \"\\\\g<1>'\", token)\n elif possible_types[0] == 'suffix 3':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n stressed_word = re.sub('^(' + stem_cutted +\n '([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){3})',\n \"\\\\g<1>'\", token)\n elif possible_types[0] == 'presuffix':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix) + '$', '', stem)\n for num in range(1, 5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num] +\n '$', '', stem)\n suffixes = re.sub(stem_cutted, '', stem)\n stressed_word = re.sub(\n '([уеыаоэяиюёУЕЫАОЭЯИЮЁ])([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*' + suffixes +\n '.{,5})$', \"\\\\g<1>'\\\\g<2>\", token)\n elif possible_types[0] == 'type B':\n stressed_word = re.sub('^(.+[уеыаоэяиюё])([^уеыаоэяиюё]*)$',\n \"\\\\g<1>'\\\\g<2>\", token)\n try:\n parts = stressed_word.split(\"'\")\n stressed_word = original_token[:len(parts[0])] + \"'\" + original_token[\n len(parts[0]):]\n except:\n stressed_word = original_token\n return stressed_word\n\n\ndef process_stresses(part_of_speech, rules, pos, lemma, token,\n original_token, word_possible_stress, current_file):\n stressed_word, biggest_suffix, possible_types = '', '', ['']\n if part_of_speech in pos:\n word_possible_stress = find_affixes(rules, lemma, word_possible_stress)\n if word_possible_stress != {} and list(word_possible_stress.keys()\n ) != ['all prefixes', 'all suffixes'] and list(word_possible_stress\n .keys()) != ['all suffixes'] and list(word_possible_stress.keys()\n ) != ['all prefixes']:\n biggest_prefix, biggest_suffix, word_possible_stress = (\n find_biggest_affixes(word_possible_stress))\n possible_types = find_possible_types(word_possible_stress,\n biggest_suffix, biggest_prefix)\n if len(possible_types) == 1:\n stressed_word = make_stressed_word(possible_types, token,\n lemma, biggest_suffix, original_token)\n current_file = re.sub(original_token, stressed_word,\n current_file)\n if possible_types == []:\n possible_types = ['']\n return current_file, stressed_word, biggest_suffix, possible_types[0]\n\n\ndef initialize(current_file):\n morph = pymorphy2.MorphAnalyzer()\n rules_noun = make_rules('NOUN')\n rules_adj = make_rules('ADJ')\n rules_verb = make_rules('VERB')\n all_tokens = nltk.word_tokenize(current_file)\n stressed_words, biggest_suffixes, stress_types, poses = [], [], [], []\n for token in all_tokens:\n stressed_word, biggest_suffix, stress_type = token, '', ''\n original_token = token\n token = token.lower()\n word_possible_stress = {}\n if re.search('^[А-ЯЁа-яё\\\\-]+$', token) != None and token != '-':\n token = re.sub('^-', '', token)\n pos = morph.parse(token)[0].tag.POS\n lemma = morph.parse(token)[0].normal_form\n if pos != None:\n (current_file, stressed_word, biggest_suffix, stress_type) = (\n process_stresses('NOUN', rules_noun, pos, lemma, token,\n original_token, word_possible_stress, current_file))\n if biggest_suffix == '':\n (current_file, stressed_word, biggest_suffix, stress_type\n ) = (process_stresses('ADJF', rules_adj, pos, lemma,\n token, original_token, word_possible_stress,\n current_file))\n if biggest_suffix == '':\n (current_file, stressed_word, biggest_suffix,\n stress_type) = (process_stresses('VERB',\n rules_verb, pos, lemma, token, original_token,\n word_possible_stress, current_file))\n if stressed_word == '':\n stressed_word = original_token\n stressed_words.append(stressed_word)\n biggest_suffixes.append(biggest_suffix)\n stress_types.append(stress_type)\n poses.append(pos)\n return current_file, stressed_words, biggest_suffixes, stress_types, poses\n", "step-5": "import re, os, nltk, pymorphy2, sys\nfrom suffix_trees.STree import STree\n\n\ndef make_rules(folder):\n rules_dictionary = {}\n try:\n path = os.path.join(os.getcwd(), 'rules', 'data', folder)\n files = os.listdir(path)\n except:\n path = os.path.join(os.getcwd(), 'data', folder)\n files = os.listdir(path)\n short_files_rule = re.compile('.txt')\n for file in files:\n if short_files_rule.search(file) != None:\n class_name = re.sub('_', ' ', re.sub('\\.txt', '', file))\n current_file = open(os.path.join(path, file), 'r', encoding='utf-8').read()\n affixes = current_file.split(', ')\n rules_dictionary[class_name] = affixes\n return(rules_dictionary)\n\n\ndef find_affixes(rules_noun, lemma, word_possible_stress):\n for stress_type, affixes in rules_noun.items():\n for affix in affixes:\n affix_type = ''\n if re.search('^[а-яё]+\\-$', affix) != None:\n regexp = '^'+affix[:-1]\n affix_type = 'preffix'\n elif re.search('^\\-[а-яё]+$', affix) != None:\n regexp = affix[1:]+'$'\n affix_type = 'suffix'\n elif re.search('^[а-яё]+\\-\\.\\.\\.\\-[а-яё]+$', affix) != None:\n regexp = '^'+re.sub('\\-\\.\\.\\.\\-', '.+', affix)+'$'\n affix_type = 'combination'\n\n if re.search(regexp, lemma) != None:\n if stress_type in word_possible_stress:\n word_possible_stress[stress_type].append((affix, affix_type))\n else:\n word_possible_stress[stress_type] = [(affix, affix_type)]\n return(word_possible_stress)\n\n\ndef find_biggest_affixes(word_possible_stress):\n biggest_len_suffix, biggest_len_prefix = 0, 0\n biggest_suffix, biggest_prefix = '', ''\n if 'all suffixes' in word_possible_stress:\n for suffix in word_possible_stress['all suffixes']:\n if len(suffix[0]) > biggest_len_suffix:\n biggest_suffix = suffix[0]\n biggest_len_suffix = len(suffix[0])\n del word_possible_stress['all suffixes']\n \n if 'all prefixes' in word_possible_stress:\n for prefix in word_possible_stress['all prefixes']:\n if len(prefix[0]) > biggest_len_prefix:\n biggest_prefix = prefix[0]\n biggest_len_prefix = len(prefix[0])\n del word_possible_stress['all prefixes']\n return(biggest_prefix, biggest_suffix, word_possible_stress)\n\n\ndef find_possible_types(word_possible_stress, biggest_suffix, biggest_prefix):\n possible_types = []\n for stress_type, affixes in word_possible_stress.items():\n for affix in affixes:\n if affix[1] == 'suffix':\n if affix[0] == biggest_suffix:\n possible_types.append(stress_type)\n elif affix[1] == 'prefix':\n if affix[0] == biggest_prefix:\n possible_types.append(stress_type)\n elif affix[1] == 'combination':\n possible_types = []\n pair = affix[0].split('...')\n if pair[0] == biggest_prefix and pair[1] == biggest_suffix:\n possible_types.append(stress_type)\n return(possible_types)\n\n\ndef make_stressed_word(possible_types, token, lemma, biggest_suffix, original_token): \n if possible_types[0] == 'prefix' or possible_types[0] == 'first vowel':\n stressed_word = re.sub('^([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', '\\g<1>\\'', token)\n #print(token, stressed_word, lemma, biggest_prefix, biggest_suffix)\n elif possible_types[0] == 'suffix' or possible_types[0] == 'suffix 1':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)+'$', '', stem)\n for num in range(1,5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num]+'$', '', stem)\n stressed_word = re.sub('^('+stem_cutted+'[^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ])', '\\g<1>\\'', token)\n elif possible_types[0] == 'suffix 2':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)+'$', '', stem)\n for num in range(1,5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num]+'$', '', stem)\n stressed_word = re.sub('^('+stem_cutted+'([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){2})', '\\g<1>\\'', token)\n\n elif possible_types[0] == 'suffix 3':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)+'$', '', stem)\n for num in range(1,5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num]+'$', '', stem)\n stressed_word = re.sub('^('+stem_cutted+'([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*[уеыаоэяиюёУЕЫАОЭЯИЮЁ]){3})', '\\g<1>\\'', token)\n \n elif possible_types[0] == 'presuffix':\n stem = STree([token, lemma]).lcs()\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)+'$', '', stem)\n for num in range(1,5):\n if stem == stem_cutted:\n stem_cutted = re.sub(re.sub('-', '', biggest_suffix)[:-num]+'$', '', stem)\n suffixes = re.sub(stem_cutted, '', stem)\n stressed_word = re.sub('([уеыаоэяиюёУЕЫАОЭЯИЮЁ])([^уеыаоэяиюёУЕЫАОЭЯИЮЁ]*'+suffixes+'.{,5})$', '\\g<1>\\'\\g<2>', token)\n elif possible_types[0] == 'type B':\n stressed_word = re.sub('^(.+[уеыаоэяиюё])([^уеыаоэяиюё]*)$', '\\g<1>\\'\\g<2>', token)\n try:\n parts = stressed_word.split('\\'')\n stressed_word = original_token[:len(parts[0])]+'\\''+original_token[len(parts[0]):]\n except:\n stressed_word = original_token\n return(stressed_word)\n\n\ndef process_stresses(part_of_speech, rules, pos, lemma, token, original_token, word_possible_stress, current_file):\n stressed_word, biggest_suffix, possible_types = '', '', ['']\n if part_of_speech in pos:\n word_possible_stress = find_affixes(rules, lemma, word_possible_stress)\n\n if word_possible_stress != {} and list(word_possible_stress.keys()) != ['all prefixes', 'all suffixes'] and \\\n list(word_possible_stress.keys()) != ['all suffixes'] and list(word_possible_stress.keys()) != ['all prefixes']:\n\n biggest_prefix, biggest_suffix, word_possible_stress = find_biggest_affixes(word_possible_stress)\n possible_types = find_possible_types(word_possible_stress, biggest_suffix, biggest_prefix)\n if len(possible_types) == 1:\n stressed_word = make_stressed_word(possible_types, token, lemma, biggest_suffix, original_token)\n current_file = re.sub(original_token, stressed_word, current_file)\n## if pos == 'VERB':\n## print(pos, lemma, token, stressed_word, biggest_suffix, possible_types[0])\n if possible_types == []: possible_types = ['']\n return(current_file, stressed_word, biggest_suffix, possible_types[0])\n\n\ndef initialize(current_file):\n morph = pymorphy2.MorphAnalyzer()\n rules_noun = make_rules('NOUN')\n rules_adj = make_rules('ADJ')\n rules_verb = make_rules('VERB')\n all_tokens = nltk.word_tokenize(current_file)\n stressed_words, biggest_suffixes, stress_types, poses = [], [], [], []\n for token in all_tokens:\n stressed_word, biggest_suffix, stress_type = token, '', ''\n original_token = token\n token = token.lower()\n word_possible_stress = {}\n if re.search('^[А-ЯЁа-яё\\-]+$', token) != None and token != '-':\n token = re.sub('^-', '', token)\n pos = morph.parse(token)[0].tag.POS\n #pos = nltk.pos_tag(token, lang='rus')\n lemma = morph.parse(token)[0].normal_form\n if pos != None:\n current_file, stressed_word, biggest_suffix, stress_type = process_stresses('NOUN', rules_noun, pos, lemma, token, original_token, word_possible_stress, current_file)\n if biggest_suffix == '':\n current_file,stressed_word, biggest_suffix, stress_type = process_stresses('ADJF', rules_adj, pos, lemma, token, original_token, word_possible_stress, current_file)\n if biggest_suffix == '':\n current_file, stressed_word, biggest_suffix, stress_type = process_stresses('VERB', rules_verb, pos, lemma, token, original_token, word_possible_stress, current_file)\n if stressed_word == '':\n stressed_word = original_token\n stressed_words.append(stressed_word)\n biggest_suffixes.append(biggest_suffix)\n stress_types.append(stress_type)\n poses.append(pos)\n return(current_file, stressed_words, biggest_suffixes, stress_types, poses)\n", "step-ids": [ 4, 5, 7, 8, 9 ] }
[ 4, 5, 7, 8, 9 ]
# The project is based on Tensorflow's Text Generation with RNN tutorial # Copyright Petros Demetrakopoulos 2020 import tensorflow as tf import numpy as np import os import time # The project is based on Tensorflow's Text Generation with RNN tutorial # Copyright Petros Demetrakopoulos 2020 import tensorflow as tf import numpy as np import os import time from random import seed from random import randint import sys import urllib.request stopChars = [',', '(', ')', '.', '-', '[', ']', '"'] corpus_path = "/tmp/data.txt" text = open(corpus_path, 'rb').read().decode(encoding='utf-8') text = preprocessText(text) corpus_words = corpusToList(text) map(str.strip, corpus_words) # trim words vocab = sorted(set(corpus_words)) print('Corpus length (in words):', len(corpus_words)) print('Unique words in corpus: {}'.format(len(vocab))) word2idx = {u: i for i, u in enumerate(vocab)} idx2words = np.array(vocab) word_as_int = np.array([word2idx[c] for c in corpus_words]) # The maximum length sentence we want for a single input in words seqLength = 10 examples_per_epoch = len(corpus_words)//(seqLength + 1) # Create training examples / targets wordDataset = tf.data.Dataset.from_tensor_slices(word_as_int) # generating batches of 10 words each sequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True) def yuh(): corpus_path = "/tmp/data.txt" text = open(corpus_path, 'rb').read().decode(encoding='utf-8') text = preprocessText(text) corpus_words = corpusToList(text) map(str.strip, corpus_words) # trim words vocab = sorted(set(corpus_words)) print('Corpus length (in words):', len(corpus_words)) print('Unique words in corpus: {}'.format(len(vocab))) word2idx = {u: i for i, u in enumerate(vocab)} idx2words = np.array(vocab) word_as_int = np.array([word2idx[c] for c in corpus_words]) # The maximum length sentence we want for a single input in words seqLength = 10 examples_per_epoch = len(corpus_words)//(seqLength + 1) # Create training examples / targets wordDataset = tf.data.Dataset.from_tensor_slices(word_as_int) # generating batches of 10 words each sequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True) def preprocessText(text): text = text.replace('\n', ' ').replace('\t', '') processedText = text.lower() for char in stopChars: processedText = processedText.replace(char, ' ') return processedText def corpusToList(corpus): corpusList = [w for w in corpus.split(' ')] # removing empty strings from list corpusList = [i for i in corpusList if i] return corpusList def split_input_target(chunk): input_text = chunk[:-1] target_text = chunk[1:] return input_text, target_text def loss(labels, logits): return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True) def generateLyrics(model, startString, temp): # Number of words to generate num_generate = 30 # Converting our start string to numbers (vectorizing) start_string_list = [w for w in startString.split(' ')] input_eval = [word2idx[s] for s in start_string_list] input_eval = tf.expand_dims(input_eval, 0) text_generated = [] model.reset_states() for i in range(num_generate): predictions = model(input_eval) predictions = tf.squeeze(predictions, 0) predictions = predictions / temp predicted_id = tf.random.categorical( predictions, num_samples=1)[-1, 0].numpy() input_eval = tf.expand_dims([predicted_id], 0) text_generated.append(' ' + idx2words[predicted_id]) return (startString + ''.join(text_generated)) def doSomeWork(artist): url = '''https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.txt?alt=media&token=604b7b6c-2ef0-4611-ab6e-a08dd53e99be''' urllib.request.urlretrieve(url, '/tmp/data.txt') if artist == "kanye": url = ''' https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkanye.h5?alt=media&token=a0b94c61-e696-453d-9a16-110af66f6afd''' if artist == "nas": url = ''' https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fnas.h5?alt=media&token=037ef224-be5f-4449-a89c-c1897e164289''' if artist == "biggie": url = '''https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fbiggie.h5?alt=media&token=3244a8e2-017c-472f-a66b-7810a198d038''' if artist == "jayz": url = '''https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fjayz.h5?alt=media&token=500ff44d-60fe-4774-9c85-5ea6f06da81b''' if artist == "ross" or artist == "kendrick" or artist == "50cent": url = ''' https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.h5?alt=media&token=6ceff75d-5a71-49d4-b927-e727888d872f ''' named = "/tmp/" + artist + ".h5" if (artist == "biggie") or artist == "50cent": named = "/tmp/kendrick" + ".h5" urllib.request.urlretrieve(url, named) yuh() model = tf.keras.models.load_model(named) seed(1) input_str = vocab[randint(0, len(vocab))] lyricz = [] for i in range(10): lyrics = generateLyrics(model, startString=input_str, temp=0.6) temp = lyrics.replace("nigga", "homie").replace("niggas", "homies").replace("nigger", "homie").replace( "niggers", "homies").replace("faggot", "maggot").replace("fag", "mag").replace('\r', '') lyricz.append(lyrics.replace("nigga", "homie").replace('\r', '')) input_str = temp.split()[-1] return jsonify({ "Success": "It worked", "Url": " ".join(lyricz) })
normal
{ "blob_id": "5ff0c6bde8f3ffcb1f5988b0bbd1dfdd7fa2e818", "index": 8800, "step-1": "<mask token>\n\n\ndef yuh():\n corpus_path = '/tmp/data.txt'\n text = open(corpus_path, 'rb').read().decode(encoding='utf-8')\n text = preprocessText(text)\n corpus_words = corpusToList(text)\n map(str.strip, corpus_words)\n vocab = sorted(set(corpus_words))\n print('Corpus length (in words):', len(corpus_words))\n print('Unique words in corpus: {}'.format(len(vocab)))\n word2idx = {u: i for i, u in enumerate(vocab)}\n idx2words = np.array(vocab)\n word_as_int = np.array([word2idx[c] for c in corpus_words])\n seqLength = 10\n examples_per_epoch = len(corpus_words) // (seqLength + 1)\n wordDataset = tf.data.Dataset.from_tensor_slices(word_as_int)\n sequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True)\n\n\ndef preprocessText(text):\n text = text.replace('\\n', ' ').replace('\\t', '')\n processedText = text.lower()\n for char in stopChars:\n processedText = processedText.replace(char, ' ')\n return processedText\n\n\n<mask token>\n\n\ndef split_input_target(chunk):\n input_text = chunk[:-1]\n target_text = chunk[1:]\n return input_text, target_text\n\n\ndef loss(labels, logits):\n return tf.keras.losses.sparse_categorical_crossentropy(labels, logits,\n from_logits=True)\n\n\ndef generateLyrics(model, startString, temp):\n num_generate = 30\n start_string_list = [w for w in startString.split(' ')]\n input_eval = [word2idx[s] for s in start_string_list]\n input_eval = tf.expand_dims(input_eval, 0)\n text_generated = []\n model.reset_states()\n for i in range(num_generate):\n predictions = model(input_eval)\n predictions = tf.squeeze(predictions, 0)\n predictions = predictions / temp\n predicted_id = tf.random.categorical(predictions, num_samples=1)[-1, 0\n ].numpy()\n input_eval = tf.expand_dims([predicted_id], 0)\n text_generated.append(' ' + idx2words[predicted_id])\n return startString + ''.join(text_generated)\n\n\ndef doSomeWork(artist):\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.txt?alt=media&token=604b7b6c-2ef0-4611-ab6e-a08dd53e99be'\n )\n urllib.request.urlretrieve(url, '/tmp/data.txt')\n if artist == 'kanye':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkanye.h5?alt=media&token=a0b94c61-e696-453d-9a16-110af66f6afd\"\"\"\n if artist == 'nas':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fnas.h5?alt=media&token=037ef224-be5f-4449-a89c-c1897e164289\"\"\"\n if artist == 'biggie':\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fbiggie.h5?alt=media&token=3244a8e2-017c-472f-a66b-7810a198d038'\n )\n if artist == 'jayz':\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fjayz.h5?alt=media&token=500ff44d-60fe-4774-9c85-5ea6f06da81b'\n )\n if artist == 'ross' or artist == 'kendrick' or artist == '50cent':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.h5?alt=media&token=6ceff75d-5a71-49d4-b927-e727888d872f\n \"\"\"\n named = '/tmp/' + artist + '.h5'\n if artist == 'biggie' or artist == '50cent':\n named = '/tmp/kendrick' + '.h5'\n urllib.request.urlretrieve(url, named)\n yuh()\n model = tf.keras.models.load_model(named)\n seed(1)\n input_str = vocab[randint(0, len(vocab))]\n lyricz = []\n for i in range(10):\n lyrics = generateLyrics(model, startString=input_str, temp=0.6)\n temp = lyrics.replace('nigga', 'homie').replace('niggas', 'homies'\n ).replace('nigger', 'homie').replace('niggers', 'homies').replace(\n 'faggot', 'maggot').replace('fag', 'mag').replace('\\r', '')\n lyricz.append(lyrics.replace('nigga', 'homie').replace('\\r', ''))\n input_str = temp.split()[-1]\n return jsonify({'Success': 'It worked', 'Url': ' '.join(lyricz)})\n", "step-2": "<mask token>\n\n\ndef yuh():\n corpus_path = '/tmp/data.txt'\n text = open(corpus_path, 'rb').read().decode(encoding='utf-8')\n text = preprocessText(text)\n corpus_words = corpusToList(text)\n map(str.strip, corpus_words)\n vocab = sorted(set(corpus_words))\n print('Corpus length (in words):', len(corpus_words))\n print('Unique words in corpus: {}'.format(len(vocab)))\n word2idx = {u: i for i, u in enumerate(vocab)}\n idx2words = np.array(vocab)\n word_as_int = np.array([word2idx[c] for c in corpus_words])\n seqLength = 10\n examples_per_epoch = len(corpus_words) // (seqLength + 1)\n wordDataset = tf.data.Dataset.from_tensor_slices(word_as_int)\n sequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True)\n\n\ndef preprocessText(text):\n text = text.replace('\\n', ' ').replace('\\t', '')\n processedText = text.lower()\n for char in stopChars:\n processedText = processedText.replace(char, ' ')\n return processedText\n\n\ndef corpusToList(corpus):\n corpusList = [w for w in corpus.split(' ')]\n corpusList = [i for i in corpusList if i]\n return corpusList\n\n\ndef split_input_target(chunk):\n input_text = chunk[:-1]\n target_text = chunk[1:]\n return input_text, target_text\n\n\ndef loss(labels, logits):\n return tf.keras.losses.sparse_categorical_crossentropy(labels, logits,\n from_logits=True)\n\n\ndef generateLyrics(model, startString, temp):\n num_generate = 30\n start_string_list = [w for w in startString.split(' ')]\n input_eval = [word2idx[s] for s in start_string_list]\n input_eval = tf.expand_dims(input_eval, 0)\n text_generated = []\n model.reset_states()\n for i in range(num_generate):\n predictions = model(input_eval)\n predictions = tf.squeeze(predictions, 0)\n predictions = predictions / temp\n predicted_id = tf.random.categorical(predictions, num_samples=1)[-1, 0\n ].numpy()\n input_eval = tf.expand_dims([predicted_id], 0)\n text_generated.append(' ' + idx2words[predicted_id])\n return startString + ''.join(text_generated)\n\n\ndef doSomeWork(artist):\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.txt?alt=media&token=604b7b6c-2ef0-4611-ab6e-a08dd53e99be'\n )\n urllib.request.urlretrieve(url, '/tmp/data.txt')\n if artist == 'kanye':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkanye.h5?alt=media&token=a0b94c61-e696-453d-9a16-110af66f6afd\"\"\"\n if artist == 'nas':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fnas.h5?alt=media&token=037ef224-be5f-4449-a89c-c1897e164289\"\"\"\n if artist == 'biggie':\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fbiggie.h5?alt=media&token=3244a8e2-017c-472f-a66b-7810a198d038'\n )\n if artist == 'jayz':\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fjayz.h5?alt=media&token=500ff44d-60fe-4774-9c85-5ea6f06da81b'\n )\n if artist == 'ross' or artist == 'kendrick' or artist == '50cent':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.h5?alt=media&token=6ceff75d-5a71-49d4-b927-e727888d872f\n \"\"\"\n named = '/tmp/' + artist + '.h5'\n if artist == 'biggie' or artist == '50cent':\n named = '/tmp/kendrick' + '.h5'\n urllib.request.urlretrieve(url, named)\n yuh()\n model = tf.keras.models.load_model(named)\n seed(1)\n input_str = vocab[randint(0, len(vocab))]\n lyricz = []\n for i in range(10):\n lyrics = generateLyrics(model, startString=input_str, temp=0.6)\n temp = lyrics.replace('nigga', 'homie').replace('niggas', 'homies'\n ).replace('nigger', 'homie').replace('niggers', 'homies').replace(\n 'faggot', 'maggot').replace('fag', 'mag').replace('\\r', '')\n lyricz.append(lyrics.replace('nigga', 'homie').replace('\\r', ''))\n input_str = temp.split()[-1]\n return jsonify({'Success': 'It worked', 'Url': ' '.join(lyricz)})\n", "step-3": "<mask token>\nmap(str.strip, corpus_words)\n<mask token>\nprint('Corpus length (in words):', len(corpus_words))\nprint('Unique words in corpus: {}'.format(len(vocab)))\n<mask token>\n\n\ndef yuh():\n corpus_path = '/tmp/data.txt'\n text = open(corpus_path, 'rb').read().decode(encoding='utf-8')\n text = preprocessText(text)\n corpus_words = corpusToList(text)\n map(str.strip, corpus_words)\n vocab = sorted(set(corpus_words))\n print('Corpus length (in words):', len(corpus_words))\n print('Unique words in corpus: {}'.format(len(vocab)))\n word2idx = {u: i for i, u in enumerate(vocab)}\n idx2words = np.array(vocab)\n word_as_int = np.array([word2idx[c] for c in corpus_words])\n seqLength = 10\n examples_per_epoch = len(corpus_words) // (seqLength + 1)\n wordDataset = tf.data.Dataset.from_tensor_slices(word_as_int)\n sequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True)\n\n\ndef preprocessText(text):\n text = text.replace('\\n', ' ').replace('\\t', '')\n processedText = text.lower()\n for char in stopChars:\n processedText = processedText.replace(char, ' ')\n return processedText\n\n\ndef corpusToList(corpus):\n corpusList = [w for w in corpus.split(' ')]\n corpusList = [i for i in corpusList if i]\n return corpusList\n\n\ndef split_input_target(chunk):\n input_text = chunk[:-1]\n target_text = chunk[1:]\n return input_text, target_text\n\n\ndef loss(labels, logits):\n return tf.keras.losses.sparse_categorical_crossentropy(labels, logits,\n from_logits=True)\n\n\ndef generateLyrics(model, startString, temp):\n num_generate = 30\n start_string_list = [w for w in startString.split(' ')]\n input_eval = [word2idx[s] for s in start_string_list]\n input_eval = tf.expand_dims(input_eval, 0)\n text_generated = []\n model.reset_states()\n for i in range(num_generate):\n predictions = model(input_eval)\n predictions = tf.squeeze(predictions, 0)\n predictions = predictions / temp\n predicted_id = tf.random.categorical(predictions, num_samples=1)[-1, 0\n ].numpy()\n input_eval = tf.expand_dims([predicted_id], 0)\n text_generated.append(' ' + idx2words[predicted_id])\n return startString + ''.join(text_generated)\n\n\ndef doSomeWork(artist):\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.txt?alt=media&token=604b7b6c-2ef0-4611-ab6e-a08dd53e99be'\n )\n urllib.request.urlretrieve(url, '/tmp/data.txt')\n if artist == 'kanye':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkanye.h5?alt=media&token=a0b94c61-e696-453d-9a16-110af66f6afd\"\"\"\n if artist == 'nas':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fnas.h5?alt=media&token=037ef224-be5f-4449-a89c-c1897e164289\"\"\"\n if artist == 'biggie':\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fbiggie.h5?alt=media&token=3244a8e2-017c-472f-a66b-7810a198d038'\n )\n if artist == 'jayz':\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fjayz.h5?alt=media&token=500ff44d-60fe-4774-9c85-5ea6f06da81b'\n )\n if artist == 'ross' or artist == 'kendrick' or artist == '50cent':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.h5?alt=media&token=6ceff75d-5a71-49d4-b927-e727888d872f\n \"\"\"\n named = '/tmp/' + artist + '.h5'\n if artist == 'biggie' or artist == '50cent':\n named = '/tmp/kendrick' + '.h5'\n urllib.request.urlretrieve(url, named)\n yuh()\n model = tf.keras.models.load_model(named)\n seed(1)\n input_str = vocab[randint(0, len(vocab))]\n lyricz = []\n for i in range(10):\n lyrics = generateLyrics(model, startString=input_str, temp=0.6)\n temp = lyrics.replace('nigga', 'homie').replace('niggas', 'homies'\n ).replace('nigger', 'homie').replace('niggers', 'homies').replace(\n 'faggot', 'maggot').replace('fag', 'mag').replace('\\r', '')\n lyricz.append(lyrics.replace('nigga', 'homie').replace('\\r', ''))\n input_str = temp.split()[-1]\n return jsonify({'Success': 'It worked', 'Url': ' '.join(lyricz)})\n", "step-4": "<mask token>\nstopChars = [',', '(', ')', '.', '-', '[', ']', '\"']\ncorpus_path = '/tmp/data.txt'\ntext = open(corpus_path, 'rb').read().decode(encoding='utf-8')\ntext = preprocessText(text)\ncorpus_words = corpusToList(text)\nmap(str.strip, corpus_words)\nvocab = sorted(set(corpus_words))\nprint('Corpus length (in words):', len(corpus_words))\nprint('Unique words in corpus: {}'.format(len(vocab)))\nword2idx = {u: i for i, u in enumerate(vocab)}\nidx2words = np.array(vocab)\nword_as_int = np.array([word2idx[c] for c in corpus_words])\nseqLength = 10\nexamples_per_epoch = len(corpus_words) // (seqLength + 1)\nwordDataset = tf.data.Dataset.from_tensor_slices(word_as_int)\nsequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True)\n\n\ndef yuh():\n corpus_path = '/tmp/data.txt'\n text = open(corpus_path, 'rb').read().decode(encoding='utf-8')\n text = preprocessText(text)\n corpus_words = corpusToList(text)\n map(str.strip, corpus_words)\n vocab = sorted(set(corpus_words))\n print('Corpus length (in words):', len(corpus_words))\n print('Unique words in corpus: {}'.format(len(vocab)))\n word2idx = {u: i for i, u in enumerate(vocab)}\n idx2words = np.array(vocab)\n word_as_int = np.array([word2idx[c] for c in corpus_words])\n seqLength = 10\n examples_per_epoch = len(corpus_words) // (seqLength + 1)\n wordDataset = tf.data.Dataset.from_tensor_slices(word_as_int)\n sequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True)\n\n\ndef preprocessText(text):\n text = text.replace('\\n', ' ').replace('\\t', '')\n processedText = text.lower()\n for char in stopChars:\n processedText = processedText.replace(char, ' ')\n return processedText\n\n\ndef corpusToList(corpus):\n corpusList = [w for w in corpus.split(' ')]\n corpusList = [i for i in corpusList if i]\n return corpusList\n\n\ndef split_input_target(chunk):\n input_text = chunk[:-1]\n target_text = chunk[1:]\n return input_text, target_text\n\n\ndef loss(labels, logits):\n return tf.keras.losses.sparse_categorical_crossentropy(labels, logits,\n from_logits=True)\n\n\ndef generateLyrics(model, startString, temp):\n num_generate = 30\n start_string_list = [w for w in startString.split(' ')]\n input_eval = [word2idx[s] for s in start_string_list]\n input_eval = tf.expand_dims(input_eval, 0)\n text_generated = []\n model.reset_states()\n for i in range(num_generate):\n predictions = model(input_eval)\n predictions = tf.squeeze(predictions, 0)\n predictions = predictions / temp\n predicted_id = tf.random.categorical(predictions, num_samples=1)[-1, 0\n ].numpy()\n input_eval = tf.expand_dims([predicted_id], 0)\n text_generated.append(' ' + idx2words[predicted_id])\n return startString + ''.join(text_generated)\n\n\ndef doSomeWork(artist):\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.txt?alt=media&token=604b7b6c-2ef0-4611-ab6e-a08dd53e99be'\n )\n urllib.request.urlretrieve(url, '/tmp/data.txt')\n if artist == 'kanye':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkanye.h5?alt=media&token=a0b94c61-e696-453d-9a16-110af66f6afd\"\"\"\n if artist == 'nas':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fnas.h5?alt=media&token=037ef224-be5f-4449-a89c-c1897e164289\"\"\"\n if artist == 'biggie':\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fbiggie.h5?alt=media&token=3244a8e2-017c-472f-a66b-7810a198d038'\n )\n if artist == 'jayz':\n url = (\n 'https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fjayz.h5?alt=media&token=500ff44d-60fe-4774-9c85-5ea6f06da81b'\n )\n if artist == 'ross' or artist == 'kendrick' or artist == '50cent':\n url = \"\"\"\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.h5?alt=media&token=6ceff75d-5a71-49d4-b927-e727888d872f\n \"\"\"\n named = '/tmp/' + artist + '.h5'\n if artist == 'biggie' or artist == '50cent':\n named = '/tmp/kendrick' + '.h5'\n urllib.request.urlretrieve(url, named)\n yuh()\n model = tf.keras.models.load_model(named)\n seed(1)\n input_str = vocab[randint(0, len(vocab))]\n lyricz = []\n for i in range(10):\n lyrics = generateLyrics(model, startString=input_str, temp=0.6)\n temp = lyrics.replace('nigga', 'homie').replace('niggas', 'homies'\n ).replace('nigger', 'homie').replace('niggers', 'homies').replace(\n 'faggot', 'maggot').replace('fag', 'mag').replace('\\r', '')\n lyricz.append(lyrics.replace('nigga', 'homie').replace('\\r', ''))\n input_str = temp.split()[-1]\n return jsonify({'Success': 'It worked', 'Url': ' '.join(lyricz)})\n", "step-5": "# The project is based on Tensorflow's Text Generation with RNN tutorial\n# Copyright Petros Demetrakopoulos 2020\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport time\n# The project is based on Tensorflow's Text Generation with RNN tutorial\n# Copyright Petros Demetrakopoulos 2020\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport time\nfrom random import seed\nfrom random import randint\nimport sys\nimport urllib.request\n\nstopChars = [',', '(', ')', '.', '-', '[', ']', '\"']\n\n\ncorpus_path = \"/tmp/data.txt\"\ntext = open(corpus_path, 'rb').read().decode(encoding='utf-8')\ntext = preprocessText(text)\ncorpus_words = corpusToList(text)\nmap(str.strip, corpus_words) # trim words\n\nvocab = sorted(set(corpus_words))\nprint('Corpus length (in words):', len(corpus_words))\nprint('Unique words in corpus: {}'.format(len(vocab)))\n\n\nword2idx = {u: i for i, u in enumerate(vocab)}\nidx2words = np.array(vocab)\nword_as_int = np.array([word2idx[c] for c in corpus_words])\n# The maximum length sentence we want for a single input in words\nseqLength = 10\nexamples_per_epoch = len(corpus_words)//(seqLength + 1)\n\n# Create training examples / targets\nwordDataset = tf.data.Dataset.from_tensor_slices(word_as_int)\n\n# generating batches of 10 words each\nsequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True)\n\ndef yuh(): \n corpus_path = \"/tmp/data.txt\"\n text = open(corpus_path, 'rb').read().decode(encoding='utf-8')\n text = preprocessText(text)\n corpus_words = corpusToList(text)\n map(str.strip, corpus_words) # trim words\n\n vocab = sorted(set(corpus_words))\n print('Corpus length (in words):', len(corpus_words))\n print('Unique words in corpus: {}'.format(len(vocab)))\n\n\n word2idx = {u: i for i, u in enumerate(vocab)}\n idx2words = np.array(vocab)\n word_as_int = np.array([word2idx[c] for c in corpus_words])\n # The maximum length sentence we want for a single input in words\n seqLength = 10\n examples_per_epoch = len(corpus_words)//(seqLength + 1)\n\n# Create training examples / targets\n wordDataset = tf.data.Dataset.from_tensor_slices(word_as_int)\n\n# generating batches of 10 words each\n sequencesOfWords = wordDataset.batch(seqLength + 1, drop_remainder=True)\n\ndef preprocessText(text):\n text = text.replace('\\n', ' ').replace('\\t', '')\n processedText = text.lower()\n for char in stopChars:\n processedText = processedText.replace(char, ' ')\n return processedText\n\n\ndef corpusToList(corpus):\n corpusList = [w for w in corpus.split(' ')]\n # removing empty strings from list\n corpusList = [i for i in corpusList if i]\n return corpusList\n\ndef split_input_target(chunk):\n input_text = chunk[:-1]\n target_text = chunk[1:]\n return input_text, target_text\n\n\ndef loss(labels, logits):\n return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)\n\n\ndef generateLyrics(model, startString, temp):\n # Number of words to generate\n num_generate = 30\n\n # Converting our start string to numbers (vectorizing)\n start_string_list = [w for w in startString.split(' ')]\n input_eval = [word2idx[s] for s in start_string_list]\n input_eval = tf.expand_dims(input_eval, 0)\n\n text_generated = []\n\n model.reset_states()\n for i in range(num_generate):\n predictions = model(input_eval)\n predictions = tf.squeeze(predictions, 0)\n\n predictions = predictions / temp\n predicted_id = tf.random.categorical(\n predictions, num_samples=1)[-1, 0].numpy()\n\n input_eval = tf.expand_dims([predicted_id], 0)\n text_generated.append(' ' + idx2words[predicted_id])\n\n return (startString + ''.join(text_generated))\n\n\ndef doSomeWork(artist):\n url = '''https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.txt?alt=media&token=604b7b6c-2ef0-4611-ab6e-a08dd53e99be'''\n urllib.request.urlretrieve(url, '/tmp/data.txt')\n\n if artist == \"kanye\": \n url = '''\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkanye.h5?alt=media&token=a0b94c61-e696-453d-9a16-110af66f6afd'''\n if artist == \"nas\": \n url = '''\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fnas.h5?alt=media&token=037ef224-be5f-4449-a89c-c1897e164289'''\n if artist == \"biggie\": \n url = '''https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fbiggie.h5?alt=media&token=3244a8e2-017c-472f-a66b-7810a198d038'''\n if artist == \"jayz\": \n url = '''https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fjayz.h5?alt=media&token=500ff44d-60fe-4774-9c85-5ea6f06da81b'''\n if artist == \"ross\" or artist == \"kendrick\" or artist == \"50cent\": \n url = '''\n https://firebasestorage.googleapis.com/v0/b/shellhacks-327117.appspot.com/o/models%2Fkendrick.h5?alt=media&token=6ceff75d-5a71-49d4-b927-e727888d872f\n '''\n \n\n named = \"/tmp/\" + artist + \".h5\"\n if (artist == \"biggie\") or artist == \"50cent\":\n named = \"/tmp/kendrick\" + \".h5\"\n\n urllib.request.urlretrieve(url, named)\n\n\n\n\n yuh()\n \n\n model = tf.keras.models.load_model(named)\n\n seed(1)\n input_str = vocab[randint(0, len(vocab))]\n lyricz = []\n\n for i in range(10):\n lyrics = generateLyrics(model, startString=input_str, temp=0.6)\n temp = lyrics.replace(\"nigga\", \"homie\").replace(\"niggas\", \"homies\").replace(\"nigger\", \"homie\").replace(\n \"niggers\", \"homies\").replace(\"faggot\", \"maggot\").replace(\"fag\", \"mag\").replace('\\r', '')\n lyricz.append(lyrics.replace(\"nigga\", \"homie\").replace('\\r', ''))\n input_str = temp.split()[-1]\n\n return jsonify({\n \"Success\": \"It worked\",\n \"Url\": \" \".join(lyricz)\n })\n", "step-ids": [ 6, 7, 8, 9, 11 ] }
[ 6, 7, 8, 9, 11 ]
class CustomPrinter(object): def __init__(self, val): self.val = val def to_string(self): res = "{" for m in xrange(64): res += hex(int(self.val[m])) if m != 63: res += ", " res += " }" return res def lookup_type(val): if str(val.type) == 'unsigned char [64]': return CustomPrinter(val) return None gdb.pretty_printers.append(lookup_type)
normal
{ "blob_id": "4d5b2ed016cfc6740c3ee5397c894fabc1bec73f", "index": 6963, "step-1": "class CustomPrinter(object):\n <mask token>\n\n def to_string(self):\n res = '{'\n for m in xrange(64):\n res += hex(int(self.val[m]))\n if m != 63:\n res += ', '\n res += ' }'\n return res\n\n\n<mask token>\n", "step-2": "class CustomPrinter(object):\n\n def __init__(self, val):\n self.val = val\n\n def to_string(self):\n res = '{'\n for m in xrange(64):\n res += hex(int(self.val[m]))\n if m != 63:\n res += ', '\n res += ' }'\n return res\n\n\n<mask token>\n", "step-3": "class CustomPrinter(object):\n\n def __init__(self, val):\n self.val = val\n\n def to_string(self):\n res = '{'\n for m in xrange(64):\n res += hex(int(self.val[m]))\n if m != 63:\n res += ', '\n res += ' }'\n return res\n\n\ndef lookup_type(val):\n if str(val.type) == 'unsigned char [64]':\n return CustomPrinter(val)\n return None\n\n\n<mask token>\n", "step-4": "class CustomPrinter(object):\n\n def __init__(self, val):\n self.val = val\n\n def to_string(self):\n res = '{'\n for m in xrange(64):\n res += hex(int(self.val[m]))\n if m != 63:\n res += ', '\n res += ' }'\n return res\n\n\ndef lookup_type(val):\n if str(val.type) == 'unsigned char [64]':\n return CustomPrinter(val)\n return None\n\n\ngdb.pretty_printers.append(lookup_type)\n", "step-5": "class CustomPrinter(object):\n def __init__(self, val):\n self.val = val\n\n def to_string(self):\n res = \"{\"\n for m in xrange(64):\n res += hex(int(self.val[m]))\n if m != 63:\n res += \", \"\n res += \" }\"\n return res\n\n\ndef lookup_type(val):\n if str(val.type) == 'unsigned char [64]':\n return CustomPrinter(val)\n return None\n\n\ngdb.pretty_printers.append(lookup_type)\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
# -*- coding:utf-8 -*- """ 逆波兰表达式,中缀表达式可以对应一棵二叉树,逆波兰表达式即该二叉树后续遍历的结果。 """ def isOperator(c): return c == '+' or c == '-' or c == '*' or c == '/' def reversePolishNotation(p): stack = list() for cur in p: if not isOperator(cur): stack.append(cur) else: b = float(stack.pop()) a = float(stack.pop()) if cur == '+': stack.append(a + b) elif cur == '-': stack.append(a - b) elif cur == '*': stack.append(a * b) elif cur == '/': stack.append(a / b) return stack[-1] if __name__ == '__main__': p = ['2', '1', '+', '3', '*'] print reversePolishNotation(p)
normal
{ "blob_id": "93a47d6ba1f699d881f0d22c4775433e4a451890", "index": 6168, "step-1": "# -*- coding:utf-8 -*-\n\n\"\"\"\n逆波兰表达式,中缀表达式可以对应一棵二叉树,逆波兰表达式即该二叉树后续遍历的结果。\n\"\"\"\n\ndef isOperator(c):\n return c == '+' or c == '-' or c == '*' or c == '/'\n\n\ndef reversePolishNotation(p):\n stack = list()\n for cur in p:\n if not isOperator(cur):\n stack.append(cur)\n else:\n b = float(stack.pop())\n a = float(stack.pop())\n if cur == '+':\n stack.append(a + b)\n elif cur == '-':\n stack.append(a - b)\n elif cur == '*':\n stack.append(a * b)\n elif cur == '/':\n stack.append(a / b)\n return stack[-1]\n\n\nif __name__ == '__main__':\n p = ['2', '1', '+', '3', '*']\n print reversePolishNotation(p)", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> class Cuneiform(pp.unicode_set): <|reserved_special_token_0|> _ranges: List[Tuple[int, ...]] = [(66432, 66517), (73728, 74751), ( 74752, 74879)] <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Cuneiform(pp.unicode_set): """Unicode set for Cuneiform Character Range""" _ranges: List[Tuple[int, ...]] = [(66432, 66517), (73728, 74751), ( 74752, 74879)] <|reserved_special_token_0|> rvalue <<= fn_call | ident | str_expr | pp.common.number <|reserved_special_token_0|> script.parseString(cuneiform_hello_world).pprint(width=40) <|reserved_special_token_0|> ident.add_parse_action(lambda t: names_map.get(t[0], t[0])) def_.add_parse_action(lambda : 'def') print(""" convert Cuneiform Python to executable Python""") <|reserved_special_token_0|> print('=================\n' + cuneiform_hello_world.strip() + """ ================= """ + transformed + """ ================= """) print('# run transformed Python') exec(transformed) <|reserved_special_token_1|> <|reserved_special_token_0|> class Cuneiform(pp.unicode_set): """Unicode set for Cuneiform Character Range""" _ranges: List[Tuple[int, ...]] = [(66432, 66517), (73728, 74751), ( 74752, 74879)] <|reserved_special_token_0|> LPAR, RPAR, COLON, EQ = map(pp.Suppress, '():=') def_ = pp.Keyword('𒁴𒈫', ident_chars=Cuneiform.identbodychars).set_name('def') any_keyword = def_ ident = ~any_keyword + pp.Word(Cuneiform.identchars, Cuneiform. identbodychars, asKeyword=True) str_expr = pp.infix_notation(pp.QuotedString('"') | pp.common.integer, [( '*', 2, pp.OpAssoc.LEFT), ('+', 2, pp.OpAssoc.LEFT)]) rvalue = pp.Forward() fn_call = (ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR)).set_name( 'fn_call') rvalue <<= fn_call | ident | str_expr | pp.common.number assignment_stmt = ident + EQ + rvalue stmt = pp.Group(fn_call | assignment_stmt).set_name('stmt') fn_def = pp.Group(def_ + ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR ) + COLON).set_name('fn_def') fn_body = pp.IndentedBlock(stmt).set_name('fn_body') fn_expr = pp.Group(fn_def + pp.Group(fn_body)) script = fn_expr[...] + stmt[...] cuneiform_hello_world = """ 𒁴𒈫 𒀄𒂖𒆷𒁎(): 𒀁 = "𒀄𒂖𒆷𒁎, 𒍟𒁎𒉿𒆷𒀳!\\n" * 3 𒄑𒉿𒅔𒋫(𒀁) 𒀄𒂖𒆷𒁎()""" script.parseString(cuneiform_hello_world).pprint(width=40) names_map = {'𒄑𒉿𒅔𒋫': 'print'} ident.add_parse_action(lambda t: names_map.get(t[0], t[0])) def_.add_parse_action(lambda : 'def') print(""" convert Cuneiform Python to executable Python""") transformed = (def_ | ident).ignore(pp.quoted_string).transform_string( cuneiform_hello_world).strip() print('=================\n' + cuneiform_hello_world.strip() + """ ================= """ + transformed + """ ================= """) print('# run transformed Python') exec(transformed) <|reserved_special_token_1|> from typing import List, Tuple import pyparsing as pp class Cuneiform(pp.unicode_set): """Unicode set for Cuneiform Character Range""" _ranges: List[Tuple[int, ...]] = [(66432, 66517), (73728, 74751), ( 74752, 74879)] <|reserved_special_token_0|> LPAR, RPAR, COLON, EQ = map(pp.Suppress, '():=') def_ = pp.Keyword('𒁴𒈫', ident_chars=Cuneiform.identbodychars).set_name('def') any_keyword = def_ ident = ~any_keyword + pp.Word(Cuneiform.identchars, Cuneiform. identbodychars, asKeyword=True) str_expr = pp.infix_notation(pp.QuotedString('"') | pp.common.integer, [( '*', 2, pp.OpAssoc.LEFT), ('+', 2, pp.OpAssoc.LEFT)]) rvalue = pp.Forward() fn_call = (ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR)).set_name( 'fn_call') rvalue <<= fn_call | ident | str_expr | pp.common.number assignment_stmt = ident + EQ + rvalue stmt = pp.Group(fn_call | assignment_stmt).set_name('stmt') fn_def = pp.Group(def_ + ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR ) + COLON).set_name('fn_def') fn_body = pp.IndentedBlock(stmt).set_name('fn_body') fn_expr = pp.Group(fn_def + pp.Group(fn_body)) script = fn_expr[...] + stmt[...] cuneiform_hello_world = """ 𒁴𒈫 𒀄𒂖𒆷𒁎(): 𒀁 = "𒀄𒂖𒆷𒁎, 𒍟𒁎𒉿𒆷𒀳!\\n" * 3 𒄑𒉿𒅔𒋫(𒀁) 𒀄𒂖𒆷𒁎()""" script.parseString(cuneiform_hello_world).pprint(width=40) names_map = {'𒄑𒉿𒅔𒋫': 'print'} ident.add_parse_action(lambda t: names_map.get(t[0], t[0])) def_.add_parse_action(lambda : 'def') print(""" convert Cuneiform Python to executable Python""") transformed = (def_ | ident).ignore(pp.quoted_string).transform_string( cuneiform_hello_world).strip() print('=================\n' + cuneiform_hello_world.strip() + """ ================= """ + transformed + """ ================= """) print('# run transformed Python') exec(transformed) <|reserved_special_token_1|> # # cuneiform_python.py # # Example showing how to create a custom Unicode set for parsing # # Copyright Paul McGuire, 2021 # from typing import List, Tuple import pyparsing as pp class Cuneiform(pp.unicode_set): """Unicode set for Cuneiform Character Range""" _ranges: List[Tuple[int, ...]] = [ (0x10380, 0x103d5), (0x12000, 0x123FF), (0x12400, 0x1247F), ] # list out all valid identifier characters # print(Cuneiform.identchars) """ Simple Cuneiform Python language transformer Define Cuneiform "words" print: 𒄑𒉿𒅔𒋫 hello: 𒀄𒂖𒆷𒁎 world: 𒍟𒁎𒉿𒆷𒀳 def: 𒁴𒈫 """ # uncomment to show parse-time debugging # pp.enable_diag(pp.Diagnostics.enable_debug_on_named_expressions) # define a MINIMAL Python parser LPAR, RPAR, COLON, EQ = map(pp.Suppress, "():=") def_ = pp.Keyword("𒁴𒈫", ident_chars=Cuneiform.identbodychars).set_name("def") any_keyword = def_ ident = (~any_keyword) + pp.Word( Cuneiform.identchars, Cuneiform.identbodychars, asKeyword=True ) str_expr = pp.infix_notation( pp.QuotedString('"') | pp.common.integer, [ ("*", 2, pp.OpAssoc.LEFT), ("+", 2, pp.OpAssoc.LEFT), ], ) rvalue = pp.Forward() fn_call = (ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR)).set_name("fn_call") rvalue <<= fn_call | ident | str_expr | pp.common.number assignment_stmt = ident + EQ + rvalue stmt = pp.Group(fn_call | assignment_stmt).set_name("stmt") fn_def = pp.Group( def_ + ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR) + COLON ).set_name("fn_def") fn_body = pp.IndentedBlock(stmt).set_name("fn_body") fn_expr = pp.Group(fn_def + pp.Group(fn_body)) script = fn_expr[...] + stmt[...] # parse some Python written in Cuneiform cuneiform_hello_world = r""" 𒁴𒈫 𒀄𒂖𒆷𒁎(): 𒀁 = "𒀄𒂖𒆷𒁎, 𒍟𒁎𒉿𒆷𒀳!\n" * 3 𒄑𒉿𒅔𒋫(𒀁) 𒀄𒂖𒆷𒁎()""" script.parseString(cuneiform_hello_world).pprint(width=40) # use transform_string to convert keywords and builtins to runnable Python names_map = { "𒄑𒉿𒅔𒋫": "print", } ident.add_parse_action(lambda t: names_map.get(t[0], t[0])) def_.add_parse_action(lambda: "def") print("\nconvert Cuneiform Python to executable Python") transformed = ( # always put ident last (def_ | ident) .ignore(pp.quoted_string) .transform_string(cuneiform_hello_world) .strip() ) print( "=================\n" + cuneiform_hello_world.strip() + "\n=================\n" + transformed + "\n=================\n" ) print("# run transformed Python") exec(transformed)
flexible
{ "blob_id": "bc1aefd0b0a87b80a10cecf00407b4608a6902b5", "index": 3897, "step-1": "<mask token>\n\n\nclass Cuneiform(pp.unicode_set):\n <mask token>\n _ranges: List[Tuple[int, ...]] = [(66432, 66517), (73728, 74751), (\n 74752, 74879)]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Cuneiform(pp.unicode_set):\n \"\"\"Unicode set for Cuneiform Character Range\"\"\"\n _ranges: List[Tuple[int, ...]] = [(66432, 66517), (73728, 74751), (\n 74752, 74879)]\n\n\n<mask token>\nrvalue <<= fn_call | ident | str_expr | pp.common.number\n<mask token>\nscript.parseString(cuneiform_hello_world).pprint(width=40)\n<mask token>\nident.add_parse_action(lambda t: names_map.get(t[0], t[0]))\ndef_.add_parse_action(lambda : 'def')\nprint(\"\"\"\nconvert Cuneiform Python to executable Python\"\"\")\n<mask token>\nprint('=================\\n' + cuneiform_hello_world.strip() +\n \"\"\"\n=================\n\"\"\" + transformed + \"\"\"\n=================\n\"\"\")\nprint('# run transformed Python')\nexec(transformed)\n", "step-3": "<mask token>\n\n\nclass Cuneiform(pp.unicode_set):\n \"\"\"Unicode set for Cuneiform Character Range\"\"\"\n _ranges: List[Tuple[int, ...]] = [(66432, 66517), (73728, 74751), (\n 74752, 74879)]\n\n\n<mask token>\nLPAR, RPAR, COLON, EQ = map(pp.Suppress, '():=')\ndef_ = pp.Keyword('𒁴𒈫', ident_chars=Cuneiform.identbodychars).set_name('def')\nany_keyword = def_\nident = ~any_keyword + pp.Word(Cuneiform.identchars, Cuneiform.\n identbodychars, asKeyword=True)\nstr_expr = pp.infix_notation(pp.QuotedString('\"') | pp.common.integer, [(\n '*', 2, pp.OpAssoc.LEFT), ('+', 2, pp.OpAssoc.LEFT)])\nrvalue = pp.Forward()\nfn_call = (ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR)).set_name(\n 'fn_call')\nrvalue <<= fn_call | ident | str_expr | pp.common.number\nassignment_stmt = ident + EQ + rvalue\nstmt = pp.Group(fn_call | assignment_stmt).set_name('stmt')\nfn_def = pp.Group(def_ + ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR\n ) + COLON).set_name('fn_def')\nfn_body = pp.IndentedBlock(stmt).set_name('fn_body')\nfn_expr = pp.Group(fn_def + pp.Group(fn_body))\nscript = fn_expr[...] + stmt[...]\ncuneiform_hello_world = \"\"\"\n𒁴𒈫 𒀄𒂖𒆷𒁎():\n 𒀁 = \"𒀄𒂖𒆷𒁎, 𒍟𒁎𒉿𒆷𒀳!\\\\n\" * 3\n 𒄑𒉿𒅔𒋫(𒀁)\n\n𒀄𒂖𒆷𒁎()\"\"\"\nscript.parseString(cuneiform_hello_world).pprint(width=40)\nnames_map = {'𒄑𒉿𒅔𒋫': 'print'}\nident.add_parse_action(lambda t: names_map.get(t[0], t[0]))\ndef_.add_parse_action(lambda : 'def')\nprint(\"\"\"\nconvert Cuneiform Python to executable Python\"\"\")\ntransformed = (def_ | ident).ignore(pp.quoted_string).transform_string(\n cuneiform_hello_world).strip()\nprint('=================\\n' + cuneiform_hello_world.strip() +\n \"\"\"\n=================\n\"\"\" + transformed + \"\"\"\n=================\n\"\"\")\nprint('# run transformed Python')\nexec(transformed)\n", "step-4": "from typing import List, Tuple\nimport pyparsing as pp\n\n\nclass Cuneiform(pp.unicode_set):\n \"\"\"Unicode set for Cuneiform Character Range\"\"\"\n _ranges: List[Tuple[int, ...]] = [(66432, 66517), (73728, 74751), (\n 74752, 74879)]\n\n\n<mask token>\nLPAR, RPAR, COLON, EQ = map(pp.Suppress, '():=')\ndef_ = pp.Keyword('𒁴𒈫', ident_chars=Cuneiform.identbodychars).set_name('def')\nany_keyword = def_\nident = ~any_keyword + pp.Word(Cuneiform.identchars, Cuneiform.\n identbodychars, asKeyword=True)\nstr_expr = pp.infix_notation(pp.QuotedString('\"') | pp.common.integer, [(\n '*', 2, pp.OpAssoc.LEFT), ('+', 2, pp.OpAssoc.LEFT)])\nrvalue = pp.Forward()\nfn_call = (ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR)).set_name(\n 'fn_call')\nrvalue <<= fn_call | ident | str_expr | pp.common.number\nassignment_stmt = ident + EQ + rvalue\nstmt = pp.Group(fn_call | assignment_stmt).set_name('stmt')\nfn_def = pp.Group(def_ + ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR\n ) + COLON).set_name('fn_def')\nfn_body = pp.IndentedBlock(stmt).set_name('fn_body')\nfn_expr = pp.Group(fn_def + pp.Group(fn_body))\nscript = fn_expr[...] + stmt[...]\ncuneiform_hello_world = \"\"\"\n𒁴𒈫 𒀄𒂖𒆷𒁎():\n 𒀁 = \"𒀄𒂖𒆷𒁎, 𒍟𒁎𒉿𒆷𒀳!\\\\n\" * 3\n 𒄑𒉿𒅔𒋫(𒀁)\n\n𒀄𒂖𒆷𒁎()\"\"\"\nscript.parseString(cuneiform_hello_world).pprint(width=40)\nnames_map = {'𒄑𒉿𒅔𒋫': 'print'}\nident.add_parse_action(lambda t: names_map.get(t[0], t[0]))\ndef_.add_parse_action(lambda : 'def')\nprint(\"\"\"\nconvert Cuneiform Python to executable Python\"\"\")\ntransformed = (def_ | ident).ignore(pp.quoted_string).transform_string(\n cuneiform_hello_world).strip()\nprint('=================\\n' + cuneiform_hello_world.strip() +\n \"\"\"\n=================\n\"\"\" + transformed + \"\"\"\n=================\n\"\"\")\nprint('# run transformed Python')\nexec(transformed)\n", "step-5": "#\n# cuneiform_python.py\n#\n# Example showing how to create a custom Unicode set for parsing\n#\n# Copyright Paul McGuire, 2021\n#\nfrom typing import List, Tuple\nimport pyparsing as pp\n\n\nclass Cuneiform(pp.unicode_set):\n \"\"\"Unicode set for Cuneiform Character Range\"\"\"\n\n _ranges: List[Tuple[int, ...]] = [\n (0x10380, 0x103d5),\n (0x12000, 0x123FF),\n (0x12400, 0x1247F),\n ]\n\n\n# list out all valid identifier characters\n# print(Cuneiform.identchars)\n\n\n\"\"\"\nSimple Cuneiform Python language transformer\n\nDefine Cuneiform \"words\"\n print: 𒄑𒉿𒅔𒋫\n hello: 𒀄𒂖𒆷𒁎\n world: 𒍟𒁎𒉿𒆷𒀳\n def: 𒁴𒈫\n\"\"\"\n\n# uncomment to show parse-time debugging\n# pp.enable_diag(pp.Diagnostics.enable_debug_on_named_expressions)\n\n# define a MINIMAL Python parser\nLPAR, RPAR, COLON, EQ = map(pp.Suppress, \"():=\")\ndef_ = pp.Keyword(\"𒁴𒈫\", ident_chars=Cuneiform.identbodychars).set_name(\"def\")\nany_keyword = def_\nident = (~any_keyword) + pp.Word(\n Cuneiform.identchars, Cuneiform.identbodychars, asKeyword=True\n)\nstr_expr = pp.infix_notation(\n pp.QuotedString('\"') | pp.common.integer,\n [\n (\"*\", 2, pp.OpAssoc.LEFT),\n (\"+\", 2, pp.OpAssoc.LEFT),\n ],\n)\n\nrvalue = pp.Forward()\nfn_call = (ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR)).set_name(\"fn_call\")\n\nrvalue <<= fn_call | ident | str_expr | pp.common.number\nassignment_stmt = ident + EQ + rvalue\n\nstmt = pp.Group(fn_call | assignment_stmt).set_name(\"stmt\")\n\nfn_def = pp.Group(\n def_ + ident + pp.Group(LPAR + pp.Optional(rvalue) + RPAR) + COLON\n).set_name(\"fn_def\")\nfn_body = pp.IndentedBlock(stmt).set_name(\"fn_body\")\nfn_expr = pp.Group(fn_def + pp.Group(fn_body))\n\nscript = fn_expr[...] + stmt[...]\n\n\n# parse some Python written in Cuneiform\ncuneiform_hello_world = r\"\"\"\n𒁴𒈫 𒀄𒂖𒆷𒁎():\n 𒀁 = \"𒀄𒂖𒆷𒁎, 𒍟𒁎𒉿𒆷𒀳!\\n\" * 3\n 𒄑𒉿𒅔𒋫(𒀁)\n\n𒀄𒂖𒆷𒁎()\"\"\"\nscript.parseString(cuneiform_hello_world).pprint(width=40)\n\n\n# use transform_string to convert keywords and builtins to runnable Python\nnames_map = {\n \"𒄑𒉿𒅔𒋫\": \"print\",\n}\nident.add_parse_action(lambda t: names_map.get(t[0], t[0]))\ndef_.add_parse_action(lambda: \"def\")\n\nprint(\"\\nconvert Cuneiform Python to executable Python\")\ntransformed = (\n # always put ident last\n (def_ | ident)\n .ignore(pp.quoted_string)\n .transform_string(cuneiform_hello_world)\n .strip()\n)\nprint(\n \"=================\\n\"\n + cuneiform_hello_world.strip()\n + \"\\n=================\\n\"\n + transformed\n + \"\\n=================\\n\"\n)\nprint(\"# run transformed Python\")\nexec(transformed)\n", "step-ids": [ 1, 3, 4, 5, 6 ] }
[ 1, 3, 4, 5, 6 ]
#!/usr/bin/python #_*_coding:utf-8_*_ import random def main(): source = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ." words = source.strip().split(" ") new_str = list() for word in words: if len(word) > 4: shuffled_char = random.sample(list(word[1:-1]), len(list(word[1:-1]))) new_str.append(word[:1] + "".join(shuffled_char) + word[-1:]) else: new_str.append(word) print " ".join(new_str) if __name__ == "__main__": main()
normal
{ "blob_id": "14b98186fbc9c275cea3c042cdb4899f6d0c54c6", "index": 3419, "step-1": "#!/usr/bin/python\n#_*_coding:utf-8_*_\n\nimport random\n\ndef main():\n source = \"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .\"\n words = source.strip().split(\" \")\n new_str = list()\n for word in words:\n if len(word) > 4:\n shuffled_char = random.sample(list(word[1:-1]), len(list(word[1:-1])))\n new_str.append(word[:1] + \"\".join(shuffled_char) + word[-1:])\n else:\n new_str.append(word)\n print \" \".join(new_str)\n\n\nif __name__ == \"__main__\":\n main()\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/python import platform from numpy import ctypeslib,empty,array,exp,ascontiguousarray,zeros,asfortranarray from ctypes import c_float,c_double,c_int from time import time def resize(img,scale): """ downsample img to scale """ sdims=img.shape datatype=c_double if img.dtype!=datatype: print "Error the image must be of doubles!" raise RuntimeError if scale>1.0: print "Invalid scaling factor!" raise RuntimeError img = asfortranarray(img,c_double) # make array continguous try: mresize = ctypeslib.load_library("libresize.so",".") except: print "Unable to load resize library" raise RuntimeError #use two times the 1d resize to get a 2d resize fresize = mresize.resize1dtran fresize.restype = None fresize.argtypes = [ ctypeslib.ndpointer(dtype=datatype, ndim=3), c_int,ctypeslib.ndpointer(dtype=datatype, ndim=3), c_int, c_int , c_int ] ddims = [int(round(sdims[0]*scale)),int(round(sdims[1]*scale)),sdims[2]]; mxdst = zeros((ddims), dtype=datatype) tmp = zeros((ddims[0],sdims[1],sdims[2]), dtype=datatype) img1=img t1=time() fresize(img1, sdims[0], tmp, ddims[0], sdims[1], sdims[2]); fresize(tmp, sdims[1], mxdst, ddims[1], ddims[0], sdims[2]); t2=time() return mxdst.reshape(ddims[2],ddims[1],ddims[0]).T if __name__ == "__main__": from numpy.random import random_integers from time import time from pylab import imread,figure,imshow from ctypes import c_float,c_double,c_int img=imread("test.png").astype(c_double) imshow(img) img1=resize(img,0.25) figure() imshow(img1)
normal
{ "blob_id": "816f4cfe98f5e5b23f2c8f9f42c5f3ed8458042f", "index": 3700, "step-1": "#!/usr/bin/python \n\nimport platform\nfrom numpy import ctypeslib,empty,array,exp,ascontiguousarray,zeros,asfortranarray\nfrom ctypes import c_float,c_double,c_int\nfrom time import time\n\ndef resize(img,scale):\n \"\"\"\n downsample img to scale \n \"\"\"\n sdims=img.shape\n datatype=c_double\n if img.dtype!=datatype:\n print \"Error the image must be of doubles!\"\n raise RuntimeError\n\n if scale>1.0:\n print \"Invalid scaling factor!\"\n raise RuntimeError \n \n img = asfortranarray(img,c_double) # make array continguous\n \n try:\n mresize = ctypeslib.load_library(\"libresize.so\",\".\") \n except:\n print \"Unable to load resize library\"\n raise RuntimeError\n \n #use two times the 1d resize to get a 2d resize\n fresize = mresize.resize1dtran\n fresize.restype = None\n fresize.argtypes = [ ctypeslib.ndpointer(dtype=datatype, ndim=3), c_int,ctypeslib.ndpointer(dtype=datatype, ndim=3), c_int, c_int , c_int ]\n ddims = [int(round(sdims[0]*scale)),int(round(sdims[1]*scale)),sdims[2]];\n mxdst = zeros((ddims), dtype=datatype)\n tmp = zeros((ddims[0],sdims[1],sdims[2]), dtype=datatype)\n img1=img\n t1=time()\n fresize(img1, sdims[0], tmp, ddims[0], sdims[1], sdims[2]);\n fresize(tmp, sdims[1], mxdst, ddims[1], ddims[0], sdims[2]);\n t2=time()\n return mxdst.reshape(ddims[2],ddims[1],ddims[0]).T\n\n\nif __name__ == \"__main__\":\n from numpy.random import random_integers\n from time import time\n from pylab import imread,figure,imshow\n from ctypes import c_float,c_double,c_int\n \n img=imread(\"test.png\").astype(c_double)\n imshow(img)\n img1=resize(img,0.25)\n figure()\n imshow(img1)\n\n \n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/env python #coding:utf-8 """ Author: Wusf --<wushifan221@gmail.com> Purpose: Created: 2016/2/29 """ import os,sys,sqlite3 MyQtLibPath = os.path.abspath("D:\\MyQuantLib\\") sys.path.append(MyQtLibPath) import PCA.PCA_For_Stat_Arb2 as pca import pandas as pd import numpy as np import time def ComputeZScores(begDate,endDate,computeZScore,paramsDict,mark): v = paramsDict['EigenNum'] varPecent = paramsDict['VarExplained'] corrSampleDays = paramsDict['CorrMatSampleDays'] regressSampleDays = paramsDict['RegressSampleDays'] ouSampleDays = paramsDict['OUFitSampleDays'] ifDeTrend = paramsDict['IfDeTrend'] ifAdjustReturnByVol = paramsDict['IfAdjRetByVol'] days = [] score=pd.DataFrame() score_adj = pd.DataFrame() revsD=pd.DataFrame() rsqrd=pd.DataFrame() significantEigNum = [] c = 0 for i in range(600,len(computeZScore.trdDay)): scoreDate = computeZScore.trdDay[i] if scoreDate>=begDate and scoreDate<endDate: c+=1 tm1 = time.time() k = 1 for i in range(600,len(computeZScore.trdDay)): scoreDate = computeZScore.trdDay[i] if scoreDate>=begDate and scoreDate<endDate: if k==1 or i%1==0: reEstCorrDay = computeZScore.trdDay[i] computeZScore.GenEigenPort(reEstCorrDay,v,varPecent,corrSampleDays,0.05) print "Re estimate correlation matrix and process PCA" computeZScore.RegressOnEigenFactor(scoreDate,regressSampleDays,ifAdjustReturnByVol,winsorize=0) res = computeZScore.OUFitAndCalcZScore(ouSampleDays,ifDeTrend) significantEigNum.append(computeZScore.significantEigNum) _score = res[0].loc['score'].to_frame(scoreDate).transpose() _scoreAdj = res[0].loc['score_adj'].to_frame(scoreDate).transpose() _revsD = res[0].loc['period'].to_frame(scoreDate).transpose() _rsqrd = res[1].to_frame(scoreDate).transpose() score = score.append(_score) score_adj=score_adj.append(_scoreAdj) revsD = revsD.append(_revsD) rsqrd = rsqrd.append(_rsqrd) k+=1 tm2 = time.time() deltaT = int((tm2-tm1)/k*(c-k)) print "Generating zscore,date:{},paras:{}|{}|{}|{}......{}s left".format(scoreDate,v,varPecent,corrSampleDays,regressSampleDays,deltaT) score.to_csv("ZScores{}.csv".format(mark)) score_adj.to_csv("ZScores_adj{}.csv".format(mark)) revsD.to_csv("ReversePerid{}.csv".format(mark)) rsqrd.to_csv("RegressionRSquared{}.csv".format(mark)) np.savetxt("sigEigNum{}.csv".format(mark), np.array(significantEigNum), delimiter=",") if __name__=="__main__": computeZScore = pca.PCA_For_Stat_Arb("MktData\\MktData_Wind_CICC.db", 1,"20050104") computeZScore.LoadDataIntoTimeSeries("000300","000300",1) begDate = "20080101" endDate = "20160310" params1 = {} params1['EigenNum']=0 params1['VarExplained']=0.60 params1['CorrMatSampleDays']=100 params1['RegressSampleDays']=40 params1['OUFitSampleDays']=40 params1['IfDeTrend']=0 params1['IfAdjRetByVol']=0 params2 = {} params2['EigenNum']=0 params2['VarExplained']=0.60 params2['CorrMatSampleDays']=80 params2['RegressSampleDays']=40 params2['OUFitSampleDays']=40 params2['IfDeTrend']=0 params2['IfAdjRetByVol']=0 params3 = {} params3['EigenNum']=0 params3['VarExplained']=0.60 params3['CorrMatSampleDays']=60 params3['RegressSampleDays']=40 params3['OUFitSampleDays']=40 params3['IfDeTrend']=0 params3['IfAdjRetByVol']=0 params4 = {} params4['EigenNum']=0 params4['VarExplained']=0.60 params4['CorrMatSampleDays']=40 params4['RegressSampleDays']=40 params4['OUFitSampleDays']=40 params4['IfDeTrend']=0 params4['IfAdjRetByVol']=0 params5 = {} params5['EigenNum']=0 params5['VarExplained']=0.65 params5['CorrMatSampleDays']=60 params5['RegressSampleDays']=40 params5['OUFitSampleDays']=40 params5['IfDeTrend']=0 params5['IfAdjRetByVol']=0 params6 = {} params6['EigenNum']=0 params6['VarExplained']=0.60 params6['CorrMatSampleDays']=60 params6['RegressSampleDays']=40 params6['OUFitSampleDays']=40 params6['IfDeTrend']=1 params6['IfAdjRetByVol']=0 params7 = {} params7['EigenNum']=0 params7['VarExplained']=0.60 params7['CorrMatSampleDays']=60 params7['RegressSampleDays']=60 params7['OUFitSampleDays']=60 params7['IfDeTrend']=0 params7['IfAdjRetByVol']=0 ComputeZScores(begDate,endDate,computeZScore,params1,'Params301') ComputeZScores(begDate,endDate,computeZScore,params2,'Params302') ComputeZScores(begDate,endDate,computeZScore,params3,'Params303') ComputeZScores(begDate,endDate,computeZScore,params4,'Params304') ComputeZScores(begDate,endDate,computeZScore,params5,'Params305') ComputeZScores(begDate,endDate,computeZScore,params6,'Params306') ComputeZScores(begDate,endDate,computeZScore,params7,'Params307')
normal
{ "blob_id": "70cda2d6d3928cd8008daf221cd78665a9b05eea", "index": 7064, "step-1": "#!/usr/bin/env python\n#coding:utf-8\n\"\"\"\n Author: Wusf --<wushifan221@gmail.com>\n Purpose: \n Created: 2016/2/29\n\"\"\"\n\nimport os,sys,sqlite3\nMyQtLibPath = os.path.abspath(\"D:\\\\MyQuantLib\\\\\")\nsys.path.append(MyQtLibPath)\n\nimport PCA.PCA_For_Stat_Arb2 as pca\nimport pandas as pd\nimport numpy as np\nimport time\n\n\ndef ComputeZScores(begDate,endDate,computeZScore,paramsDict,mark):\n\n v = paramsDict['EigenNum']\n varPecent = paramsDict['VarExplained']\n corrSampleDays = paramsDict['CorrMatSampleDays']\n regressSampleDays = paramsDict['RegressSampleDays']\n ouSampleDays = paramsDict['OUFitSampleDays']\n ifDeTrend = paramsDict['IfDeTrend']\n ifAdjustReturnByVol = paramsDict['IfAdjRetByVol']\n\n \n days = []\n score=pd.DataFrame()\n score_adj = pd.DataFrame()\n revsD=pd.DataFrame()\n rsqrd=pd.DataFrame()\n significantEigNum = []\n \n c = 0\n for i in range(600,len(computeZScore.trdDay)):\n scoreDate = computeZScore.trdDay[i]\n if scoreDate>=begDate and scoreDate<endDate: \n c+=1\n \n tm1 = time.time()\n k = 1\n for i in range(600,len(computeZScore.trdDay)):\n scoreDate = computeZScore.trdDay[i]\n if scoreDate>=begDate and scoreDate<endDate:\n if k==1 or i%1==0:\n reEstCorrDay = computeZScore.trdDay[i]\n computeZScore.GenEigenPort(reEstCorrDay,v,varPecent,corrSampleDays,0.05)\n print \"Re estimate correlation matrix and process PCA\"\n computeZScore.RegressOnEigenFactor(scoreDate,regressSampleDays,ifAdjustReturnByVol,winsorize=0)\n res = computeZScore.OUFitAndCalcZScore(ouSampleDays,ifDeTrend)\n significantEigNum.append(computeZScore.significantEigNum)\n _score = res[0].loc['score'].to_frame(scoreDate).transpose()\n _scoreAdj = res[0].loc['score_adj'].to_frame(scoreDate).transpose()\n _revsD = res[0].loc['period'].to_frame(scoreDate).transpose()\n _rsqrd = res[1].to_frame(scoreDate).transpose()\n score = score.append(_score)\n score_adj=score_adj.append(_scoreAdj)\n revsD = revsD.append(_revsD)\n rsqrd = rsqrd.append(_rsqrd)\n k+=1\n tm2 = time.time()\n deltaT = int((tm2-tm1)/k*(c-k))\n print \"Generating zscore,date:{},paras:{}|{}|{}|{}......{}s left\".format(scoreDate,v,varPecent,corrSampleDays,regressSampleDays,deltaT)\n score.to_csv(\"ZScores{}.csv\".format(mark))\n score_adj.to_csv(\"ZScores_adj{}.csv\".format(mark))\n revsD.to_csv(\"ReversePerid{}.csv\".format(mark))\n rsqrd.to_csv(\"RegressionRSquared{}.csv\".format(mark))\n np.savetxt(\"sigEigNum{}.csv\".format(mark), np.array(significantEigNum), delimiter=\",\")\n\n\n\n\nif __name__==\"__main__\":\n computeZScore = pca.PCA_For_Stat_Arb(\"MktData\\\\MktData_Wind_CICC.db\", 1,\"20050104\")\n computeZScore.LoadDataIntoTimeSeries(\"000300\",\"000300\",1) \n begDate = \"20080101\"\n endDate = \"20160310\"\n params1 = {}\n params1['EigenNum']=0\n params1['VarExplained']=0.60\n params1['CorrMatSampleDays']=100\n params1['RegressSampleDays']=40\n params1['OUFitSampleDays']=40\n params1['IfDeTrend']=0\n params1['IfAdjRetByVol']=0\n \n params2 = {}\n params2['EigenNum']=0\n params2['VarExplained']=0.60\n params2['CorrMatSampleDays']=80\n params2['RegressSampleDays']=40\n params2['OUFitSampleDays']=40\n params2['IfDeTrend']=0\n params2['IfAdjRetByVol']=0 \n \n params3 = {}\n params3['EigenNum']=0\n params3['VarExplained']=0.60\n params3['CorrMatSampleDays']=60\n params3['RegressSampleDays']=40\n params3['OUFitSampleDays']=40\n params3['IfDeTrend']=0\n params3['IfAdjRetByVol']=0 \n \n params4 = {}\n params4['EigenNum']=0\n params4['VarExplained']=0.60\n params4['CorrMatSampleDays']=40\n params4['RegressSampleDays']=40\n params4['OUFitSampleDays']=40\n params4['IfDeTrend']=0\n params4['IfAdjRetByVol']=0 \n \n params5 = {}\n params5['EigenNum']=0\n params5['VarExplained']=0.65\n params5['CorrMatSampleDays']=60\n params5['RegressSampleDays']=40\n params5['OUFitSampleDays']=40\n params5['IfDeTrend']=0\n params5['IfAdjRetByVol']=0 \n \n params6 = {}\n params6['EigenNum']=0\n params6['VarExplained']=0.60\n params6['CorrMatSampleDays']=60\n params6['RegressSampleDays']=40\n params6['OUFitSampleDays']=40\n params6['IfDeTrend']=1\n params6['IfAdjRetByVol']=0 \n \n params7 = {}\n params7['EigenNum']=0\n params7['VarExplained']=0.60\n params7['CorrMatSampleDays']=60\n params7['RegressSampleDays']=60\n params7['OUFitSampleDays']=60\n params7['IfDeTrend']=0\n params7['IfAdjRetByVol']=0 \n \n \n ComputeZScores(begDate,endDate,computeZScore,params1,'Params301')\n ComputeZScores(begDate,endDate,computeZScore,params2,'Params302')\n ComputeZScores(begDate,endDate,computeZScore,params3,'Params303')\n ComputeZScores(begDate,endDate,computeZScore,params4,'Params304')\n ComputeZScores(begDate,endDate,computeZScore,params5,'Params305')\n ComputeZScores(begDate,endDate,computeZScore,params6,'Params306')\n ComputeZScores(begDate,endDate,computeZScore,params7,'Params307')\n\n\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> class CNN(object): def __init__(self): self.model = tf.keras.Sequential([tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 1)), tf.keras.layers. MaxPool2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras. layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers. MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation ='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers. Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense( 512, activation='relu'), tf.keras.layers.Dense(1, activation= 'sigmoid')]) self.last_training_history = {} def print_model_info(self): print(self.model.summary()) def get_model(self): return self.model def load_weights(self, filepath='model.h5'): self.model.load_weights(filepath) self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) def load_last_training_history(self, filepath='result.pk'): with open(filepath, 'rb') as f: self.last_training_history = pickle.load(f) def get_last_training_history(self): return self.last_training_history def plot_last_training_history(self, save_plot=False): for key in self.last_training_history: y = self.last_training_history[key] plt.plot([(i + 1) for i in range(len(y))], y, label=key) plt.legend() plt.grid() plt.xlabel('epoch') if save_plot: plt.savefig('training_history.png', dpi=300) else: plt.show() def train(self, directory, epochs=100, save_model=False, save_history=False ): train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale =1.0 / 255, rotation_range=20, width_shift_range=0.15, height_shift_range=0.15, shear_range=0.15, zoom_range=0.15, fill_mode='nearest', horizontal_flip=True, vertical_flip=False, brightness_range=None, channel_shift_range=0) test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale =1.0 / 255) train_generator = train_datagen.flow_from_directory(directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') test_generator = test_datagen.flow_from_directory(directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) history = self.model.fit(train_generator, epochs=epochs, validation_data=test_generator) if save_model: self.model.save('model.h5') if save_history: with open('result.pk', 'wb') as f: pickle.dump(history.history, f) self.last_training_history = history.history return history.history def predict_directory(self, directory, probabilities=True): if directory[-1] != '\\' and directory[-1] != '/': directory += '/' predictions = {} onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os. path.join(directory, f))] for image_file in onlyfiles: img = tf.keras.preprocessing.image.load_img(directory + image_file, target_size=(150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img) x = x.reshape((1,) + x.shape) x = x / 255 y = self.model.predict(x)[0][0] if probabilities: predictions[image_file] = y else: predictions[image_file] = y > 0.5 return predictions def predict_single_image(self, file_url): self.load_weights() self.load_last_training_history() file_name = 'image.jpg' urllib.request.urlretrieve(file_url, file_name) img = tf.keras.preprocessing.image.load_img(file_name, target_size= (150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img) x = x.reshape((1,) + x.shape) x = x / 255 prediction = self.model.predict(x)[0][0] is_default_image = prediction < 0.5 print(prediction) os.remove(file_name) return json.dumps(True) if is_default_image else json.dumps(False) <|reserved_special_token_0|> def split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05): assert train_size + test_size + val_size == 1 assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1 subdirs = next(os.walk(directory))[1] if train_size > 0: os.mkdir(directory + '/train') for subdir in subdirs: os.mkdir(directory + '/train/' + subdir) if test_size > 0: os.mkdir(directory + '/test') for subdir in subdirs: os.mkdir(directory + '/test/' + subdir) if val_size > 0: os.mkdir(directory + '/val') for subdir in subdirs: os.mkdir(directory + '/val/' + subdir) pathlist = Path(directory).rglob('*.*') for path in pathlist: instance_path = str(path) instance_properties = instance_path.split('/' ) if '/' in instance_path else instance_path.split('\\') instance_name = instance_properties[-1] instance_class = instance_properties[-2] r = random.random() if r < val_size: subfolder = '/val/' elif r < test_size + val_size: subfolder = '/test/' else: subfolder = '/train/' os.rename(instance_path, '/'.join(instance_properties[:-2]) + subfolder + instance_class + '/' + instance_name) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class CNN(object): def __init__(self): self.model = tf.keras.Sequential([tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 1)), tf.keras.layers. MaxPool2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras. layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers. MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation ='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers. Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense( 512, activation='relu'), tf.keras.layers.Dense(1, activation= 'sigmoid')]) self.last_training_history = {} def print_model_info(self): print(self.model.summary()) def get_model(self): return self.model def load_weights(self, filepath='model.h5'): self.model.load_weights(filepath) self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) def load_last_training_history(self, filepath='result.pk'): with open(filepath, 'rb') as f: self.last_training_history = pickle.load(f) def get_last_training_history(self): return self.last_training_history def plot_last_training_history(self, save_plot=False): for key in self.last_training_history: y = self.last_training_history[key] plt.plot([(i + 1) for i in range(len(y))], y, label=key) plt.legend() plt.grid() plt.xlabel('epoch') if save_plot: plt.savefig('training_history.png', dpi=300) else: plt.show() def train(self, directory, epochs=100, save_model=False, save_history=False ): train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale =1.0 / 255, rotation_range=20, width_shift_range=0.15, height_shift_range=0.15, shear_range=0.15, zoom_range=0.15, fill_mode='nearest', horizontal_flip=True, vertical_flip=False, brightness_range=None, channel_shift_range=0) test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale =1.0 / 255) train_generator = train_datagen.flow_from_directory(directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') test_generator = test_datagen.flow_from_directory(directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) history = self.model.fit(train_generator, epochs=epochs, validation_data=test_generator) if save_model: self.model.save('model.h5') if save_history: with open('result.pk', 'wb') as f: pickle.dump(history.history, f) self.last_training_history = history.history return history.history def predict_directory(self, directory, probabilities=True): if directory[-1] != '\\' and directory[-1] != '/': directory += '/' predictions = {} onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os. path.join(directory, f))] for image_file in onlyfiles: img = tf.keras.preprocessing.image.load_img(directory + image_file, target_size=(150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img) x = x.reshape((1,) + x.shape) x = x / 255 y = self.model.predict(x)[0][0] if probabilities: predictions[image_file] = y else: predictions[image_file] = y > 0.5 return predictions def predict_single_image(self, file_url): self.load_weights() self.load_last_training_history() file_name = 'image.jpg' urllib.request.urlretrieve(file_url, file_name) img = tf.keras.preprocessing.image.load_img(file_name, target_size= (150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img) x = x.reshape((1,) + x.shape) x = x / 255 prediction = self.model.predict(x)[0][0] is_default_image = prediction < 0.5 print(prediction) os.remove(file_name) return json.dumps(True) if is_default_image else json.dumps(False) def evaluate_on_directory(self, directory): val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale= 1.0 / 255) val_generator = val_datagen.flow_from_directory(directory, target_size= (150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') return self.model.evaluate(val_generator) def split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05): assert train_size + test_size + val_size == 1 assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1 subdirs = next(os.walk(directory))[1] if train_size > 0: os.mkdir(directory + '/train') for subdir in subdirs: os.mkdir(directory + '/train/' + subdir) if test_size > 0: os.mkdir(directory + '/test') for subdir in subdirs: os.mkdir(directory + '/test/' + subdir) if val_size > 0: os.mkdir(directory + '/val') for subdir in subdirs: os.mkdir(directory + '/val/' + subdir) pathlist = Path(directory).rglob('*.*') for path in pathlist: instance_path = str(path) instance_properties = instance_path.split('/' ) if '/' in instance_path else instance_path.split('\\') instance_name = instance_properties[-1] instance_class = instance_properties[-2] r = random.random() if r < val_size: subfolder = '/val/' elif r < test_size + val_size: subfolder = '/test/' else: subfolder = '/train/' os.rename(instance_path, '/'.join(instance_properties[:-2]) + subfolder + instance_class + '/' + instance_name) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class CNN(object): def __init__(self): self.model = tf.keras.Sequential([tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 1)), tf.keras.layers. MaxPool2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras. layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers. MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation ='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers. Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense( 512, activation='relu'), tf.keras.layers.Dense(1, activation= 'sigmoid')]) self.last_training_history = {} def print_model_info(self): print(self.model.summary()) def get_model(self): return self.model def load_weights(self, filepath='model.h5'): self.model.load_weights(filepath) self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) def load_last_training_history(self, filepath='result.pk'): with open(filepath, 'rb') as f: self.last_training_history = pickle.load(f) def get_last_training_history(self): return self.last_training_history def plot_last_training_history(self, save_plot=False): for key in self.last_training_history: y = self.last_training_history[key] plt.plot([(i + 1) for i in range(len(y))], y, label=key) plt.legend() plt.grid() plt.xlabel('epoch') if save_plot: plt.savefig('training_history.png', dpi=300) else: plt.show() def train(self, directory, epochs=100, save_model=False, save_history=False ): train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale =1.0 / 255, rotation_range=20, width_shift_range=0.15, height_shift_range=0.15, shear_range=0.15, zoom_range=0.15, fill_mode='nearest', horizontal_flip=True, vertical_flip=False, brightness_range=None, channel_shift_range=0) test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale =1.0 / 255) train_generator = train_datagen.flow_from_directory(directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') test_generator = test_datagen.flow_from_directory(directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) history = self.model.fit(train_generator, epochs=epochs, validation_data=test_generator) if save_model: self.model.save('model.h5') if save_history: with open('result.pk', 'wb') as f: pickle.dump(history.history, f) self.last_training_history = history.history return history.history def predict_directory(self, directory, probabilities=True): if directory[-1] != '\\' and directory[-1] != '/': directory += '/' predictions = {} onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os. path.join(directory, f))] for image_file in onlyfiles: img = tf.keras.preprocessing.image.load_img(directory + image_file, target_size=(150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img) x = x.reshape((1,) + x.shape) x = x / 255 y = self.model.predict(x)[0][0] if probabilities: predictions[image_file] = y else: predictions[image_file] = y > 0.5 return predictions def predict_single_image(self, file_url): self.load_weights() self.load_last_training_history() file_name = 'image.jpg' urllib.request.urlretrieve(file_url, file_name) img = tf.keras.preprocessing.image.load_img(file_name, target_size= (150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img) x = x.reshape((1,) + x.shape) x = x / 255 prediction = self.model.predict(x)[0][0] is_default_image = prediction < 0.5 print(prediction) os.remove(file_name) return json.dumps(True) if is_default_image else json.dumps(False) def evaluate_on_directory(self, directory): val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale= 1.0 / 255) val_generator = val_datagen.flow_from_directory(directory, target_size= (150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') return self.model.evaluate(val_generator) def split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05): assert train_size + test_size + val_size == 1 assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1 subdirs = next(os.walk(directory))[1] if train_size > 0: os.mkdir(directory + '/train') for subdir in subdirs: os.mkdir(directory + '/train/' + subdir) if test_size > 0: os.mkdir(directory + '/test') for subdir in subdirs: os.mkdir(directory + '/test/' + subdir) if val_size > 0: os.mkdir(directory + '/val') for subdir in subdirs: os.mkdir(directory + '/val/' + subdir) pathlist = Path(directory).rglob('*.*') for path in pathlist: instance_path = str(path) instance_properties = instance_path.split('/' ) if '/' in instance_path else instance_path.split('\\') instance_name = instance_properties[-1] instance_class = instance_properties[-2] r = random.random() if r < val_size: subfolder = '/val/' elif r < test_size + val_size: subfolder = '/test/' else: subfolder = '/train/' os.rename(instance_path, '/'.join(instance_properties[:-2]) + subfolder + instance_class + '/' + instance_name) if __name__ == '__main__': cnn = CNN() cnn.load_weights() cnn.load_last_training_history() cnn.print_model_info() <|reserved_special_token_1|> import json import os import pickle import random import urllib.request from pathlib import Path import tensorflow as tf from matplotlib import pyplot as plt class CNN(object): def __init__(self): self.model = tf.keras.Sequential([tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 1)), tf.keras.layers. MaxPool2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras. layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers. MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation ='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers. Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense( 512, activation='relu'), tf.keras.layers.Dense(1, activation= 'sigmoid')]) self.last_training_history = {} def print_model_info(self): print(self.model.summary()) def get_model(self): return self.model def load_weights(self, filepath='model.h5'): self.model.load_weights(filepath) self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) def load_last_training_history(self, filepath='result.pk'): with open(filepath, 'rb') as f: self.last_training_history = pickle.load(f) def get_last_training_history(self): return self.last_training_history def plot_last_training_history(self, save_plot=False): for key in self.last_training_history: y = self.last_training_history[key] plt.plot([(i + 1) for i in range(len(y))], y, label=key) plt.legend() plt.grid() plt.xlabel('epoch') if save_plot: plt.savefig('training_history.png', dpi=300) else: plt.show() def train(self, directory, epochs=100, save_model=False, save_history=False ): train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale =1.0 / 255, rotation_range=20, width_shift_range=0.15, height_shift_range=0.15, shear_range=0.15, zoom_range=0.15, fill_mode='nearest', horizontal_flip=True, vertical_flip=False, brightness_range=None, channel_shift_range=0) test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale =1.0 / 255) train_generator = train_datagen.flow_from_directory(directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') test_generator = test_datagen.flow_from_directory(directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') self.model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) history = self.model.fit(train_generator, epochs=epochs, validation_data=test_generator) if save_model: self.model.save('model.h5') if save_history: with open('result.pk', 'wb') as f: pickle.dump(history.history, f) self.last_training_history = history.history return history.history def predict_directory(self, directory, probabilities=True): if directory[-1] != '\\' and directory[-1] != '/': directory += '/' predictions = {} onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os. path.join(directory, f))] for image_file in onlyfiles: img = tf.keras.preprocessing.image.load_img(directory + image_file, target_size=(150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img) x = x.reshape((1,) + x.shape) x = x / 255 y = self.model.predict(x)[0][0] if probabilities: predictions[image_file] = y else: predictions[image_file] = y > 0.5 return predictions def predict_single_image(self, file_url): self.load_weights() self.load_last_training_history() file_name = 'image.jpg' urllib.request.urlretrieve(file_url, file_name) img = tf.keras.preprocessing.image.load_img(file_name, target_size= (150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img) x = x.reshape((1,) + x.shape) x = x / 255 prediction = self.model.predict(x)[0][0] is_default_image = prediction < 0.5 print(prediction) os.remove(file_name) return json.dumps(True) if is_default_image else json.dumps(False) def evaluate_on_directory(self, directory): val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale= 1.0 / 255) val_generator = val_datagen.flow_from_directory(directory, target_size= (150, 150), batch_size=32, color_mode='grayscale', class_mode='binary') return self.model.evaluate(val_generator) def split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05): assert train_size + test_size + val_size == 1 assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1 subdirs = next(os.walk(directory))[1] if train_size > 0: os.mkdir(directory + '/train') for subdir in subdirs: os.mkdir(directory + '/train/' + subdir) if test_size > 0: os.mkdir(directory + '/test') for subdir in subdirs: os.mkdir(directory + '/test/' + subdir) if val_size > 0: os.mkdir(directory + '/val') for subdir in subdirs: os.mkdir(directory + '/val/' + subdir) pathlist = Path(directory).rglob('*.*') for path in pathlist: instance_path = str(path) instance_properties = instance_path.split('/' ) if '/' in instance_path else instance_path.split('\\') instance_name = instance_properties[-1] instance_class = instance_properties[-2] r = random.random() if r < val_size: subfolder = '/val/' elif r < test_size + val_size: subfolder = '/test/' else: subfolder = '/train/' os.rename(instance_path, '/'.join(instance_properties[:-2]) + subfolder + instance_class + '/' + instance_name) if __name__ == '__main__': cnn = CNN() cnn.load_weights() cnn.load_last_training_history() cnn.print_model_info() <|reserved_special_token_1|> import json import os import pickle import random import urllib.request from pathlib import Path import tensorflow as tf from matplotlib import pyplot as plt class CNN(object): def __init__(self): self.model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 1)), tf.keras.layers.MaxPool2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid') ]) self.last_training_history = {} def print_model_info(self): print(self.model.summary()) def get_model(self): return self.model def load_weights(self, filepath='model.h5'): self.model.load_weights(filepath) self.model.compile( optimizer='adam', loss='binary_crossentropy', metrics=['acc'] ) def load_last_training_history(self, filepath='result.pk'): with open(filepath, 'rb') as f: self.last_training_history = pickle.load(f) def get_last_training_history(self): return self.last_training_history def plot_last_training_history(self, save_plot=False): for key in self.last_training_history: y = self.last_training_history[key] plt.plot([i + 1 for i in range(len(y))], y, label=key) plt.legend() plt.grid() plt.xlabel('epoch') if save_plot: plt.savefig('training_history.png', dpi=300) else: plt.show() def train(self, directory, epochs=100, save_model=False, save_history=False): train_datagen = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1. / 255, rotation_range=20, width_shift_range=0.15, height_shift_range=0.15, shear_range=0.15, zoom_range=0.15, fill_mode='nearest', horizontal_flip=True, vertical_flip=False, brightness_range=None, channel_shift_range=0 ) test_datagen = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1. / 255) train_generator = train_datagen.flow_from_directory( directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary' ) test_generator = test_datagen.flow_from_directory( directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary' ) self.model.compile( optimizer='adam', loss='binary_crossentropy', metrics=['acc'] ) history = self.model.fit( train_generator, epochs=epochs, validation_data=test_generator ) if save_model: self.model.save('model.h5') if save_history: with open('result.pk', 'wb') as f: pickle.dump(history.history, f) self.last_training_history = history.history return history.history def predict_directory(self, directory, probabilities=True): if directory[-1] != '\\' and directory[-1] != '/': directory += '/' predictions = {} onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] for image_file in onlyfiles: img = tf.keras.preprocessing.image.load_img(directory + image_file, target_size=(150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img, ) x = x.reshape((1,) + x.shape) x = x / 255 y = self.model.predict(x)[0][0] if probabilities: predictions[image_file] = y else: predictions[image_file] = y > 0.5 return predictions def predict_single_image(self, file_url): self.load_weights() self.load_last_training_history() file_name = "image.jpg" urllib.request.urlretrieve(file_url, file_name) img = tf.keras.preprocessing.image.load_img(file_name, target_size=(150, 150), color_mode='grayscale') x = tf.keras.preprocessing.image.img_to_array(img, ) x = x.reshape((1,) + x.shape) x = x / 255 prediction = self.model.predict(x)[0][0] is_default_image = prediction < 0.5 print(prediction) os.remove(file_name) return json.dumps(True) if is_default_image else json.dumps(False) def evaluate_on_directory(self, directory): val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1. / 255) val_generator = val_datagen.flow_from_directory( directory, target_size=(150, 150), batch_size=32, color_mode='grayscale', class_mode='binary' ) return self.model.evaluate(val_generator) def split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05): assert train_size + test_size + val_size == 1 assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1 subdirs = next(os.walk(directory))[1] if train_size > 0: os.mkdir(directory + '/train') for subdir in subdirs: os.mkdir(directory + '/train/' + subdir) if test_size > 0: os.mkdir(directory + '/test') for subdir in subdirs: os.mkdir(directory + '/test/' + subdir) if val_size > 0: os.mkdir(directory + '/val') for subdir in subdirs: os.mkdir(directory + '/val/' + subdir) pathlist = Path(directory).rglob('*.*') for path in pathlist: instance_path = str(path) instance_properties = instance_path.split('/') if '/' in instance_path else instance_path.split('\\') instance_name = instance_properties[-1] instance_class = instance_properties[-2] r = random.random() if r < val_size: subfolder = '/val/' elif r < test_size + val_size: subfolder = '/test/' else: subfolder = '/train/' os.rename(instance_path, '/'.join(instance_properties[:-2]) + subfolder + instance_class + '/' + instance_name) if __name__ == '__main__': cnn = CNN() cnn.load_weights() cnn.load_last_training_history() cnn.print_model_info()
flexible
{ "blob_id": "9535335c70129f997d7b8739444a503d0b984ac8", "index": 9753, "step-1": "<mask token>\n\n\nclass CNN(object):\n\n def __init__(self):\n self.model = tf.keras.Sequential([tf.keras.layers.Conv2D(32, (3, 3),\n activation='relu', input_shape=(150, 150, 1)), tf.keras.layers.\n MaxPool2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3),\n activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.\n layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.\n MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation\n ='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers.\n Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(\n 512, activation='relu'), tf.keras.layers.Dense(1, activation=\n 'sigmoid')])\n self.last_training_history = {}\n\n def print_model_info(self):\n print(self.model.summary())\n\n def get_model(self):\n return self.model\n\n def load_weights(self, filepath='model.h5'):\n self.model.load_weights(filepath)\n self.model.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=['acc'])\n\n def load_last_training_history(self, filepath='result.pk'):\n with open(filepath, 'rb') as f:\n self.last_training_history = pickle.load(f)\n\n def get_last_training_history(self):\n return self.last_training_history\n\n def plot_last_training_history(self, save_plot=False):\n for key in self.last_training_history:\n y = self.last_training_history[key]\n plt.plot([(i + 1) for i in range(len(y))], y, label=key)\n plt.legend()\n plt.grid()\n plt.xlabel('epoch')\n if save_plot:\n plt.savefig('training_history.png', dpi=300)\n else:\n plt.show()\n\n def train(self, directory, epochs=100, save_model=False, save_history=False\n ):\n train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale\n =1.0 / 255, rotation_range=20, width_shift_range=0.15,\n height_shift_range=0.15, shear_range=0.15, zoom_range=0.15,\n fill_mode='nearest', horizontal_flip=True, vertical_flip=False,\n brightness_range=None, channel_shift_range=0)\n test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale\n =1.0 / 255)\n train_generator = train_datagen.flow_from_directory(directory,\n target_size=(150, 150), batch_size=32, color_mode='grayscale',\n class_mode='binary')\n test_generator = test_datagen.flow_from_directory(directory,\n target_size=(150, 150), batch_size=32, color_mode='grayscale',\n class_mode='binary')\n self.model.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=['acc'])\n history = self.model.fit(train_generator, epochs=epochs,\n validation_data=test_generator)\n if save_model:\n self.model.save('model.h5')\n if save_history:\n with open('result.pk', 'wb') as f:\n pickle.dump(history.history, f)\n self.last_training_history = history.history\n return history.history\n\n def predict_directory(self, directory, probabilities=True):\n if directory[-1] != '\\\\' and directory[-1] != '/':\n directory += '/'\n predictions = {}\n onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os.\n path.join(directory, f))]\n for image_file in onlyfiles:\n img = tf.keras.preprocessing.image.load_img(directory +\n image_file, target_size=(150, 150), color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n x = x / 255\n y = self.model.predict(x)[0][0]\n if probabilities:\n predictions[image_file] = y\n else:\n predictions[image_file] = y > 0.5\n return predictions\n\n def predict_single_image(self, file_url):\n self.load_weights()\n self.load_last_training_history()\n file_name = 'image.jpg'\n urllib.request.urlretrieve(file_url, file_name)\n img = tf.keras.preprocessing.image.load_img(file_name, target_size=\n (150, 150), color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n x = x / 255\n prediction = self.model.predict(x)[0][0]\n is_default_image = prediction < 0.5\n print(prediction)\n os.remove(file_name)\n return json.dumps(True) if is_default_image else json.dumps(False)\n\n\n<mask token>\n\n\ndef split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05):\n assert train_size + test_size + val_size == 1\n assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1\n subdirs = next(os.walk(directory))[1]\n if train_size > 0:\n os.mkdir(directory + '/train')\n for subdir in subdirs:\n os.mkdir(directory + '/train/' + subdir)\n if test_size > 0:\n os.mkdir(directory + '/test')\n for subdir in subdirs:\n os.mkdir(directory + '/test/' + subdir)\n if val_size > 0:\n os.mkdir(directory + '/val')\n for subdir in subdirs:\n os.mkdir(directory + '/val/' + subdir)\n pathlist = Path(directory).rglob('*.*')\n for path in pathlist:\n instance_path = str(path)\n instance_properties = instance_path.split('/'\n ) if '/' in instance_path else instance_path.split('\\\\')\n instance_name = instance_properties[-1]\n instance_class = instance_properties[-2]\n r = random.random()\n if r < val_size:\n subfolder = '/val/'\n elif r < test_size + val_size:\n subfolder = '/test/'\n else:\n subfolder = '/train/'\n os.rename(instance_path, '/'.join(instance_properties[:-2]) +\n subfolder + instance_class + '/' + instance_name)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass CNN(object):\n\n def __init__(self):\n self.model = tf.keras.Sequential([tf.keras.layers.Conv2D(32, (3, 3),\n activation='relu', input_shape=(150, 150, 1)), tf.keras.layers.\n MaxPool2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3),\n activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.\n layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.\n MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation\n ='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers.\n Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(\n 512, activation='relu'), tf.keras.layers.Dense(1, activation=\n 'sigmoid')])\n self.last_training_history = {}\n\n def print_model_info(self):\n print(self.model.summary())\n\n def get_model(self):\n return self.model\n\n def load_weights(self, filepath='model.h5'):\n self.model.load_weights(filepath)\n self.model.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=['acc'])\n\n def load_last_training_history(self, filepath='result.pk'):\n with open(filepath, 'rb') as f:\n self.last_training_history = pickle.load(f)\n\n def get_last_training_history(self):\n return self.last_training_history\n\n def plot_last_training_history(self, save_plot=False):\n for key in self.last_training_history:\n y = self.last_training_history[key]\n plt.plot([(i + 1) for i in range(len(y))], y, label=key)\n plt.legend()\n plt.grid()\n plt.xlabel('epoch')\n if save_plot:\n plt.savefig('training_history.png', dpi=300)\n else:\n plt.show()\n\n def train(self, directory, epochs=100, save_model=False, save_history=False\n ):\n train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale\n =1.0 / 255, rotation_range=20, width_shift_range=0.15,\n height_shift_range=0.15, shear_range=0.15, zoom_range=0.15,\n fill_mode='nearest', horizontal_flip=True, vertical_flip=False,\n brightness_range=None, channel_shift_range=0)\n test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale\n =1.0 / 255)\n train_generator = train_datagen.flow_from_directory(directory,\n target_size=(150, 150), batch_size=32, color_mode='grayscale',\n class_mode='binary')\n test_generator = test_datagen.flow_from_directory(directory,\n target_size=(150, 150), batch_size=32, color_mode='grayscale',\n class_mode='binary')\n self.model.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=['acc'])\n history = self.model.fit(train_generator, epochs=epochs,\n validation_data=test_generator)\n if save_model:\n self.model.save('model.h5')\n if save_history:\n with open('result.pk', 'wb') as f:\n pickle.dump(history.history, f)\n self.last_training_history = history.history\n return history.history\n\n def predict_directory(self, directory, probabilities=True):\n if directory[-1] != '\\\\' and directory[-1] != '/':\n directory += '/'\n predictions = {}\n onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os.\n path.join(directory, f))]\n for image_file in onlyfiles:\n img = tf.keras.preprocessing.image.load_img(directory +\n image_file, target_size=(150, 150), color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n x = x / 255\n y = self.model.predict(x)[0][0]\n if probabilities:\n predictions[image_file] = y\n else:\n predictions[image_file] = y > 0.5\n return predictions\n\n def predict_single_image(self, file_url):\n self.load_weights()\n self.load_last_training_history()\n file_name = 'image.jpg'\n urllib.request.urlretrieve(file_url, file_name)\n img = tf.keras.preprocessing.image.load_img(file_name, target_size=\n (150, 150), color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n x = x / 255\n prediction = self.model.predict(x)[0][0]\n is_default_image = prediction < 0.5\n print(prediction)\n os.remove(file_name)\n return json.dumps(True) if is_default_image else json.dumps(False)\n\n\ndef evaluate_on_directory(self, directory):\n val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=\n 1.0 / 255)\n val_generator = val_datagen.flow_from_directory(directory, target_size=\n (150, 150), batch_size=32, color_mode='grayscale', class_mode='binary')\n return self.model.evaluate(val_generator)\n\n\ndef split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05):\n assert train_size + test_size + val_size == 1\n assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1\n subdirs = next(os.walk(directory))[1]\n if train_size > 0:\n os.mkdir(directory + '/train')\n for subdir in subdirs:\n os.mkdir(directory + '/train/' + subdir)\n if test_size > 0:\n os.mkdir(directory + '/test')\n for subdir in subdirs:\n os.mkdir(directory + '/test/' + subdir)\n if val_size > 0:\n os.mkdir(directory + '/val')\n for subdir in subdirs:\n os.mkdir(directory + '/val/' + subdir)\n pathlist = Path(directory).rglob('*.*')\n for path in pathlist:\n instance_path = str(path)\n instance_properties = instance_path.split('/'\n ) if '/' in instance_path else instance_path.split('\\\\')\n instance_name = instance_properties[-1]\n instance_class = instance_properties[-2]\n r = random.random()\n if r < val_size:\n subfolder = '/val/'\n elif r < test_size + val_size:\n subfolder = '/test/'\n else:\n subfolder = '/train/'\n os.rename(instance_path, '/'.join(instance_properties[:-2]) +\n subfolder + instance_class + '/' + instance_name)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass CNN(object):\n\n def __init__(self):\n self.model = tf.keras.Sequential([tf.keras.layers.Conv2D(32, (3, 3),\n activation='relu', input_shape=(150, 150, 1)), tf.keras.layers.\n MaxPool2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3),\n activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.\n layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.\n MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation\n ='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers.\n Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(\n 512, activation='relu'), tf.keras.layers.Dense(1, activation=\n 'sigmoid')])\n self.last_training_history = {}\n\n def print_model_info(self):\n print(self.model.summary())\n\n def get_model(self):\n return self.model\n\n def load_weights(self, filepath='model.h5'):\n self.model.load_weights(filepath)\n self.model.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=['acc'])\n\n def load_last_training_history(self, filepath='result.pk'):\n with open(filepath, 'rb') as f:\n self.last_training_history = pickle.load(f)\n\n def get_last_training_history(self):\n return self.last_training_history\n\n def plot_last_training_history(self, save_plot=False):\n for key in self.last_training_history:\n y = self.last_training_history[key]\n plt.plot([(i + 1) for i in range(len(y))], y, label=key)\n plt.legend()\n plt.grid()\n plt.xlabel('epoch')\n if save_plot:\n plt.savefig('training_history.png', dpi=300)\n else:\n plt.show()\n\n def train(self, directory, epochs=100, save_model=False, save_history=False\n ):\n train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale\n =1.0 / 255, rotation_range=20, width_shift_range=0.15,\n height_shift_range=0.15, shear_range=0.15, zoom_range=0.15,\n fill_mode='nearest', horizontal_flip=True, vertical_flip=False,\n brightness_range=None, channel_shift_range=0)\n test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale\n =1.0 / 255)\n train_generator = train_datagen.flow_from_directory(directory,\n target_size=(150, 150), batch_size=32, color_mode='grayscale',\n class_mode='binary')\n test_generator = test_datagen.flow_from_directory(directory,\n target_size=(150, 150), batch_size=32, color_mode='grayscale',\n class_mode='binary')\n self.model.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=['acc'])\n history = self.model.fit(train_generator, epochs=epochs,\n validation_data=test_generator)\n if save_model:\n self.model.save('model.h5')\n if save_history:\n with open('result.pk', 'wb') as f:\n pickle.dump(history.history, f)\n self.last_training_history = history.history\n return history.history\n\n def predict_directory(self, directory, probabilities=True):\n if directory[-1] != '\\\\' and directory[-1] != '/':\n directory += '/'\n predictions = {}\n onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os.\n path.join(directory, f))]\n for image_file in onlyfiles:\n img = tf.keras.preprocessing.image.load_img(directory +\n image_file, target_size=(150, 150), color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n x = x / 255\n y = self.model.predict(x)[0][0]\n if probabilities:\n predictions[image_file] = y\n else:\n predictions[image_file] = y > 0.5\n return predictions\n\n def predict_single_image(self, file_url):\n self.load_weights()\n self.load_last_training_history()\n file_name = 'image.jpg'\n urllib.request.urlretrieve(file_url, file_name)\n img = tf.keras.preprocessing.image.load_img(file_name, target_size=\n (150, 150), color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n x = x / 255\n prediction = self.model.predict(x)[0][0]\n is_default_image = prediction < 0.5\n print(prediction)\n os.remove(file_name)\n return json.dumps(True) if is_default_image else json.dumps(False)\n\n\ndef evaluate_on_directory(self, directory):\n val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=\n 1.0 / 255)\n val_generator = val_datagen.flow_from_directory(directory, target_size=\n (150, 150), batch_size=32, color_mode='grayscale', class_mode='binary')\n return self.model.evaluate(val_generator)\n\n\ndef split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05):\n assert train_size + test_size + val_size == 1\n assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1\n subdirs = next(os.walk(directory))[1]\n if train_size > 0:\n os.mkdir(directory + '/train')\n for subdir in subdirs:\n os.mkdir(directory + '/train/' + subdir)\n if test_size > 0:\n os.mkdir(directory + '/test')\n for subdir in subdirs:\n os.mkdir(directory + '/test/' + subdir)\n if val_size > 0:\n os.mkdir(directory + '/val')\n for subdir in subdirs:\n os.mkdir(directory + '/val/' + subdir)\n pathlist = Path(directory).rglob('*.*')\n for path in pathlist:\n instance_path = str(path)\n instance_properties = instance_path.split('/'\n ) if '/' in instance_path else instance_path.split('\\\\')\n instance_name = instance_properties[-1]\n instance_class = instance_properties[-2]\n r = random.random()\n if r < val_size:\n subfolder = '/val/'\n elif r < test_size + val_size:\n subfolder = '/test/'\n else:\n subfolder = '/train/'\n os.rename(instance_path, '/'.join(instance_properties[:-2]) +\n subfolder + instance_class + '/' + instance_name)\n\n\nif __name__ == '__main__':\n cnn = CNN()\n cnn.load_weights()\n cnn.load_last_training_history()\n cnn.print_model_info()\n", "step-4": "import json\nimport os\nimport pickle\nimport random\nimport urllib.request\nfrom pathlib import Path\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\n\n\nclass CNN(object):\n\n def __init__(self):\n self.model = tf.keras.Sequential([tf.keras.layers.Conv2D(32, (3, 3),\n activation='relu', input_shape=(150, 150, 1)), tf.keras.layers.\n MaxPool2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3),\n activation='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.\n layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.\n MaxPool2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation\n ='relu'), tf.keras.layers.MaxPool2D(2, 2), tf.keras.layers.\n Flatten(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(\n 512, activation='relu'), tf.keras.layers.Dense(1, activation=\n 'sigmoid')])\n self.last_training_history = {}\n\n def print_model_info(self):\n print(self.model.summary())\n\n def get_model(self):\n return self.model\n\n def load_weights(self, filepath='model.h5'):\n self.model.load_weights(filepath)\n self.model.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=['acc'])\n\n def load_last_training_history(self, filepath='result.pk'):\n with open(filepath, 'rb') as f:\n self.last_training_history = pickle.load(f)\n\n def get_last_training_history(self):\n return self.last_training_history\n\n def plot_last_training_history(self, save_plot=False):\n for key in self.last_training_history:\n y = self.last_training_history[key]\n plt.plot([(i + 1) for i in range(len(y))], y, label=key)\n plt.legend()\n plt.grid()\n plt.xlabel('epoch')\n if save_plot:\n plt.savefig('training_history.png', dpi=300)\n else:\n plt.show()\n\n def train(self, directory, epochs=100, save_model=False, save_history=False\n ):\n train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale\n =1.0 / 255, rotation_range=20, width_shift_range=0.15,\n height_shift_range=0.15, shear_range=0.15, zoom_range=0.15,\n fill_mode='nearest', horizontal_flip=True, vertical_flip=False,\n brightness_range=None, channel_shift_range=0)\n test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale\n =1.0 / 255)\n train_generator = train_datagen.flow_from_directory(directory,\n target_size=(150, 150), batch_size=32, color_mode='grayscale',\n class_mode='binary')\n test_generator = test_datagen.flow_from_directory(directory,\n target_size=(150, 150), batch_size=32, color_mode='grayscale',\n class_mode='binary')\n self.model.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=['acc'])\n history = self.model.fit(train_generator, epochs=epochs,\n validation_data=test_generator)\n if save_model:\n self.model.save('model.h5')\n if save_history:\n with open('result.pk', 'wb') as f:\n pickle.dump(history.history, f)\n self.last_training_history = history.history\n return history.history\n\n def predict_directory(self, directory, probabilities=True):\n if directory[-1] != '\\\\' and directory[-1] != '/':\n directory += '/'\n predictions = {}\n onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os.\n path.join(directory, f))]\n for image_file in onlyfiles:\n img = tf.keras.preprocessing.image.load_img(directory +\n image_file, target_size=(150, 150), color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n x = x / 255\n y = self.model.predict(x)[0][0]\n if probabilities:\n predictions[image_file] = y\n else:\n predictions[image_file] = y > 0.5\n return predictions\n\n def predict_single_image(self, file_url):\n self.load_weights()\n self.load_last_training_history()\n file_name = 'image.jpg'\n urllib.request.urlretrieve(file_url, file_name)\n img = tf.keras.preprocessing.image.load_img(file_name, target_size=\n (150, 150), color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img)\n x = x.reshape((1,) + x.shape)\n x = x / 255\n prediction = self.model.predict(x)[0][0]\n is_default_image = prediction < 0.5\n print(prediction)\n os.remove(file_name)\n return json.dumps(True) if is_default_image else json.dumps(False)\n\n\ndef evaluate_on_directory(self, directory):\n val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=\n 1.0 / 255)\n val_generator = val_datagen.flow_from_directory(directory, target_size=\n (150, 150), batch_size=32, color_mode='grayscale', class_mode='binary')\n return self.model.evaluate(val_generator)\n\n\ndef split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05):\n assert train_size + test_size + val_size == 1\n assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1\n subdirs = next(os.walk(directory))[1]\n if train_size > 0:\n os.mkdir(directory + '/train')\n for subdir in subdirs:\n os.mkdir(directory + '/train/' + subdir)\n if test_size > 0:\n os.mkdir(directory + '/test')\n for subdir in subdirs:\n os.mkdir(directory + '/test/' + subdir)\n if val_size > 0:\n os.mkdir(directory + '/val')\n for subdir in subdirs:\n os.mkdir(directory + '/val/' + subdir)\n pathlist = Path(directory).rglob('*.*')\n for path in pathlist:\n instance_path = str(path)\n instance_properties = instance_path.split('/'\n ) if '/' in instance_path else instance_path.split('\\\\')\n instance_name = instance_properties[-1]\n instance_class = instance_properties[-2]\n r = random.random()\n if r < val_size:\n subfolder = '/val/'\n elif r < test_size + val_size:\n subfolder = '/test/'\n else:\n subfolder = '/train/'\n os.rename(instance_path, '/'.join(instance_properties[:-2]) +\n subfolder + instance_class + '/' + instance_name)\n\n\nif __name__ == '__main__':\n cnn = CNN()\n cnn.load_weights()\n cnn.load_last_training_history()\n cnn.print_model_info()\n", "step-5": "import json\nimport os\nimport pickle\nimport random\nimport urllib.request\nfrom pathlib import Path\n\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\n\n\nclass CNN(object):\n\n def __init__(self):\n self.model = tf.keras.Sequential([\n tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 1)),\n tf.keras.layers.MaxPool2D((2, 2)),\n tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),\n tf.keras.layers.MaxPool2D(2, 2),\n tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),\n tf.keras.layers.MaxPool2D(2, 2),\n tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),\n tf.keras.layers.MaxPool2D(2, 2),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dropout(0.5),\n tf.keras.layers.Dense(512, activation='relu'),\n tf.keras.layers.Dense(1, activation='sigmoid')\n ])\n self.last_training_history = {}\n\n def print_model_info(self):\n print(self.model.summary())\n\n def get_model(self):\n return self.model\n\n def load_weights(self, filepath='model.h5'):\n self.model.load_weights(filepath)\n self.model.compile(\n optimizer='adam',\n loss='binary_crossentropy',\n metrics=['acc']\n )\n\n def load_last_training_history(self, filepath='result.pk'):\n with open(filepath, 'rb') as f:\n self.last_training_history = pickle.load(f)\n\n def get_last_training_history(self):\n return self.last_training_history\n\n def plot_last_training_history(self, save_plot=False):\n for key in self.last_training_history:\n y = self.last_training_history[key]\n plt.plot([i + 1 for i in range(len(y))], y, label=key)\n plt.legend()\n plt.grid()\n plt.xlabel('epoch')\n if save_plot:\n plt.savefig('training_history.png', dpi=300)\n else:\n plt.show()\n\n def train(self, directory, epochs=100, save_model=False, save_history=False):\n train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n rescale=1. / 255,\n rotation_range=20,\n width_shift_range=0.15,\n height_shift_range=0.15,\n shear_range=0.15,\n zoom_range=0.15,\n fill_mode='nearest',\n horizontal_flip=True,\n vertical_flip=False,\n brightness_range=None,\n channel_shift_range=0\n )\n\n test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n rescale=1. / 255) \n\n train_generator = train_datagen.flow_from_directory(\n directory,\n target_size=(150, 150),\n batch_size=32,\n color_mode='grayscale',\n class_mode='binary'\n )\n\n test_generator = test_datagen.flow_from_directory(\n directory,\n target_size=(150, 150),\n batch_size=32,\n color_mode='grayscale',\n class_mode='binary'\n )\n\n self.model.compile(\n optimizer='adam',\n loss='binary_crossentropy',\n metrics=['acc']\n )\n\n history = self.model.fit(\n train_generator,\n epochs=epochs,\n validation_data=test_generator\n )\n\n if save_model:\n self.model.save('model.h5')\n\n if save_history:\n with open('result.pk', 'wb') as f:\n pickle.dump(history.history, f)\n\n self.last_training_history = history.history\n\n return history.history\n\n def predict_directory(self, directory, probabilities=True):\n if directory[-1] != '\\\\' and directory[-1] != '/':\n directory += '/'\n predictions = {}\n onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]\n for image_file in onlyfiles:\n img = tf.keras.preprocessing.image.load_img(directory + image_file, target_size=(150, 150),\n color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img, )\n x = x.reshape((1,) + x.shape)\n x = x / 255\n y = self.model.predict(x)[0][0]\n if probabilities:\n predictions[image_file] = y\n else:\n predictions[image_file] = y > 0.5\n return predictions\n\n def predict_single_image(self, file_url):\n self.load_weights()\n self.load_last_training_history()\n file_name = \"image.jpg\"\n urllib.request.urlretrieve(file_url, file_name)\n img = tf.keras.preprocessing.image.load_img(file_name, target_size=(150, 150),\n color_mode='grayscale')\n x = tf.keras.preprocessing.image.img_to_array(img, )\n x = x.reshape((1,) + x.shape)\n x = x / 255\n prediction = self.model.predict(x)[0][0]\n is_default_image = prediction < 0.5\n print(prediction)\n os.remove(file_name)\n\n return json.dumps(True) if is_default_image else json.dumps(False)\n\n\ndef evaluate_on_directory(self, directory):\n val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1. / 255)\n val_generator = val_datagen.flow_from_directory(\n directory,\n target_size=(150, 150),\n batch_size=32,\n color_mode='grayscale',\n class_mode='binary'\n )\n return self.model.evaluate(val_generator)\n\n\ndef split_directory(directory, train_size=0.75, test_size=0.2, val_size=0.05):\n assert train_size + test_size + val_size == 1\n assert 0 <= train_size <= 1 and 0 <= test_size <= 1 and 0 <= val_size <= 1\n subdirs = next(os.walk(directory))[1]\n if train_size > 0:\n os.mkdir(directory + '/train')\n for subdir in subdirs:\n os.mkdir(directory + '/train/' + subdir)\n if test_size > 0:\n os.mkdir(directory + '/test')\n for subdir in subdirs:\n os.mkdir(directory + '/test/' + subdir)\n if val_size > 0:\n os.mkdir(directory + '/val')\n for subdir in subdirs:\n os.mkdir(directory + '/val/' + subdir)\n pathlist = Path(directory).rglob('*.*')\n for path in pathlist:\n instance_path = str(path)\n instance_properties = instance_path.split('/') if '/' in instance_path else instance_path.split('\\\\')\n instance_name = instance_properties[-1]\n instance_class = instance_properties[-2]\n r = random.random()\n if r < val_size:\n subfolder = '/val/'\n elif r < test_size + val_size:\n subfolder = '/test/'\n else:\n subfolder = '/train/'\n os.rename(instance_path, '/'.join(instance_properties[:-2]) + subfolder + instance_class + '/' + instance_name)\n\n\nif __name__ == '__main__':\n\n cnn = CNN()\n cnn.load_weights()\n cnn.load_last_training_history()\n cnn.print_model_info()\n", "step-ids": [ 12, 13, 14, 15, 16 ] }
[ 12, 13, 14, 15, 16 ]
a=int(input()) s=0 t=0 while(a!=0): t=a%10 s=s+t a=a//10 print(s)
normal
{ "blob_id": "6050e83e73faaf40cbd5455efd3ad01e4e131188", "index": 2587, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile a != 0:\n t = a % 10\n s = s + t\n a = a // 10\nprint(s)\n", "step-3": "a = int(input())\ns = 0\nt = 0\nwhile a != 0:\n t = a % 10\n s = s + t\n a = a // 10\nprint(s)\n", "step-4": "a=int(input())\ns=0\nt=0\nwhile(a!=0):\n t=a%10\n s=s+t\n a=a//10\nprint(s)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print(type(data)) <|reserved_special_token_0|> print(data) <|reserved_special_token_1|> <|reserved_special_token_0|> url = 'http://icanhazdadjoke.com/' response = requests.get(url, headers={'Accept': 'application/json'}) data = response.text print(type(data)) data = response.json() print(data) <|reserved_special_token_1|> import requests url = 'http://icanhazdadjoke.com/' response = requests.get(url, headers={'Accept': 'application/json'}) data = response.text print(type(data)) data = response.json() print(data) <|reserved_special_token_1|> import requests # url="http://www.google.com" # response=requests.get(url) # print(response.status_code) url = "http://icanhazdadjoke.com/" response = requests.get(url, headers={"Accept": "application/json"}) data = response.text print(type(data)) data = response.json() print(data)
flexible
{ "blob_id": "f94894e5d3e6a0ff367911c72f4d863ac32c8baa", "index": 1435, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(type(data))\n<mask token>\nprint(data)\n", "step-3": "<mask token>\nurl = 'http://icanhazdadjoke.com/'\nresponse = requests.get(url, headers={'Accept': 'application/json'})\ndata = response.text\nprint(type(data))\ndata = response.json()\nprint(data)\n", "step-4": "import requests\nurl = 'http://icanhazdadjoke.com/'\nresponse = requests.get(url, headers={'Accept': 'application/json'})\ndata = response.text\nprint(type(data))\ndata = response.json()\nprint(data)\n", "step-5": "import requests\n\n# url=\"http://www.google.com\"\n# response=requests.get(url)\n# print(response.status_code)\n\n\nurl = \"http://icanhazdadjoke.com/\"\nresponse = requests.get(url, headers={\"Accept\": \"application/json\"})\ndata = response.text\nprint(type(data))\ndata = response.json()\nprint(data)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def segment_ts(): ts_len = len(x1) mod = ts_len % window_size rnge = 0 if skip_offset == 0: ts_len = int((ts_len - mod - window_size) / 1) rnge = int(ts_len / window_size) else: ts_len = int(math.ceil((ts_len - window_size) / skip_offset)) rnge = int(ts_len) curr_count = 0 words = list() indices = list() complete_indices = list() for i in range(0, rnge): sub_section = x1[curr_count:curr_count + window_size] sub_section = normalize(sub_section) curr_word = '' chunk_size = int(len(sub_section) / word_lenth) num = 0 curr_letter = '' for j in range(0, word_lenth): chunk = sub_section[num:num + chunk_size] curr_letter = alphabetize_ts(chunk) curr_word += str(curr_letter) complete_indices.append(curr_count) num += chunk_size words.append(curr_word) indices.append(curr_count) temp_list = [] temp_list.append(sub_section) temp_df = pd.DataFrame() temp_df.insert(loc=0, column='sub_section', value=temp_list) temp_df.insert(loc=0, column='keys', value=curr_word) temp_df.insert(loc=0, column='position', value=sorted(sub_section)[ len(sub_section) // 2]) temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section)) temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section)) temp_df.insert(loc=0, column='indices', value=curr_count) curr_count = curr_count + skip_offset - 1 if i == 0: df_sax = temp_df.copy() else: df_sax = df_sax.append(temp_df, ignore_index=True) return words, indices, df_sax <|reserved_special_token_0|> def complete_word(): complete_word = list() complete_indices = indices """ Simillar Words """ complete_word = alphabetize sax = defaultdict(list) for i in range(0, len(complete_word)): if len(complete_word[i]) == word_lenth: sax[complete_word[i]].append(complete_indices[i]) return sax def Compare_Shape(): simillar_word = complete_word() map_keys = defaultdict(list) map_indices = defaultdict(list) for key_i in simillar_word: temp_list = list() temp_list.append(simillar_word.get(key_i)) map_keys[key_i].append(key_i) for key_j in simillar_word: dist = hamming_distance(key_i, key_j) if dist == ham_distance and key_i != key_j: map_keys[key_i].append(key_j) temp_list.append(simillar_word.get(key_j)) else: map_keys[key_i].append([]) tempp = list(itertools.chain(*temp_list)) map_indices[key_i].append(tempp) return map_keys, map_indices <|reserved_special_token_0|> def dtw_test2(): df_dtw_prep = df_sax dtw_df = pd.DataFrame() for k, v in compare_list.items(): v_temp = str(v)[2:-2] v1 = [int(s) for s in v_temp.split(',')] for i in range(0, len(v1) - 1): for j in range(i, len(v1)): if v1[i] != v1[j]: row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]] row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]] sub_section1 = row1.iloc[0]['sub_section'] sub_section2 = row2.iloc[0]['sub_section'] index1 = row1.iloc[0]['indices'] index2 = row2.iloc[0]['indices'] x = np.array(sub_section1).reshape(-1, 1) y = np.array(sub_section2).reshape(-1, 1) euclidean_norm = lambda x, y: np.abs(x - y) dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x, y, dist=euclidean_norm) temp_df = pd.DataFrame([[k, index1, index2, sub_section1, sub_section2, dtw_value]], columns=[ 'keyy', 'index1', 'index2', 'sub_section1', 'sub_section2', 'dtw_value']) dtw_df = dtw_df.append(temp_df, ignore_index=True) return dtw_df <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def segment_ts(): ts_len = len(x1) mod = ts_len % window_size rnge = 0 if skip_offset == 0: ts_len = int((ts_len - mod - window_size) / 1) rnge = int(ts_len / window_size) else: ts_len = int(math.ceil((ts_len - window_size) / skip_offset)) rnge = int(ts_len) curr_count = 0 words = list() indices = list() complete_indices = list() for i in range(0, rnge): sub_section = x1[curr_count:curr_count + window_size] sub_section = normalize(sub_section) curr_word = '' chunk_size = int(len(sub_section) / word_lenth) num = 0 curr_letter = '' for j in range(0, word_lenth): chunk = sub_section[num:num + chunk_size] curr_letter = alphabetize_ts(chunk) curr_word += str(curr_letter) complete_indices.append(curr_count) num += chunk_size words.append(curr_word) indices.append(curr_count) temp_list = [] temp_list.append(sub_section) temp_df = pd.DataFrame() temp_df.insert(loc=0, column='sub_section', value=temp_list) temp_df.insert(loc=0, column='keys', value=curr_word) temp_df.insert(loc=0, column='position', value=sorted(sub_section)[ len(sub_section) // 2]) temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section)) temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section)) temp_df.insert(loc=0, column='indices', value=curr_count) curr_count = curr_count + skip_offset - 1 if i == 0: df_sax = temp_df.copy() else: df_sax = df_sax.append(temp_df, ignore_index=True) return words, indices, df_sax <|reserved_special_token_0|> def complete_word(): complete_word = list() complete_indices = indices """ Simillar Words """ complete_word = alphabetize sax = defaultdict(list) for i in range(0, len(complete_word)): if len(complete_word[i]) == word_lenth: sax[complete_word[i]].append(complete_indices[i]) return sax def Compare_Shape(): simillar_word = complete_word() map_keys = defaultdict(list) map_indices = defaultdict(list) for key_i in simillar_word: temp_list = list() temp_list.append(simillar_word.get(key_i)) map_keys[key_i].append(key_i) for key_j in simillar_word: dist = hamming_distance(key_i, key_j) if dist == ham_distance and key_i != key_j: map_keys[key_i].append(key_j) temp_list.append(simillar_word.get(key_j)) else: map_keys[key_i].append([]) tempp = list(itertools.chain(*temp_list)) map_indices[key_i].append(tempp) return map_keys, map_indices <|reserved_special_token_0|> def dtw_test2(): df_dtw_prep = df_sax dtw_df = pd.DataFrame() for k, v in compare_list.items(): v_temp = str(v)[2:-2] v1 = [int(s) for s in v_temp.split(',')] for i in range(0, len(v1) - 1): for j in range(i, len(v1)): if v1[i] != v1[j]: row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]] row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]] sub_section1 = row1.iloc[0]['sub_section'] sub_section2 = row2.iloc[0]['sub_section'] index1 = row1.iloc[0]['indices'] index2 = row2.iloc[0]['indices'] x = np.array(sub_section1).reshape(-1, 1) y = np.array(sub_section2).reshape(-1, 1) euclidean_norm = lambda x, y: np.abs(x - y) dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x, y, dist=euclidean_norm) temp_df = pd.DataFrame([[k, index1, index2, sub_section1, sub_section2, dtw_value]], columns=[ 'keyy', 'index1', 'index2', 'sub_section1', 'sub_section2', 'dtw_value']) dtw_df = dtw_df.append(temp_df, ignore_index=True) return dtw_df <|reserved_special_token_0|> print('Time: ', stop - start) <|reserved_special_token_1|> <|reserved_special_token_0|> start = timeit.default_timer() data = pd.read_csv('test_data2.csv', sep=',', header=None) x1 = data.iloc[1:, 1].values.flatten() x1 = np.asfarray(x1, float) y_alphabet_size = 4 word_lenth = 3 window_size = round(len(x1) * 10 / 100) skip_offset = round(window_size / 2) ham_distance = 1 epsilon = 1e-06 def segment_ts(): ts_len = len(x1) mod = ts_len % window_size rnge = 0 if skip_offset == 0: ts_len = int((ts_len - mod - window_size) / 1) rnge = int(ts_len / window_size) else: ts_len = int(math.ceil((ts_len - window_size) / skip_offset)) rnge = int(ts_len) curr_count = 0 words = list() indices = list() complete_indices = list() for i in range(0, rnge): sub_section = x1[curr_count:curr_count + window_size] sub_section = normalize(sub_section) curr_word = '' chunk_size = int(len(sub_section) / word_lenth) num = 0 curr_letter = '' for j in range(0, word_lenth): chunk = sub_section[num:num + chunk_size] curr_letter = alphabetize_ts(chunk) curr_word += str(curr_letter) complete_indices.append(curr_count) num += chunk_size words.append(curr_word) indices.append(curr_count) temp_list = [] temp_list.append(sub_section) temp_df = pd.DataFrame() temp_df.insert(loc=0, column='sub_section', value=temp_list) temp_df.insert(loc=0, column='keys', value=curr_word) temp_df.insert(loc=0, column='position', value=sorted(sub_section)[ len(sub_section) // 2]) temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section)) temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section)) temp_df.insert(loc=0, column='indices', value=curr_count) curr_count = curr_count + skip_offset - 1 if i == 0: df_sax = temp_df.copy() else: df_sax = df_sax.append(temp_df, ignore_index=True) return words, indices, df_sax alphabetize, indices, df_sax = segment_ts() <|reserved_special_token_0|> def complete_word(): complete_word = list() complete_indices = indices """ Simillar Words """ complete_word = alphabetize sax = defaultdict(list) for i in range(0, len(complete_word)): if len(complete_word[i]) == word_lenth: sax[complete_word[i]].append(complete_indices[i]) return sax def Compare_Shape(): simillar_word = complete_word() map_keys = defaultdict(list) map_indices = defaultdict(list) for key_i in simillar_word: temp_list = list() temp_list.append(simillar_word.get(key_i)) map_keys[key_i].append(key_i) for key_j in simillar_word: dist = hamming_distance(key_i, key_j) if dist == ham_distance and key_i != key_j: map_keys[key_i].append(key_j) temp_list.append(simillar_word.get(key_j)) else: map_keys[key_i].append([]) tempp = list(itertools.chain(*temp_list)) map_indices[key_i].append(tempp) return map_keys, map_indices compare_strings, compare_list = Compare_Shape() def dtw_test2(): df_dtw_prep = df_sax dtw_df = pd.DataFrame() for k, v in compare_list.items(): v_temp = str(v)[2:-2] v1 = [int(s) for s in v_temp.split(',')] for i in range(0, len(v1) - 1): for j in range(i, len(v1)): if v1[i] != v1[j]: row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]] row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]] sub_section1 = row1.iloc[0]['sub_section'] sub_section2 = row2.iloc[0]['sub_section'] index1 = row1.iloc[0]['indices'] index2 = row2.iloc[0]['indices'] x = np.array(sub_section1).reshape(-1, 1) y = np.array(sub_section2).reshape(-1, 1) euclidean_norm = lambda x, y: np.abs(x - y) dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x, y, dist=euclidean_norm) temp_df = pd.DataFrame([[k, index1, index2, sub_section1, sub_section2, dtw_value]], columns=[ 'keyy', 'index1', 'index2', 'sub_section1', 'sub_section2', 'dtw_value']) dtw_df = dtw_df.append(temp_df, ignore_index=True) return dtw_df dt_test = dtw_test2() stop = timeit.default_timer() print('Time: ', stop - start) <|reserved_special_token_1|> <|reserved_special_token_0|> import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import defaultdict import math import itertools from dtw import dtw import timeit from helper_functions import normalize, alphabetize_ts, hamming_distance <|reserved_special_token_0|> start = timeit.default_timer() data = pd.read_csv('test_data2.csv', sep=',', header=None) x1 = data.iloc[1:, 1].values.flatten() x1 = np.asfarray(x1, float) y_alphabet_size = 4 word_lenth = 3 window_size = round(len(x1) * 10 / 100) skip_offset = round(window_size / 2) ham_distance = 1 epsilon = 1e-06 def segment_ts(): ts_len = len(x1) mod = ts_len % window_size rnge = 0 if skip_offset == 0: ts_len = int((ts_len - mod - window_size) / 1) rnge = int(ts_len / window_size) else: ts_len = int(math.ceil((ts_len - window_size) / skip_offset)) rnge = int(ts_len) curr_count = 0 words = list() indices = list() complete_indices = list() for i in range(0, rnge): sub_section = x1[curr_count:curr_count + window_size] sub_section = normalize(sub_section) curr_word = '' chunk_size = int(len(sub_section) / word_lenth) num = 0 curr_letter = '' for j in range(0, word_lenth): chunk = sub_section[num:num + chunk_size] curr_letter = alphabetize_ts(chunk) curr_word += str(curr_letter) complete_indices.append(curr_count) num += chunk_size words.append(curr_word) indices.append(curr_count) temp_list = [] temp_list.append(sub_section) temp_df = pd.DataFrame() temp_df.insert(loc=0, column='sub_section', value=temp_list) temp_df.insert(loc=0, column='keys', value=curr_word) temp_df.insert(loc=0, column='position', value=sorted(sub_section)[ len(sub_section) // 2]) temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section)) temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section)) temp_df.insert(loc=0, column='indices', value=curr_count) curr_count = curr_count + skip_offset - 1 if i == 0: df_sax = temp_df.copy() else: df_sax = df_sax.append(temp_df, ignore_index=True) return words, indices, df_sax alphabetize, indices, df_sax = segment_ts() <|reserved_special_token_0|> def complete_word(): complete_word = list() complete_indices = indices """ Simillar Words """ complete_word = alphabetize sax = defaultdict(list) for i in range(0, len(complete_word)): if len(complete_word[i]) == word_lenth: sax[complete_word[i]].append(complete_indices[i]) return sax def Compare_Shape(): simillar_word = complete_word() map_keys = defaultdict(list) map_indices = defaultdict(list) for key_i in simillar_word: temp_list = list() temp_list.append(simillar_word.get(key_i)) map_keys[key_i].append(key_i) for key_j in simillar_word: dist = hamming_distance(key_i, key_j) if dist == ham_distance and key_i != key_j: map_keys[key_i].append(key_j) temp_list.append(simillar_word.get(key_j)) else: map_keys[key_i].append([]) tempp = list(itertools.chain(*temp_list)) map_indices[key_i].append(tempp) return map_keys, map_indices compare_strings, compare_list = Compare_Shape() def dtw_test2(): df_dtw_prep = df_sax dtw_df = pd.DataFrame() for k, v in compare_list.items(): v_temp = str(v)[2:-2] v1 = [int(s) for s in v_temp.split(',')] for i in range(0, len(v1) - 1): for j in range(i, len(v1)): if v1[i] != v1[j]: row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]] row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]] sub_section1 = row1.iloc[0]['sub_section'] sub_section2 = row2.iloc[0]['sub_section'] index1 = row1.iloc[0]['indices'] index2 = row2.iloc[0]['indices'] x = np.array(sub_section1).reshape(-1, 1) y = np.array(sub_section2).reshape(-1, 1) euclidean_norm = lambda x, y: np.abs(x - y) dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x, y, dist=euclidean_norm) temp_df = pd.DataFrame([[k, index1, index2, sub_section1, sub_section2, dtw_value]], columns=[ 'keyy', 'index1', 'index2', 'sub_section1', 'sub_section2', 'dtw_value']) dtw_df = dtw_df.append(temp_df, ignore_index=True) return dtw_df dt_test = dtw_test2() stop = timeit.default_timer() print('Time: ', stop - start) <|reserved_special_token_1|> # -*- coding: utf-8 -*- """ Created on Sat Aug 3 17:16:12 2019 @author: Meagatron """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import defaultdict import math import itertools from dtw import dtw import timeit from helper_functions import normalize,alphabetize_ts,hamming_distance """------------- Intialization ------------- """ start = timeit.default_timer() data = pd.read_csv('test_data2.csv', sep=',', header=None) x1 = data.iloc[1:,1].values.flatten() x1=np.asfarray(x1,float) y_alphabet_size=4 word_lenth=3 window_size=round( len(x1) *10 /100 ) skip_offset=round(window_size/2) ham_distance=1 epsilon = 1e-6 def segment_ts(): ts_len=len(x1) mod = ts_len%window_size rnge=0 if(skip_offset==0): ts_len=int((ts_len-mod-window_size)/1) rnge=int(ts_len/window_size) else: ts_len=int(math.ceil((ts_len-window_size)/skip_offset)) rnge=int(ts_len) curr_count=0 words=list() indices=list() complete_indices=list() for i in range(0, rnge): sub_section = x1[curr_count:(curr_count+window_size)] sub_section=normalize(sub_section) curr_word="" chunk_size=int(len(sub_section)/word_lenth) num=0 curr_letter="" for j in range(0,word_lenth): chunk = sub_section[num:num + chunk_size] curr_letter=alphabetize_ts(chunk) curr_word+=str(curr_letter) complete_indices.append(curr_count) num+=chunk_size words.append(curr_word) indices.append(curr_count) temp_list=[] temp_list.append(sub_section) temp_df = pd.DataFrame() temp_df.insert(loc=0, column='sub_section', value=temp_list) temp_df.insert(loc=0, column='keys', value=curr_word) temp_df.insert(loc=0, column='position', value=sorted(sub_section)[len(sub_section) // 2]) temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section)) temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section)) temp_df.insert(loc=0, column='indices', value=curr_count) curr_count=curr_count+skip_offset-1 if(i==0): df_sax =temp_df.copy() else: df_sax=df_sax.append(temp_df, ignore_index=True) return (words,indices,df_sax) alphabetize,indices,df_sax=segment_ts() """ Complete Words """ def complete_word(): complete_word=list() complete_indices=indices """ Simillar Words """ complete_word=alphabetize sax = defaultdict(list) for i in range(0,len(complete_word)): if(len(complete_word[i])==word_lenth): sax[complete_word[i]].append(complete_indices[i]) return sax #alphabetize1,indices1,df_sax=segment_ts() def Compare_Shape(): simillar_word=complete_word() map_keys = defaultdict(list) map_indices=defaultdict(list) for key_i in simillar_word: temp_list=list() temp_list.append(simillar_word.get(key_i)) map_keys[key_i].append(key_i) for key_j in simillar_word: dist=hamming_distance(key_i, key_j) if(dist==ham_distance and key_i !=key_j): map_keys[key_i].append(key_j) temp_list.append(simillar_word.get(key_j)) else: map_keys[key_i].append([]) tempp = list(itertools.chain(*temp_list)) map_indices[key_i].append(tempp) return (map_keys,map_indices) compare_strings,compare_list=Compare_Shape() def dtw_test2 (): df_dtw_prep=df_sax dtw_df=pd.DataFrame() for k, v in compare_list.items(): v_temp=str(v)[2:-2] v1=[int(s) for s in v_temp.split(',')] for i in range(0,len(v1)-1): for j in range(i,len(v1)): if(v1[i] != v1[j]): row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]] row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]] sub_section1 = row1.iloc[0]['sub_section'] sub_section2 = row2.iloc[0]['sub_section'] index1 = row1.iloc[0]['indices'] index2 = row2.iloc[0]['indices'] x=np.array(sub_section1).reshape(-1, 1) y=np.array(sub_section2).reshape(-1, 1) euclidean_norm = lambda x, y: np.abs(x - y) dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x, y, dist=euclidean_norm) temp_df = pd.DataFrame([[k,index1,index2,sub_section1,sub_section2,dtw_value]], columns=['keyy','index1','index2','sub_section1','sub_section2','dtw_value']) dtw_df=dtw_df.append(temp_df,ignore_index=True) return(dtw_df) dt_test=dtw_test2 () stop = timeit.default_timer() print('Time: ', stop - start)
flexible
{ "blob_id": "16215ee42c4ea284dca0ebb7372fef04c0cc54b9", "index": 2149, "step-1": "<mask token>\n\n\ndef segment_ts():\n ts_len = len(x1)\n mod = ts_len % window_size\n rnge = 0\n if skip_offset == 0:\n ts_len = int((ts_len - mod - window_size) / 1)\n rnge = int(ts_len / window_size)\n else:\n ts_len = int(math.ceil((ts_len - window_size) / skip_offset))\n rnge = int(ts_len)\n curr_count = 0\n words = list()\n indices = list()\n complete_indices = list()\n for i in range(0, rnge):\n sub_section = x1[curr_count:curr_count + window_size]\n sub_section = normalize(sub_section)\n curr_word = ''\n chunk_size = int(len(sub_section) / word_lenth)\n num = 0\n curr_letter = ''\n for j in range(0, word_lenth):\n chunk = sub_section[num:num + chunk_size]\n curr_letter = alphabetize_ts(chunk)\n curr_word += str(curr_letter)\n complete_indices.append(curr_count)\n num += chunk_size\n words.append(curr_word)\n indices.append(curr_count)\n temp_list = []\n temp_list.append(sub_section)\n temp_df = pd.DataFrame()\n temp_df.insert(loc=0, column='sub_section', value=temp_list)\n temp_df.insert(loc=0, column='keys', value=curr_word)\n temp_df.insert(loc=0, column='position', value=sorted(sub_section)[\n len(sub_section) // 2])\n temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section))\n temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section))\n temp_df.insert(loc=0, column='indices', value=curr_count)\n curr_count = curr_count + skip_offset - 1\n if i == 0:\n df_sax = temp_df.copy()\n else:\n df_sax = df_sax.append(temp_df, ignore_index=True)\n return words, indices, df_sax\n\n\n<mask token>\n\n\ndef complete_word():\n complete_word = list()\n complete_indices = indices\n \"\"\" Simillar Words \"\"\"\n complete_word = alphabetize\n sax = defaultdict(list)\n for i in range(0, len(complete_word)):\n if len(complete_word[i]) == word_lenth:\n sax[complete_word[i]].append(complete_indices[i])\n return sax\n\n\ndef Compare_Shape():\n simillar_word = complete_word()\n map_keys = defaultdict(list)\n map_indices = defaultdict(list)\n for key_i in simillar_word:\n temp_list = list()\n temp_list.append(simillar_word.get(key_i))\n map_keys[key_i].append(key_i)\n for key_j in simillar_word:\n dist = hamming_distance(key_i, key_j)\n if dist == ham_distance and key_i != key_j:\n map_keys[key_i].append(key_j)\n temp_list.append(simillar_word.get(key_j))\n else:\n map_keys[key_i].append([])\n tempp = list(itertools.chain(*temp_list))\n map_indices[key_i].append(tempp)\n return map_keys, map_indices\n\n\n<mask token>\n\n\ndef dtw_test2():\n df_dtw_prep = df_sax\n dtw_df = pd.DataFrame()\n for k, v in compare_list.items():\n v_temp = str(v)[2:-2]\n v1 = [int(s) for s in v_temp.split(',')]\n for i in range(0, len(v1) - 1):\n for j in range(i, len(v1)):\n if v1[i] != v1[j]:\n row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]]\n row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]]\n sub_section1 = row1.iloc[0]['sub_section']\n sub_section2 = row2.iloc[0]['sub_section']\n index1 = row1.iloc[0]['indices']\n index2 = row2.iloc[0]['indices']\n x = np.array(sub_section1).reshape(-1, 1)\n y = np.array(sub_section2).reshape(-1, 1)\n euclidean_norm = lambda x, y: np.abs(x - y)\n dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x,\n y, dist=euclidean_norm)\n temp_df = pd.DataFrame([[k, index1, index2,\n sub_section1, sub_section2, dtw_value]], columns=[\n 'keyy', 'index1', 'index2', 'sub_section1',\n 'sub_section2', 'dtw_value'])\n dtw_df = dtw_df.append(temp_df, ignore_index=True)\n return dtw_df\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef segment_ts():\n ts_len = len(x1)\n mod = ts_len % window_size\n rnge = 0\n if skip_offset == 0:\n ts_len = int((ts_len - mod - window_size) / 1)\n rnge = int(ts_len / window_size)\n else:\n ts_len = int(math.ceil((ts_len - window_size) / skip_offset))\n rnge = int(ts_len)\n curr_count = 0\n words = list()\n indices = list()\n complete_indices = list()\n for i in range(0, rnge):\n sub_section = x1[curr_count:curr_count + window_size]\n sub_section = normalize(sub_section)\n curr_word = ''\n chunk_size = int(len(sub_section) / word_lenth)\n num = 0\n curr_letter = ''\n for j in range(0, word_lenth):\n chunk = sub_section[num:num + chunk_size]\n curr_letter = alphabetize_ts(chunk)\n curr_word += str(curr_letter)\n complete_indices.append(curr_count)\n num += chunk_size\n words.append(curr_word)\n indices.append(curr_count)\n temp_list = []\n temp_list.append(sub_section)\n temp_df = pd.DataFrame()\n temp_df.insert(loc=0, column='sub_section', value=temp_list)\n temp_df.insert(loc=0, column='keys', value=curr_word)\n temp_df.insert(loc=0, column='position', value=sorted(sub_section)[\n len(sub_section) // 2])\n temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section))\n temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section))\n temp_df.insert(loc=0, column='indices', value=curr_count)\n curr_count = curr_count + skip_offset - 1\n if i == 0:\n df_sax = temp_df.copy()\n else:\n df_sax = df_sax.append(temp_df, ignore_index=True)\n return words, indices, df_sax\n\n\n<mask token>\n\n\ndef complete_word():\n complete_word = list()\n complete_indices = indices\n \"\"\" Simillar Words \"\"\"\n complete_word = alphabetize\n sax = defaultdict(list)\n for i in range(0, len(complete_word)):\n if len(complete_word[i]) == word_lenth:\n sax[complete_word[i]].append(complete_indices[i])\n return sax\n\n\ndef Compare_Shape():\n simillar_word = complete_word()\n map_keys = defaultdict(list)\n map_indices = defaultdict(list)\n for key_i in simillar_word:\n temp_list = list()\n temp_list.append(simillar_word.get(key_i))\n map_keys[key_i].append(key_i)\n for key_j in simillar_word:\n dist = hamming_distance(key_i, key_j)\n if dist == ham_distance and key_i != key_j:\n map_keys[key_i].append(key_j)\n temp_list.append(simillar_word.get(key_j))\n else:\n map_keys[key_i].append([])\n tempp = list(itertools.chain(*temp_list))\n map_indices[key_i].append(tempp)\n return map_keys, map_indices\n\n\n<mask token>\n\n\ndef dtw_test2():\n df_dtw_prep = df_sax\n dtw_df = pd.DataFrame()\n for k, v in compare_list.items():\n v_temp = str(v)[2:-2]\n v1 = [int(s) for s in v_temp.split(',')]\n for i in range(0, len(v1) - 1):\n for j in range(i, len(v1)):\n if v1[i] != v1[j]:\n row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]]\n row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]]\n sub_section1 = row1.iloc[0]['sub_section']\n sub_section2 = row2.iloc[0]['sub_section']\n index1 = row1.iloc[0]['indices']\n index2 = row2.iloc[0]['indices']\n x = np.array(sub_section1).reshape(-1, 1)\n y = np.array(sub_section2).reshape(-1, 1)\n euclidean_norm = lambda x, y: np.abs(x - y)\n dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x,\n y, dist=euclidean_norm)\n temp_df = pd.DataFrame([[k, index1, index2,\n sub_section1, sub_section2, dtw_value]], columns=[\n 'keyy', 'index1', 'index2', 'sub_section1',\n 'sub_section2', 'dtw_value'])\n dtw_df = dtw_df.append(temp_df, ignore_index=True)\n return dtw_df\n\n\n<mask token>\nprint('Time: ', stop - start)\n", "step-3": "<mask token>\nstart = timeit.default_timer()\ndata = pd.read_csv('test_data2.csv', sep=',', header=None)\nx1 = data.iloc[1:, 1].values.flatten()\nx1 = np.asfarray(x1, float)\ny_alphabet_size = 4\nword_lenth = 3\nwindow_size = round(len(x1) * 10 / 100)\nskip_offset = round(window_size / 2)\nham_distance = 1\nepsilon = 1e-06\n\n\ndef segment_ts():\n ts_len = len(x1)\n mod = ts_len % window_size\n rnge = 0\n if skip_offset == 0:\n ts_len = int((ts_len - mod - window_size) / 1)\n rnge = int(ts_len / window_size)\n else:\n ts_len = int(math.ceil((ts_len - window_size) / skip_offset))\n rnge = int(ts_len)\n curr_count = 0\n words = list()\n indices = list()\n complete_indices = list()\n for i in range(0, rnge):\n sub_section = x1[curr_count:curr_count + window_size]\n sub_section = normalize(sub_section)\n curr_word = ''\n chunk_size = int(len(sub_section) / word_lenth)\n num = 0\n curr_letter = ''\n for j in range(0, word_lenth):\n chunk = sub_section[num:num + chunk_size]\n curr_letter = alphabetize_ts(chunk)\n curr_word += str(curr_letter)\n complete_indices.append(curr_count)\n num += chunk_size\n words.append(curr_word)\n indices.append(curr_count)\n temp_list = []\n temp_list.append(sub_section)\n temp_df = pd.DataFrame()\n temp_df.insert(loc=0, column='sub_section', value=temp_list)\n temp_df.insert(loc=0, column='keys', value=curr_word)\n temp_df.insert(loc=0, column='position', value=sorted(sub_section)[\n len(sub_section) // 2])\n temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section))\n temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section))\n temp_df.insert(loc=0, column='indices', value=curr_count)\n curr_count = curr_count + skip_offset - 1\n if i == 0:\n df_sax = temp_df.copy()\n else:\n df_sax = df_sax.append(temp_df, ignore_index=True)\n return words, indices, df_sax\n\n\nalphabetize, indices, df_sax = segment_ts()\n<mask token>\n\n\ndef complete_word():\n complete_word = list()\n complete_indices = indices\n \"\"\" Simillar Words \"\"\"\n complete_word = alphabetize\n sax = defaultdict(list)\n for i in range(0, len(complete_word)):\n if len(complete_word[i]) == word_lenth:\n sax[complete_word[i]].append(complete_indices[i])\n return sax\n\n\ndef Compare_Shape():\n simillar_word = complete_word()\n map_keys = defaultdict(list)\n map_indices = defaultdict(list)\n for key_i in simillar_word:\n temp_list = list()\n temp_list.append(simillar_word.get(key_i))\n map_keys[key_i].append(key_i)\n for key_j in simillar_word:\n dist = hamming_distance(key_i, key_j)\n if dist == ham_distance and key_i != key_j:\n map_keys[key_i].append(key_j)\n temp_list.append(simillar_word.get(key_j))\n else:\n map_keys[key_i].append([])\n tempp = list(itertools.chain(*temp_list))\n map_indices[key_i].append(tempp)\n return map_keys, map_indices\n\n\ncompare_strings, compare_list = Compare_Shape()\n\n\ndef dtw_test2():\n df_dtw_prep = df_sax\n dtw_df = pd.DataFrame()\n for k, v in compare_list.items():\n v_temp = str(v)[2:-2]\n v1 = [int(s) for s in v_temp.split(',')]\n for i in range(0, len(v1) - 1):\n for j in range(i, len(v1)):\n if v1[i] != v1[j]:\n row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]]\n row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]]\n sub_section1 = row1.iloc[0]['sub_section']\n sub_section2 = row2.iloc[0]['sub_section']\n index1 = row1.iloc[0]['indices']\n index2 = row2.iloc[0]['indices']\n x = np.array(sub_section1).reshape(-1, 1)\n y = np.array(sub_section2).reshape(-1, 1)\n euclidean_norm = lambda x, y: np.abs(x - y)\n dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x,\n y, dist=euclidean_norm)\n temp_df = pd.DataFrame([[k, index1, index2,\n sub_section1, sub_section2, dtw_value]], columns=[\n 'keyy', 'index1', 'index2', 'sub_section1',\n 'sub_section2', 'dtw_value'])\n dtw_df = dtw_df.append(temp_df, ignore_index=True)\n return dtw_df\n\n\ndt_test = dtw_test2()\nstop = timeit.default_timer()\nprint('Time: ', stop - start)\n", "step-4": "<mask token>\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nimport math\nimport itertools\nfrom dtw import dtw\nimport timeit\nfrom helper_functions import normalize, alphabetize_ts, hamming_distance\n<mask token>\nstart = timeit.default_timer()\ndata = pd.read_csv('test_data2.csv', sep=',', header=None)\nx1 = data.iloc[1:, 1].values.flatten()\nx1 = np.asfarray(x1, float)\ny_alphabet_size = 4\nword_lenth = 3\nwindow_size = round(len(x1) * 10 / 100)\nskip_offset = round(window_size / 2)\nham_distance = 1\nepsilon = 1e-06\n\n\ndef segment_ts():\n ts_len = len(x1)\n mod = ts_len % window_size\n rnge = 0\n if skip_offset == 0:\n ts_len = int((ts_len - mod - window_size) / 1)\n rnge = int(ts_len / window_size)\n else:\n ts_len = int(math.ceil((ts_len - window_size) / skip_offset))\n rnge = int(ts_len)\n curr_count = 0\n words = list()\n indices = list()\n complete_indices = list()\n for i in range(0, rnge):\n sub_section = x1[curr_count:curr_count + window_size]\n sub_section = normalize(sub_section)\n curr_word = ''\n chunk_size = int(len(sub_section) / word_lenth)\n num = 0\n curr_letter = ''\n for j in range(0, word_lenth):\n chunk = sub_section[num:num + chunk_size]\n curr_letter = alphabetize_ts(chunk)\n curr_word += str(curr_letter)\n complete_indices.append(curr_count)\n num += chunk_size\n words.append(curr_word)\n indices.append(curr_count)\n temp_list = []\n temp_list.append(sub_section)\n temp_df = pd.DataFrame()\n temp_df.insert(loc=0, column='sub_section', value=temp_list)\n temp_df.insert(loc=0, column='keys', value=curr_word)\n temp_df.insert(loc=0, column='position', value=sorted(sub_section)[\n len(sub_section) // 2])\n temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section))\n temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section))\n temp_df.insert(loc=0, column='indices', value=curr_count)\n curr_count = curr_count + skip_offset - 1\n if i == 0:\n df_sax = temp_df.copy()\n else:\n df_sax = df_sax.append(temp_df, ignore_index=True)\n return words, indices, df_sax\n\n\nalphabetize, indices, df_sax = segment_ts()\n<mask token>\n\n\ndef complete_word():\n complete_word = list()\n complete_indices = indices\n \"\"\" Simillar Words \"\"\"\n complete_word = alphabetize\n sax = defaultdict(list)\n for i in range(0, len(complete_word)):\n if len(complete_word[i]) == word_lenth:\n sax[complete_word[i]].append(complete_indices[i])\n return sax\n\n\ndef Compare_Shape():\n simillar_word = complete_word()\n map_keys = defaultdict(list)\n map_indices = defaultdict(list)\n for key_i in simillar_word:\n temp_list = list()\n temp_list.append(simillar_word.get(key_i))\n map_keys[key_i].append(key_i)\n for key_j in simillar_word:\n dist = hamming_distance(key_i, key_j)\n if dist == ham_distance and key_i != key_j:\n map_keys[key_i].append(key_j)\n temp_list.append(simillar_word.get(key_j))\n else:\n map_keys[key_i].append([])\n tempp = list(itertools.chain(*temp_list))\n map_indices[key_i].append(tempp)\n return map_keys, map_indices\n\n\ncompare_strings, compare_list = Compare_Shape()\n\n\ndef dtw_test2():\n df_dtw_prep = df_sax\n dtw_df = pd.DataFrame()\n for k, v in compare_list.items():\n v_temp = str(v)[2:-2]\n v1 = [int(s) for s in v_temp.split(',')]\n for i in range(0, len(v1) - 1):\n for j in range(i, len(v1)):\n if v1[i] != v1[j]:\n row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]]\n row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]]\n sub_section1 = row1.iloc[0]['sub_section']\n sub_section2 = row2.iloc[0]['sub_section']\n index1 = row1.iloc[0]['indices']\n index2 = row2.iloc[0]['indices']\n x = np.array(sub_section1).reshape(-1, 1)\n y = np.array(sub_section2).reshape(-1, 1)\n euclidean_norm = lambda x, y: np.abs(x - y)\n dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x,\n y, dist=euclidean_norm)\n temp_df = pd.DataFrame([[k, index1, index2,\n sub_section1, sub_section2, dtw_value]], columns=[\n 'keyy', 'index1', 'index2', 'sub_section1',\n 'sub_section2', 'dtw_value'])\n dtw_df = dtw_df.append(temp_df, ignore_index=True)\n return dtw_df\n\n\ndt_test = dtw_test2()\nstop = timeit.default_timer()\nprint('Time: ', stop - start)\n", "step-5": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 3 17:16:12 2019\n\n@author: Meagatron\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nimport math\nimport itertools\nfrom dtw import dtw\nimport timeit\n\nfrom helper_functions import normalize,alphabetize_ts,hamming_distance\n\n\n\n\"\"\"------------- Intialization ------------- \"\"\"\nstart = timeit.default_timer()\n\ndata = pd.read_csv('test_data2.csv', sep=',', header=None)\nx1 = data.iloc[1:,1].values.flatten() \nx1=np.asfarray(x1,float)\n\n\n\n\n\ny_alphabet_size=4\nword_lenth=3\nwindow_size=round( len(x1) *10 /100 )\nskip_offset=round(window_size/2)\nham_distance=1\nepsilon = 1e-6\n\n\ndef segment_ts():\n\n\n ts_len=len(x1)\n\n mod = ts_len%window_size\n rnge=0\n if(skip_offset==0):\n ts_len=int((ts_len-mod-window_size)/1)\n rnge=int(ts_len/window_size)\n else:\n ts_len=int(math.ceil((ts_len-window_size)/skip_offset))\n rnge=int(ts_len)\n\n curr_count=0\n words=list()\n indices=list()\n complete_indices=list()\n \n for i in range(0, rnge):\n\n sub_section = x1[curr_count:(curr_count+window_size)]\n sub_section=normalize(sub_section)\n \n curr_word=\"\"\n chunk_size=int(len(sub_section)/word_lenth)\n num=0\n curr_letter=\"\"\n for j in range(0,word_lenth):\n chunk = sub_section[num:num + chunk_size]\n curr_letter=alphabetize_ts(chunk)\n curr_word+=str(curr_letter)\n complete_indices.append(curr_count)\n num+=chunk_size\n\n words.append(curr_word)\n indices.append(curr_count)\n \n\n temp_list=[]\n temp_list.append(sub_section)\n \n \n temp_df = pd.DataFrame()\n temp_df.insert(loc=0, column='sub_section', value=temp_list)\n temp_df.insert(loc=0, column='keys', value=curr_word)\n temp_df.insert(loc=0, column='position', value=sorted(sub_section)[len(sub_section) // 2])\n temp_df.insert(loc=0, column='scale_high', value=np.max(sub_section))\n temp_df.insert(loc=0, column='scale_low', value=np.min(sub_section))\n temp_df.insert(loc=0, column='indices', value=curr_count)\n \n \n curr_count=curr_count+skip_offset-1\n\n if(i==0):\n\n df_sax =temp_df.copy()\n else:\n df_sax=df_sax.append(temp_df, ignore_index=True)\n\n return (words,indices,df_sax)\n\n\nalphabetize,indices,df_sax=segment_ts()\n\n\n\n\"\"\" Complete Words \"\"\"\ndef complete_word():\n \n complete_word=list()\n complete_indices=indices\n\n \"\"\" Simillar Words \"\"\"\n complete_word=alphabetize\n sax = defaultdict(list)\n for i in range(0,len(complete_word)):\n if(len(complete_word[i])==word_lenth):\n sax[complete_word[i]].append(complete_indices[i])\n return sax\n\n#alphabetize1,indices1,df_sax=segment_ts()\n\n\ndef Compare_Shape():\n simillar_word=complete_word()\n map_keys = defaultdict(list)\n map_indices=defaultdict(list)\n \n \n for key_i in simillar_word:\n temp_list=list()\n temp_list.append(simillar_word.get(key_i))\n map_keys[key_i].append(key_i)\n \n for key_j in simillar_word:\n dist=hamming_distance(key_i, key_j)\n if(dist==ham_distance and key_i !=key_j):\n map_keys[key_i].append(key_j)\n temp_list.append(simillar_word.get(key_j))\n else:\n map_keys[key_i].append([])\n\n tempp = list(itertools.chain(*temp_list))\n map_indices[key_i].append(tempp) \n return (map_keys,map_indices)\n\n\n\n\ncompare_strings,compare_list=Compare_Shape()\n\n\ndef dtw_test2 ():\n df_dtw_prep=df_sax\n \n dtw_df=pd.DataFrame()\n \n \n for k, v in compare_list.items():\n \n v_temp=str(v)[2:-2]\n v1=[int(s) for s in v_temp.split(',')]\n\n for i in range(0,len(v1)-1):\n for j in range(i,len(v1)):\n \n \n if(v1[i] != v1[j]):\n \n \n\n row1 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[i]]\n row2 = df_dtw_prep.loc[df_dtw_prep['indices'] == v1[j]]\n \n sub_section1 = row1.iloc[0]['sub_section']\n sub_section2 = row2.iloc[0]['sub_section']\n \n \n index1 = row1.iloc[0]['indices']\n index2 = row2.iloc[0]['indices']\n \n\n x=np.array(sub_section1).reshape(-1, 1)\n y=np.array(sub_section2).reshape(-1, 1)\n\n euclidean_norm = lambda x, y: np.abs(x - y)\n dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x, y, dist=euclidean_norm)\n \n \n temp_df = pd.DataFrame([[k,index1,index2,sub_section1,sub_section2,dtw_value]], \n columns=['keyy','index1','index2','sub_section1','sub_section2','dtw_value'])\n dtw_df=dtw_df.append(temp_df,ignore_index=True)\n \n \n return(dtw_df)\n\n\ndt_test=dtw_test2 ()\n\n\nstop = timeit.default_timer()\nprint('Time: ', stop - start) \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
def isSubsetSum(set, n, sum): subset =([[False for i in range(sum + 1)] for i in range(n + 1)]) for i in range(n + 1): subset[i][0] = True for i in range(1, sum + 1): subset[0][i]= False for i in range(1, n + 1): for j in range(1, sum + 1): if j<set[i-1]: subset[i][j] = subset[i-1][j] if j>= set[i-1]: subset[i][j] = (subset[i-1][j] or subset[i - 1][j-set[i-1]]) return subset[n][sum] t=int(input()) for i in range(t): n,k=map(int,input().split()) lst=list(map(int,input().strip().split(' ')))[:n] if (isSubsetSum(lst, n, k) == True): print("YES") else: print("NO")
normal
{ "blob_id": "830e7e84eebd6a4adb411cc95c9e9c8ff7bdac30", "index": 778, "step-1": "<mask token>\n", "step-2": "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n subset[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if j < set[i - 1]:\n subset[i][j] = subset[i - 1][j]\n if j >= set[i - 1]:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1]\n ]\n return subset[n][sum]\n\n\n<mask token>\n", "step-3": "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n subset[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if j < set[i - 1]:\n subset[i][j] = subset[i - 1][j]\n if j >= set[i - 1]:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1]\n ]\n return subset[n][sum]\n\n\n<mask token>\nfor i in range(t):\n n, k = map(int, input().split())\n lst = list(map(int, input().strip().split(' ')))[:n]\n if isSubsetSum(lst, n, k) == True:\n print('YES')\n else:\n print('NO')\n", "step-4": "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n subset[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if j < set[i - 1]:\n subset[i][j] = subset[i - 1][j]\n if j >= set[i - 1]:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1]\n ]\n return subset[n][sum]\n\n\nt = int(input())\nfor i in range(t):\n n, k = map(int, input().split())\n lst = list(map(int, input().strip().split(' ')))[:n]\n if isSubsetSum(lst, n, k) == True:\n print('YES')\n else:\n print('NO')\n", "step-5": "def isSubsetSum(set, n, sum): \n subset =([[False for i in range(sum + 1)] for i in range(n + 1)]) \n for i in range(n + 1): \n subset[i][0] = True\n for i in range(1, sum + 1): \n subset[0][i]= False\n for i in range(1, n + 1): \n for j in range(1, sum + 1): \n if j<set[i-1]: \n subset[i][j] = subset[i-1][j] \n if j>= set[i-1]: \n subset[i][j] = (subset[i-1][j] or subset[i - 1][j-set[i-1]]) \n return subset[n][sum] \nt=int(input())\nfor i in range(t):\n n,k=map(int,input().split())\n lst=list(map(int,input().strip().split(' ')))[:n]\n if (isSubsetSum(lst, n, k) == True): \n print(\"YES\") \n else: \n print(\"NO\") \n \n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def split_matrix(ratings, num_users, num_movies): X = np.zeros((num_users, num_movies)) for r in np.arange(len(ratings)): X[ratings[r, 0] - 1, ratings[r, 1] - 1] = ratings[r, 2] return X def mf_gd(ratings, num_users, num_movies): X_data = split_matrix(ratings, num_users, num_movies) X_hat = np.zeros(num_users, num_movies) err = np.zeros(num_users, num_movies) U = np.random.rand(num_users, num_factors) M = np.random.rand(num_factors, num_movies) U_prime = U M_prime = M for nr in np.arange(num_iter): for i in np.arange(len(ratings)): userID = ratings[i, 0] - 1 movieID = ratings[i, 1] - 1 actual = ratings[i, 2] prediction = np.sum(U[userID, :] * M[:, movieID]) error = actual - prediction for k in np.arange(num_factors): U_prime[userID, k] = U[userID, k] + lr * (2 * error * M[k, movieID] - regularization * U[userID, k]) M_prime[k, movieID] = M[k, movieID] + lr * (2 * error * U[ userID, k] - regularization * M[k, movieID]) U = U_prime M = M_prime X_hat = np.dot(U, M) err = X_data - X_hat e = err[np.where(np.isnan(err) == False)] ir = np.sqrt(np.mean(e ** 2)) print('Error for iteration #', nr, ':', ir) X_hat = np.dot(U, M) return X_hat <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def split_matrix(ratings, num_users, num_movies): X = np.zeros((num_users, num_movies)) for r in np.arange(len(ratings)): X[ratings[r, 0] - 1, ratings[r, 1] - 1] = ratings[r, 2] return X def mf_gd(ratings, num_users, num_movies): X_data = split_matrix(ratings, num_users, num_movies) X_hat = np.zeros(num_users, num_movies) err = np.zeros(num_users, num_movies) U = np.random.rand(num_users, num_factors) M = np.random.rand(num_factors, num_movies) U_prime = U M_prime = M for nr in np.arange(num_iter): for i in np.arange(len(ratings)): userID = ratings[i, 0] - 1 movieID = ratings[i, 1] - 1 actual = ratings[i, 2] prediction = np.sum(U[userID, :] * M[:, movieID]) error = actual - prediction for k in np.arange(num_factors): U_prime[userID, k] = U[userID, k] + lr * (2 * error * M[k, movieID] - regularization * U[userID, k]) M_prime[k, movieID] = M[k, movieID] + lr * (2 * error * U[ userID, k] - regularization * M[k, movieID]) U = U_prime M = M_prime X_hat = np.dot(U, M) err = X_data - X_hat e = err[np.where(np.isnan(err) == False)] ir = np.sqrt(np.mean(e ** 2)) print('Error for iteration #', nr, ':', ir) X_hat = np.dot(U, M) return X_hat def mf(): ratings = np.genfromtxt( 'D:/Leiden/Semester 1_Sept/Assignment1/AiDM/ml-1m/ratings.dat', usecols=(0, 1, 2), delimiter='::', dtype='int') num_users = np.max(ratings[:, 0]) num_movies = np.max(ratings[:, 1]) print(num_users, num_movies) print(len(ratings)) for f in np.arange(folds): print('Fold #', f) np.random.shuffle(ratings) train_set = np.array([ratings[x] for x in np.arange(len(ratings)) if x % folds != f]) test_set = np.array([ratings[x] for x in np.arange(len(ratings)) if x % folds == f]) X_hat = mf_gd(train_set, num_users, num_movies) X_train = split_matrix(train_set, num_users, num_movies) X_test = split_matrix(test_set, num_users, num_movies) err_train = X_train - X_hat err_test = X_test - X_hat e_mf = err_train[np.where(np.isnan(err_train) == False)] error_train_mf = np.sqrt(np.mean(e_mf ** 2)) e2_mf = err_test[np.where(np.isnan(err_test) == False)] error_test_mf = np.sqrt(np.mean(e2_mf ** 2)) print('Matrix Factorization Error -> training set: ', error_train_mf) print('Matrix Factorization Error -> test set: ', error_test_mf) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> np.random.seed(17) def split_matrix(ratings, num_users, num_movies): X = np.zeros((num_users, num_movies)) for r in np.arange(len(ratings)): X[ratings[r, 0] - 1, ratings[r, 1] - 1] = ratings[r, 2] return X def mf_gd(ratings, num_users, num_movies): X_data = split_matrix(ratings, num_users, num_movies) X_hat = np.zeros(num_users, num_movies) err = np.zeros(num_users, num_movies) U = np.random.rand(num_users, num_factors) M = np.random.rand(num_factors, num_movies) U_prime = U M_prime = M for nr in np.arange(num_iter): for i in np.arange(len(ratings)): userID = ratings[i, 0] - 1 movieID = ratings[i, 1] - 1 actual = ratings[i, 2] prediction = np.sum(U[userID, :] * M[:, movieID]) error = actual - prediction for k in np.arange(num_factors): U_prime[userID, k] = U[userID, k] + lr * (2 * error * M[k, movieID] - regularization * U[userID, k]) M_prime[k, movieID] = M[k, movieID] + lr * (2 * error * U[ userID, k] - regularization * M[k, movieID]) U = U_prime M = M_prime X_hat = np.dot(U, M) err = X_data - X_hat e = err[np.where(np.isnan(err) == False)] ir = np.sqrt(np.mean(e ** 2)) print('Error for iteration #', nr, ':', ir) X_hat = np.dot(U, M) return X_hat def mf(): ratings = np.genfromtxt( 'D:/Leiden/Semester 1_Sept/Assignment1/AiDM/ml-1m/ratings.dat', usecols=(0, 1, 2), delimiter='::', dtype='int') num_users = np.max(ratings[:, 0]) num_movies = np.max(ratings[:, 1]) print(num_users, num_movies) print(len(ratings)) for f in np.arange(folds): print('Fold #', f) np.random.shuffle(ratings) train_set = np.array([ratings[x] for x in np.arange(len(ratings)) if x % folds != f]) test_set = np.array([ratings[x] for x in np.arange(len(ratings)) if x % folds == f]) X_hat = mf_gd(train_set, num_users, num_movies) X_train = split_matrix(train_set, num_users, num_movies) X_test = split_matrix(test_set, num_users, num_movies) err_train = X_train - X_hat err_test = X_test - X_hat e_mf = err_train[np.where(np.isnan(err_train) == False)] error_train_mf = np.sqrt(np.mean(e_mf ** 2)) e2_mf = err_test[np.where(np.isnan(err_test) == False)] error_test_mf = np.sqrt(np.mean(e2_mf ** 2)) print('Matrix Factorization Error -> training set: ', error_train_mf) print('Matrix Factorization Error -> test set: ', error_test_mf) mf() <|reserved_special_token_1|> <|reserved_special_token_0|> num_factors = 10 num_iter = 75 regularization = 0.05 lr = 0.005 folds = 5 np.random.seed(17) def split_matrix(ratings, num_users, num_movies): X = np.zeros((num_users, num_movies)) for r in np.arange(len(ratings)): X[ratings[r, 0] - 1, ratings[r, 1] - 1] = ratings[r, 2] return X def mf_gd(ratings, num_users, num_movies): X_data = split_matrix(ratings, num_users, num_movies) X_hat = np.zeros(num_users, num_movies) err = np.zeros(num_users, num_movies) U = np.random.rand(num_users, num_factors) M = np.random.rand(num_factors, num_movies) U_prime = U M_prime = M for nr in np.arange(num_iter): for i in np.arange(len(ratings)): userID = ratings[i, 0] - 1 movieID = ratings[i, 1] - 1 actual = ratings[i, 2] prediction = np.sum(U[userID, :] * M[:, movieID]) error = actual - prediction for k in np.arange(num_factors): U_prime[userID, k] = U[userID, k] + lr * (2 * error * M[k, movieID] - regularization * U[userID, k]) M_prime[k, movieID] = M[k, movieID] + lr * (2 * error * U[ userID, k] - regularization * M[k, movieID]) U = U_prime M = M_prime X_hat = np.dot(U, M) err = X_data - X_hat e = err[np.where(np.isnan(err) == False)] ir = np.sqrt(np.mean(e ** 2)) print('Error for iteration #', nr, ':', ir) X_hat = np.dot(U, M) return X_hat def mf(): ratings = np.genfromtxt( 'D:/Leiden/Semester 1_Sept/Assignment1/AiDM/ml-1m/ratings.dat', usecols=(0, 1, 2), delimiter='::', dtype='int') num_users = np.max(ratings[:, 0]) num_movies = np.max(ratings[:, 1]) print(num_users, num_movies) print(len(ratings)) for f in np.arange(folds): print('Fold #', f) np.random.shuffle(ratings) train_set = np.array([ratings[x] for x in np.arange(len(ratings)) if x % folds != f]) test_set = np.array([ratings[x] for x in np.arange(len(ratings)) if x % folds == f]) X_hat = mf_gd(train_set, num_users, num_movies) X_train = split_matrix(train_set, num_users, num_movies) X_test = split_matrix(test_set, num_users, num_movies) err_train = X_train - X_hat err_test = X_test - X_hat e_mf = err_train[np.where(np.isnan(err_train) == False)] error_train_mf = np.sqrt(np.mean(e_mf ** 2)) e2_mf = err_test[np.where(np.isnan(err_test) == False)] error_test_mf = np.sqrt(np.mean(e2_mf ** 2)) print('Matrix Factorization Error -> training set: ', error_train_mf) print('Matrix Factorization Error -> test set: ', error_test_mf) mf() <|reserved_special_token_1|> #from getData import getRatings import numpy as np num_factors = 10 num_iter = 75 regularization = 0.05 lr = 0.005 folds=5 #to make sure you are able to repeat results, set the random seed to something: np.random.seed(17) def split_matrix(ratings, num_users, num_movies): #Convert data into (IxJ) matrix X= np.zeros((num_users, num_movies)) for r in np.arange(len(ratings)): X[ratings[r,0]-1,ratings[r,1]-1] = ratings[r,2] #print(X.shape) return X def mf_gd(ratings, num_users, num_movies): X_data= split_matrix(ratings, num_users, num_movies) X_hat = np.zeros(num_users, num_movies) #predicted rating matrix err = np.zeros(num_users, num_movies) #error values # Randomly initialize weights in U and M U = np.random.rand(num_users, num_factors) M = np.random.rand(num_factors, num_movies) U_prime = U M_prime = M for nr in np.arange(num_iter): for i in np.arange(len(ratings)): userID = ratings[i,0]-1 movieID = ratings[i,1]-1 actual = ratings[i,2] prediction = np.sum(U[userID,:]*M[:,movieID]) #SVD error = actual - prediction #compute e(i,j) #update U and M using following equations: #Uprime(i,k) = u(i,k) + lr(2e*m(k,j)-lamda.u(i,k)) #Mprime(k,j) = m(k,j) + lr(2e*u(i,k)-lamda.m(k,j)) for k in np.arange(num_factors): U_prime[userID,k] = U[userID,k]+ lr * (2*error*M[k,movieID] - regularization * U[userID,k]) M_prime[k,movieID] = M[k,movieID] + lr * (2*error*U[userID,k] - regularization * M[k,movieID]) U = U_prime M = M_prime #Intermediate RMSE X_hat = np.dot(U,M) err = X_data-X_hat e = err[np.where(np.isnan(err)==False)] ir = np.sqrt(np.mean(e**2)) print ("Error for iteration #", nr, ":", ir) #Return the result X_hat = np.dot(U,M) return X_hat def mf(): #Read dataset #ratings = getRatings() ratings = np.genfromtxt("D:/Leiden/Semester 1_Sept/Assignment1/AiDM/ml-1m/ratings.dat", usecols=(0,1,2), delimiter='::',dtype='int') #number of users and movies in data. num_users= np.max(ratings[:,0]) num_movies= np.max(ratings[:,1]) print(num_users, num_movies) print(len(ratings)) #5-fold cross validation for f in np.arange(folds): print ("Fold #", f) #shuffle data for train and test np.random.shuffle(ratings) train_set = np.array([ratings[x] for x in np.arange(len(ratings)) if (x%folds) !=f]) test_set = np.array([ratings[x] for x in np.arange(len(ratings)) if (x%folds) == f]) #Matrix fact X_hat = mf_gd(train_set, num_users, num_movies) X_train = split_matrix(train_set, num_users, num_movies) X_test = split_matrix(test_set, num_users, num_movies) err_train = X_train- X_hat err_test = X_test - X_hat #RMSE e_mf = err_train[np.where(np.isnan(err_train)==False)] error_train_mf = np.sqrt(np.mean(e_mf**2)) e2_mf = err_test[np.where(np.isnan(err_test)==False)] error_test_mf = np.sqrt(np.mean(e2_mf**2)) print ('Matrix Factorization Error -> training set: ', error_train_mf) print ('Matrix Factorization Error -> test set: ', error_test_mf) mf() #Still getting a high error rate, not comparable to the website mentioned in the assignment doc. # I need to check the logic again. #https://medium.com/coinmonks/recommendation-engine-python-401c080c583e; followed this blogpost
flexible
{ "blob_id": "b4267612e7939b635542099e1ba31e661720607a", "index": 3129, "step-1": "<mask token>\n\n\ndef split_matrix(ratings, num_users, num_movies):\n X = np.zeros((num_users, num_movies))\n for r in np.arange(len(ratings)):\n X[ratings[r, 0] - 1, ratings[r, 1] - 1] = ratings[r, 2]\n return X\n\n\ndef mf_gd(ratings, num_users, num_movies):\n X_data = split_matrix(ratings, num_users, num_movies)\n X_hat = np.zeros(num_users, num_movies)\n err = np.zeros(num_users, num_movies)\n U = np.random.rand(num_users, num_factors)\n M = np.random.rand(num_factors, num_movies)\n U_prime = U\n M_prime = M\n for nr in np.arange(num_iter):\n for i in np.arange(len(ratings)):\n userID = ratings[i, 0] - 1\n movieID = ratings[i, 1] - 1\n actual = ratings[i, 2]\n prediction = np.sum(U[userID, :] * M[:, movieID])\n error = actual - prediction\n for k in np.arange(num_factors):\n U_prime[userID, k] = U[userID, k] + lr * (2 * error * M[k,\n movieID] - regularization * U[userID, k])\n M_prime[k, movieID] = M[k, movieID] + lr * (2 * error * U[\n userID, k] - regularization * M[k, movieID])\n U = U_prime\n M = M_prime\n X_hat = np.dot(U, M)\n err = X_data - X_hat\n e = err[np.where(np.isnan(err) == False)]\n ir = np.sqrt(np.mean(e ** 2))\n print('Error for iteration #', nr, ':', ir)\n X_hat = np.dot(U, M)\n return X_hat\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef split_matrix(ratings, num_users, num_movies):\n X = np.zeros((num_users, num_movies))\n for r in np.arange(len(ratings)):\n X[ratings[r, 0] - 1, ratings[r, 1] - 1] = ratings[r, 2]\n return X\n\n\ndef mf_gd(ratings, num_users, num_movies):\n X_data = split_matrix(ratings, num_users, num_movies)\n X_hat = np.zeros(num_users, num_movies)\n err = np.zeros(num_users, num_movies)\n U = np.random.rand(num_users, num_factors)\n M = np.random.rand(num_factors, num_movies)\n U_prime = U\n M_prime = M\n for nr in np.arange(num_iter):\n for i in np.arange(len(ratings)):\n userID = ratings[i, 0] - 1\n movieID = ratings[i, 1] - 1\n actual = ratings[i, 2]\n prediction = np.sum(U[userID, :] * M[:, movieID])\n error = actual - prediction\n for k in np.arange(num_factors):\n U_prime[userID, k] = U[userID, k] + lr * (2 * error * M[k,\n movieID] - regularization * U[userID, k])\n M_prime[k, movieID] = M[k, movieID] + lr * (2 * error * U[\n userID, k] - regularization * M[k, movieID])\n U = U_prime\n M = M_prime\n X_hat = np.dot(U, M)\n err = X_data - X_hat\n e = err[np.where(np.isnan(err) == False)]\n ir = np.sqrt(np.mean(e ** 2))\n print('Error for iteration #', nr, ':', ir)\n X_hat = np.dot(U, M)\n return X_hat\n\n\ndef mf():\n ratings = np.genfromtxt(\n 'D:/Leiden/Semester 1_Sept/Assignment1/AiDM/ml-1m/ratings.dat',\n usecols=(0, 1, 2), delimiter='::', dtype='int')\n num_users = np.max(ratings[:, 0])\n num_movies = np.max(ratings[:, 1])\n print(num_users, num_movies)\n print(len(ratings))\n for f in np.arange(folds):\n print('Fold #', f)\n np.random.shuffle(ratings)\n train_set = np.array([ratings[x] for x in np.arange(len(ratings)) if\n x % folds != f])\n test_set = np.array([ratings[x] for x in np.arange(len(ratings)) if\n x % folds == f])\n X_hat = mf_gd(train_set, num_users, num_movies)\n X_train = split_matrix(train_set, num_users, num_movies)\n X_test = split_matrix(test_set, num_users, num_movies)\n err_train = X_train - X_hat\n err_test = X_test - X_hat\n e_mf = err_train[np.where(np.isnan(err_train) == False)]\n error_train_mf = np.sqrt(np.mean(e_mf ** 2))\n e2_mf = err_test[np.where(np.isnan(err_test) == False)]\n error_test_mf = np.sqrt(np.mean(e2_mf ** 2))\n print('Matrix Factorization Error -> training set: ', error_train_mf)\n print('Matrix Factorization Error -> test set: ', error_test_mf)\n\n\n<mask token>\n", "step-3": "<mask token>\nnp.random.seed(17)\n\n\ndef split_matrix(ratings, num_users, num_movies):\n X = np.zeros((num_users, num_movies))\n for r in np.arange(len(ratings)):\n X[ratings[r, 0] - 1, ratings[r, 1] - 1] = ratings[r, 2]\n return X\n\n\ndef mf_gd(ratings, num_users, num_movies):\n X_data = split_matrix(ratings, num_users, num_movies)\n X_hat = np.zeros(num_users, num_movies)\n err = np.zeros(num_users, num_movies)\n U = np.random.rand(num_users, num_factors)\n M = np.random.rand(num_factors, num_movies)\n U_prime = U\n M_prime = M\n for nr in np.arange(num_iter):\n for i in np.arange(len(ratings)):\n userID = ratings[i, 0] - 1\n movieID = ratings[i, 1] - 1\n actual = ratings[i, 2]\n prediction = np.sum(U[userID, :] * M[:, movieID])\n error = actual - prediction\n for k in np.arange(num_factors):\n U_prime[userID, k] = U[userID, k] + lr * (2 * error * M[k,\n movieID] - regularization * U[userID, k])\n M_prime[k, movieID] = M[k, movieID] + lr * (2 * error * U[\n userID, k] - regularization * M[k, movieID])\n U = U_prime\n M = M_prime\n X_hat = np.dot(U, M)\n err = X_data - X_hat\n e = err[np.where(np.isnan(err) == False)]\n ir = np.sqrt(np.mean(e ** 2))\n print('Error for iteration #', nr, ':', ir)\n X_hat = np.dot(U, M)\n return X_hat\n\n\ndef mf():\n ratings = np.genfromtxt(\n 'D:/Leiden/Semester 1_Sept/Assignment1/AiDM/ml-1m/ratings.dat',\n usecols=(0, 1, 2), delimiter='::', dtype='int')\n num_users = np.max(ratings[:, 0])\n num_movies = np.max(ratings[:, 1])\n print(num_users, num_movies)\n print(len(ratings))\n for f in np.arange(folds):\n print('Fold #', f)\n np.random.shuffle(ratings)\n train_set = np.array([ratings[x] for x in np.arange(len(ratings)) if\n x % folds != f])\n test_set = np.array([ratings[x] for x in np.arange(len(ratings)) if\n x % folds == f])\n X_hat = mf_gd(train_set, num_users, num_movies)\n X_train = split_matrix(train_set, num_users, num_movies)\n X_test = split_matrix(test_set, num_users, num_movies)\n err_train = X_train - X_hat\n err_test = X_test - X_hat\n e_mf = err_train[np.where(np.isnan(err_train) == False)]\n error_train_mf = np.sqrt(np.mean(e_mf ** 2))\n e2_mf = err_test[np.where(np.isnan(err_test) == False)]\n error_test_mf = np.sqrt(np.mean(e2_mf ** 2))\n print('Matrix Factorization Error -> training set: ', error_train_mf)\n print('Matrix Factorization Error -> test set: ', error_test_mf)\n\n\nmf()\n", "step-4": "<mask token>\nnum_factors = 10\nnum_iter = 75\nregularization = 0.05\nlr = 0.005\nfolds = 5\nnp.random.seed(17)\n\n\ndef split_matrix(ratings, num_users, num_movies):\n X = np.zeros((num_users, num_movies))\n for r in np.arange(len(ratings)):\n X[ratings[r, 0] - 1, ratings[r, 1] - 1] = ratings[r, 2]\n return X\n\n\ndef mf_gd(ratings, num_users, num_movies):\n X_data = split_matrix(ratings, num_users, num_movies)\n X_hat = np.zeros(num_users, num_movies)\n err = np.zeros(num_users, num_movies)\n U = np.random.rand(num_users, num_factors)\n M = np.random.rand(num_factors, num_movies)\n U_prime = U\n M_prime = M\n for nr in np.arange(num_iter):\n for i in np.arange(len(ratings)):\n userID = ratings[i, 0] - 1\n movieID = ratings[i, 1] - 1\n actual = ratings[i, 2]\n prediction = np.sum(U[userID, :] * M[:, movieID])\n error = actual - prediction\n for k in np.arange(num_factors):\n U_prime[userID, k] = U[userID, k] + lr * (2 * error * M[k,\n movieID] - regularization * U[userID, k])\n M_prime[k, movieID] = M[k, movieID] + lr * (2 * error * U[\n userID, k] - regularization * M[k, movieID])\n U = U_prime\n M = M_prime\n X_hat = np.dot(U, M)\n err = X_data - X_hat\n e = err[np.where(np.isnan(err) == False)]\n ir = np.sqrt(np.mean(e ** 2))\n print('Error for iteration #', nr, ':', ir)\n X_hat = np.dot(U, M)\n return X_hat\n\n\ndef mf():\n ratings = np.genfromtxt(\n 'D:/Leiden/Semester 1_Sept/Assignment1/AiDM/ml-1m/ratings.dat',\n usecols=(0, 1, 2), delimiter='::', dtype='int')\n num_users = np.max(ratings[:, 0])\n num_movies = np.max(ratings[:, 1])\n print(num_users, num_movies)\n print(len(ratings))\n for f in np.arange(folds):\n print('Fold #', f)\n np.random.shuffle(ratings)\n train_set = np.array([ratings[x] for x in np.arange(len(ratings)) if\n x % folds != f])\n test_set = np.array([ratings[x] for x in np.arange(len(ratings)) if\n x % folds == f])\n X_hat = mf_gd(train_set, num_users, num_movies)\n X_train = split_matrix(train_set, num_users, num_movies)\n X_test = split_matrix(test_set, num_users, num_movies)\n err_train = X_train - X_hat\n err_test = X_test - X_hat\n e_mf = err_train[np.where(np.isnan(err_train) == False)]\n error_train_mf = np.sqrt(np.mean(e_mf ** 2))\n e2_mf = err_test[np.where(np.isnan(err_test) == False)]\n error_test_mf = np.sqrt(np.mean(e2_mf ** 2))\n print('Matrix Factorization Error -> training set: ', error_train_mf)\n print('Matrix Factorization Error -> test set: ', error_test_mf)\n\n\nmf()\n", "step-5": "#from getData import getRatings\r\nimport numpy as np \r\n\r\n\r\nnum_factors = 10\r\nnum_iter = 75\r\nregularization = 0.05\r\nlr = 0.005\r\nfolds=5\r\n\r\n#to make sure you are able to repeat results, set the random seed to something:\r\nnp.random.seed(17)\r\n\r\n\r\ndef split_matrix(ratings, num_users, num_movies):\r\n #Convert data into (IxJ) matrix\r\n X= np.zeros((num_users, num_movies))\r\n for r in np.arange(len(ratings)):\r\n X[ratings[r,0]-1,ratings[r,1]-1] = ratings[r,2]\r\n\r\n #print(X.shape)\r\n return X\r\n\r\n\r\ndef mf_gd(ratings, num_users, num_movies):\r\n X_data= split_matrix(ratings, num_users, num_movies)\r\n\r\n X_hat = np.zeros(num_users, num_movies) #predicted rating matrix\r\n err = np.zeros(num_users, num_movies) #error values\r\n\r\n # Randomly initialize weights in U and M \r\n U = np.random.rand(num_users, num_factors)\r\n M = np.random.rand(num_factors, num_movies)\r\n U_prime = U\r\n M_prime = M\r\n\r\n for nr in np.arange(num_iter):\r\n for i in np.arange(len(ratings)):\r\n userID = ratings[i,0]-1\r\n movieID = ratings[i,1]-1\r\n actual = ratings[i,2]\r\n prediction = np.sum(U[userID,:]*M[:,movieID]) #SVD\r\n error = actual - prediction #compute e(i,j)\r\n\r\n \r\n #update U and M using following equations:\r\n #Uprime(i,k) = u(i,k) + lr(2e*m(k,j)-lamda.u(i,k))\r\n #Mprime(k,j) = m(k,j) + lr(2e*u(i,k)-lamda.m(k,j))\r\n for k in np.arange(num_factors):\r\n U_prime[userID,k] = U[userID,k]+ lr * (2*error*M[k,movieID] - regularization * U[userID,k])\r\n M_prime[k,movieID] = M[k,movieID] + lr * (2*error*U[userID,k] - regularization * M[k,movieID])\r\n\r\n U = U_prime\r\n M = M_prime\r\n\r\n #Intermediate RMSE\r\n X_hat = np.dot(U,M)\r\n err = X_data-X_hat\r\n e = err[np.where(np.isnan(err)==False)]\r\n ir = np.sqrt(np.mean(e**2))\r\n\r\n print (\"Error for iteration #\", nr, \":\", ir)\r\n\r\n \r\n #Return the result \r\n X_hat = np.dot(U,M)\r\n return X_hat\r\n\r\n\r\ndef mf():\r\n #Read dataset \r\n #ratings = getRatings()\r\n ratings = np.genfromtxt(\"D:/Leiden/Semester 1_Sept/Assignment1/AiDM/ml-1m/ratings.dat\", usecols=(0,1,2), delimiter='::',dtype='int')\r\n\r\n #number of users and movies in data. \r\n num_users= np.max(ratings[:,0])\r\n num_movies= np.max(ratings[:,1])\r\n\r\n print(num_users, num_movies)\r\n print(len(ratings))\r\n \r\n #5-fold cross validation\r\n for f in np.arange(folds):\r\n print (\"Fold #\", f)\r\n\r\n #shuffle data for train and test\r\n np.random.shuffle(ratings)\r\n train_set = np.array([ratings[x] for x in np.arange(len(ratings)) if (x%folds) !=f])\r\n test_set = np.array([ratings[x] for x in np.arange(len(ratings)) if (x%folds) == f])\r\n\r\n \r\n #Matrix fact\r\n X_hat = mf_gd(train_set, num_users, num_movies)\r\n X_train = split_matrix(train_set, num_users, num_movies)\r\n X_test = split_matrix(test_set, num_users, num_movies)\r\n\r\n err_train = X_train- X_hat\r\n err_test = X_test - X_hat\r\n\r\n #RMSE\r\n e_mf = err_train[np.where(np.isnan(err_train)==False)]\r\n error_train_mf = np.sqrt(np.mean(e_mf**2))\r\n\r\n e2_mf = err_test[np.where(np.isnan(err_test)==False)]\r\n error_test_mf = np.sqrt(np.mean(e2_mf**2))\r\n \r\n\r\n print ('Matrix Factorization Error -> training set: ', error_train_mf)\r\n print ('Matrix Factorization Error -> test set: ', error_test_mf)\r\n\r\nmf()\r\n\r\n#Still getting a high error rate, not comparable to the website mentioned in the assignment doc. \r\n# I need to check the logic again. \r\n#https://medium.com/coinmonks/recommendation-engine-python-401c080c583e; followed this blogpost ", "step-ids": [ 2, 3, 4, 5, 7 ] }
[ 2, 3, 4, 5, 7 ]
<|reserved_special_token_0|> def on_identity_changed(app, identity): g.identity = identity session['identity'] = identity def configure_signals(app): identity_changed.connect(on_identity_changed, app) <|reserved_special_token_0|> def configure_before_handlers(app): @app.before_request def authenticate(): try: g.identity = session['identity'] except Exception: g.identity = Identity(0, 'Login') def configure_extensions(app): db.init_app(app) mail.init_app(app) cache.init_app(app) def configure_context_processors(app): @app.context_processor def archives(): archives = set() for dt in Post.query.from_self(Post.create_date).order_by().filter_by( author_id=g.identity.id): item = dt.create_date.year, dt.create_date.month archives.add(item) if len(archives) > 5: break archives = sorted(list(archives)) return dict(archives=archives) def configure_modules(app, modules): for module, url_prefix in modules: app.register_module(module, url_prefix=url_prefix) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def create_app(config=None, modules=None): if modules is None: modules = DEFAULT_MODULES app = Flask(DEFAULT_APP_NAME) app.config.from_pyfile(config) configure_extensions(app) configure_logging(app) configure_errorhandlers(app) configure_before_handlers(app) configure_template_filters(app) configure_context_processors(app) configure_signals(app) babel = Babel(app) configure_modules(app, modules) return app def on_identity_changed(app, identity): g.identity = identity session['identity'] = identity def configure_signals(app): identity_changed.connect(on_identity_changed, app) def configure_errorhandlers(app): @app.errorhandler(401) def unauthorized(error): flash('Please login to see this page', 'error') return redirect(url_for('account.login')) def configure_before_handlers(app): @app.before_request def authenticate(): try: g.identity = session['identity'] except Exception: g.identity = Identity(0, 'Login') def configure_extensions(app): db.init_app(app) mail.init_app(app) cache.init_app(app) def configure_context_processors(app): @app.context_processor def archives(): archives = set() for dt in Post.query.from_self(Post.create_date).order_by().filter_by( author_id=g.identity.id): item = dt.create_date.year, dt.create_date.month archives.add(item) if len(archives) > 5: break archives = sorted(list(archives)) return dict(archives=archives) def configure_modules(app, modules): for module, url_prefix in modules: app.register_module(module, url_prefix=url_prefix) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def create_app(config=None, modules=None): if modules is None: modules = DEFAULT_MODULES app = Flask(DEFAULT_APP_NAME) app.config.from_pyfile(config) configure_extensions(app) configure_logging(app) configure_errorhandlers(app) configure_before_handlers(app) configure_template_filters(app) configure_context_processors(app) configure_signals(app) babel = Babel(app) configure_modules(app, modules) return app def on_identity_changed(app, identity): g.identity = identity session['identity'] = identity def configure_signals(app): identity_changed.connect(on_identity_changed, app) def configure_errorhandlers(app): @app.errorhandler(401) def unauthorized(error): flash('Please login to see this page', 'error') return redirect(url_for('account.login')) def configure_before_handlers(app): @app.before_request def authenticate(): try: g.identity = session['identity'] except Exception: g.identity = Identity(0, 'Login') def configure_extensions(app): db.init_app(app) mail.init_app(app) cache.init_app(app) def configure_context_processors(app): @app.context_processor def archives(): archives = set() for dt in Post.query.from_self(Post.create_date).order_by().filter_by( author_id=g.identity.id): item = dt.create_date.year, dt.create_date.month archives.add(item) if len(archives) > 5: break archives = sorted(list(archives)) return dict(archives=archives) def configure_modules(app, modules): for module, url_prefix in modules: app.register_module(module, url_prefix=url_prefix) def configure_template_filters(app): @app.template_filter() def timesince(value): return helpers.timesince(value) @app.template_filter() def endtags(value): return helpers.endtags(value) @app.template_filter() def gravatar(email, size): return helpers.gravatar(email, size) @app.template_filter() def format_date(date, s='full'): return helpers.format_date(date, s) @app.template_filter() def format_datetime(time, s='full'): return helpers.format_datetime(time, s) @app.template_filter() def format_yearmonth(date): return '%s-%s' % date <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def create_app(config=None, modules=None): if modules is None: modules = DEFAULT_MODULES app = Flask(DEFAULT_APP_NAME) app.config.from_pyfile(config) configure_extensions(app) configure_logging(app) configure_errorhandlers(app) configure_before_handlers(app) configure_template_filters(app) configure_context_processors(app) configure_signals(app) babel = Babel(app) configure_modules(app, modules) return app def on_identity_changed(app, identity): g.identity = identity session['identity'] = identity def configure_signals(app): identity_changed.connect(on_identity_changed, app) def configure_errorhandlers(app): @app.errorhandler(401) def unauthorized(error): flash('Please login to see this page', 'error') return redirect(url_for('account.login')) def configure_before_handlers(app): @app.before_request def authenticate(): try: g.identity = session['identity'] except Exception: g.identity = Identity(0, 'Login') def configure_extensions(app): db.init_app(app) mail.init_app(app) cache.init_app(app) def configure_context_processors(app): @app.context_processor def archives(): archives = set() for dt in Post.query.from_self(Post.create_date).order_by().filter_by( author_id=g.identity.id): item = dt.create_date.year, dt.create_date.month archives.add(item) if len(archives) > 5: break archives = sorted(list(archives)) return dict(archives=archives) def configure_modules(app, modules): for module, url_prefix in modules: app.register_module(module, url_prefix=url_prefix) def configure_template_filters(app): @app.template_filter() def timesince(value): return helpers.timesince(value) @app.template_filter() def endtags(value): return helpers.endtags(value) @app.template_filter() def gravatar(email, size): return helpers.gravatar(email, size) @app.template_filter() def format_date(date, s='full'): return helpers.format_date(date, s) @app.template_filter() def format_datetime(time, s='full'): return helpers.format_datetime(time, s) @app.template_filter() def format_yearmonth(date): return '%s-%s' % date def configure_logging(app): mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config[ 'DEFAULT_MAIL_SENDER'], app.config['ADMINS'], 'application error', (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) formatter = logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]') debug_log = os.path.join(app.root_path, app.config['DEBUG_LOG']) debug_file_handler = RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10) debug_file_handler.setLevel(logging.DEBUG) debug_file_handler.setFormatter(formatter) app.logger.addHandler(debug_file_handler) error_log = os.path.join(app.root_path, app.config['ERROR_LOG']) error_file_handler = RotatingFileHandler(error_log, maxBytes=100000, backupCount=10) error_file_handler.setLevel(logging.ERROR) error_file_handler.setFormatter(formatter) app.logger.addHandler(error_file_handler) <|reserved_special_token_1|> #!/usr/bin/env python #coding=utf-8 """ __init__.py :license: BSD, see LICENSE for more details. """ import os import logging import sys from logging.handlers import SMTPHandler, RotatingFileHandler from flask import Flask, g, session, request, flash, redirect, jsonify, url_for from flaskext.babel import Babel from bg import helpers from bg.extensions import db, mail, cache, photos, identity_changed, Identity from bg.views import frontend,admin,post,account from bg.models import Post DEFAULT_MODULES = ( (frontend, ""), (post, "/post"), (account, "/account"), (admin, "/admin"),) DEFAULT_APP_NAME = 'bg' def create_app(config=None, modules=None): if modules is None: modules = DEFAULT_MODULES app = Flask(DEFAULT_APP_NAME) #config app.config.from_pyfile(config) configure_extensions(app) configure_logging(app) configure_errorhandlers(app) configure_before_handlers(app) configure_template_filters(app) configure_context_processors(app) configure_signals(app) babel = Babel(app) # register module configure_modules(app, modules) return app def on_identity_changed(app, identity): g.identity = identity session['identity'] = identity def configure_signals(app): identity_changed.connect(on_identity_changed, app) def configure_errorhandlers(app): @app.errorhandler(401) def unauthorized(error): #if request.is_xhr: # return jsonfiy(error=_("Login required")) flash(("Please login to see this page"), "error") #return redirect(url_for("account.login", next=request.path)) return redirect(url_for("account.login")) def configure_before_handlers(app): @app.before_request def authenticate(): try: g.identity = session['identity'] except Exception: g.identity = Identity(0,'Login') def configure_extensions(app): # configure extensions db.init_app(app) #db.app = app #db.create_all() mail.init_app(app) cache.init_app(app) #setup_themes(app) def configure_context_processors(app): @app.context_processor def archives(): archives = set() for dt in Post.query.from_self(Post.create_date).order_by().filter_by(author_id=g.identity.id): item = (dt.create_date.year, dt.create_date.month) archives.add(item) if len(archives) > 5: break archives = sorted(list(archives)) return dict(archives=archives) def configure_modules(app, modules): for module, url_prefix in modules: app.register_module(module, url_prefix=url_prefix) def configure_template_filters(app): @app.template_filter() def timesince(value): return helpers.timesince(value) @app.template_filter() def endtags(value): return helpers.endtags(value) @app.template_filter() def gravatar(email,size): return helpers.gravatar(email,size) @app.template_filter() def format_date(date,s='full'): return helpers.format_date(date,s) @app.template_filter() def format_datetime(time,s='full'): return helpers.format_datetime(time,s) @app.template_filter() def format_yearmonth(date): return '%s-%s'%date def configure_logging(app): mail_handler = \ SMTPHandler(app.config['MAIL_SERVER'], app.config['DEFAULT_MAIL_SENDER'], app.config['ADMINS'], 'application error', ( app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'], )) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) formatter = logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]') debug_log = os.path.join(app.root_path, app.config['DEBUG_LOG']) debug_file_handler = \ RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10) debug_file_handler.setLevel(logging.DEBUG) debug_file_handler.setFormatter(formatter) app.logger.addHandler(debug_file_handler) error_log = os.path.join(app.root_path, app.config['ERROR_LOG']) error_file_handler = \ RotatingFileHandler(error_log, maxBytes=100000, backupCount=10) error_file_handler.setLevel(logging.ERROR) error_file_handler.setFormatter(formatter) app.logger.addHandler(error_file_handler)
flexible
{ "blob_id": "ef124e8c15ef347efd709a5e3fb104c7fd1bccde", "index": 2753, "step-1": "<mask token>\n\n\ndef on_identity_changed(app, identity):\n g.identity = identity\n session['identity'] = identity\n\n\ndef configure_signals(app):\n identity_changed.connect(on_identity_changed, app)\n\n\n<mask token>\n\n\ndef configure_before_handlers(app):\n\n @app.before_request\n def authenticate():\n try:\n g.identity = session['identity']\n except Exception:\n g.identity = Identity(0, 'Login')\n\n\ndef configure_extensions(app):\n db.init_app(app)\n mail.init_app(app)\n cache.init_app(app)\n\n\ndef configure_context_processors(app):\n\n @app.context_processor\n def archives():\n archives = set()\n for dt in Post.query.from_self(Post.create_date).order_by().filter_by(\n author_id=g.identity.id):\n item = dt.create_date.year, dt.create_date.month\n archives.add(item)\n if len(archives) > 5:\n break\n archives = sorted(list(archives))\n return dict(archives=archives)\n\n\ndef configure_modules(app, modules):\n for module, url_prefix in modules:\n app.register_module(module, url_prefix=url_prefix)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef create_app(config=None, modules=None):\n if modules is None:\n modules = DEFAULT_MODULES\n app = Flask(DEFAULT_APP_NAME)\n app.config.from_pyfile(config)\n configure_extensions(app)\n configure_logging(app)\n configure_errorhandlers(app)\n configure_before_handlers(app)\n configure_template_filters(app)\n configure_context_processors(app)\n configure_signals(app)\n babel = Babel(app)\n configure_modules(app, modules)\n return app\n\n\ndef on_identity_changed(app, identity):\n g.identity = identity\n session['identity'] = identity\n\n\ndef configure_signals(app):\n identity_changed.connect(on_identity_changed, app)\n\n\ndef configure_errorhandlers(app):\n\n @app.errorhandler(401)\n def unauthorized(error):\n flash('Please login to see this page', 'error')\n return redirect(url_for('account.login'))\n\n\ndef configure_before_handlers(app):\n\n @app.before_request\n def authenticate():\n try:\n g.identity = session['identity']\n except Exception:\n g.identity = Identity(0, 'Login')\n\n\ndef configure_extensions(app):\n db.init_app(app)\n mail.init_app(app)\n cache.init_app(app)\n\n\ndef configure_context_processors(app):\n\n @app.context_processor\n def archives():\n archives = set()\n for dt in Post.query.from_self(Post.create_date).order_by().filter_by(\n author_id=g.identity.id):\n item = dt.create_date.year, dt.create_date.month\n archives.add(item)\n if len(archives) > 5:\n break\n archives = sorted(list(archives))\n return dict(archives=archives)\n\n\ndef configure_modules(app, modules):\n for module, url_prefix in modules:\n app.register_module(module, url_prefix=url_prefix)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef create_app(config=None, modules=None):\n if modules is None:\n modules = DEFAULT_MODULES\n app = Flask(DEFAULT_APP_NAME)\n app.config.from_pyfile(config)\n configure_extensions(app)\n configure_logging(app)\n configure_errorhandlers(app)\n configure_before_handlers(app)\n configure_template_filters(app)\n configure_context_processors(app)\n configure_signals(app)\n babel = Babel(app)\n configure_modules(app, modules)\n return app\n\n\ndef on_identity_changed(app, identity):\n g.identity = identity\n session['identity'] = identity\n\n\ndef configure_signals(app):\n identity_changed.connect(on_identity_changed, app)\n\n\ndef configure_errorhandlers(app):\n\n @app.errorhandler(401)\n def unauthorized(error):\n flash('Please login to see this page', 'error')\n return redirect(url_for('account.login'))\n\n\ndef configure_before_handlers(app):\n\n @app.before_request\n def authenticate():\n try:\n g.identity = session['identity']\n except Exception:\n g.identity = Identity(0, 'Login')\n\n\ndef configure_extensions(app):\n db.init_app(app)\n mail.init_app(app)\n cache.init_app(app)\n\n\ndef configure_context_processors(app):\n\n @app.context_processor\n def archives():\n archives = set()\n for dt in Post.query.from_self(Post.create_date).order_by().filter_by(\n author_id=g.identity.id):\n item = dt.create_date.year, dt.create_date.month\n archives.add(item)\n if len(archives) > 5:\n break\n archives = sorted(list(archives))\n return dict(archives=archives)\n\n\ndef configure_modules(app, modules):\n for module, url_prefix in modules:\n app.register_module(module, url_prefix=url_prefix)\n\n\ndef configure_template_filters(app):\n\n @app.template_filter()\n def timesince(value):\n return helpers.timesince(value)\n\n @app.template_filter()\n def endtags(value):\n return helpers.endtags(value)\n\n @app.template_filter()\n def gravatar(email, size):\n return helpers.gravatar(email, size)\n\n @app.template_filter()\n def format_date(date, s='full'):\n return helpers.format_date(date, s)\n\n @app.template_filter()\n def format_datetime(time, s='full'):\n return helpers.format_datetime(time, s)\n\n @app.template_filter()\n def format_yearmonth(date):\n return '%s-%s' % date\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef create_app(config=None, modules=None):\n if modules is None:\n modules = DEFAULT_MODULES\n app = Flask(DEFAULT_APP_NAME)\n app.config.from_pyfile(config)\n configure_extensions(app)\n configure_logging(app)\n configure_errorhandlers(app)\n configure_before_handlers(app)\n configure_template_filters(app)\n configure_context_processors(app)\n configure_signals(app)\n babel = Babel(app)\n configure_modules(app, modules)\n return app\n\n\ndef on_identity_changed(app, identity):\n g.identity = identity\n session['identity'] = identity\n\n\ndef configure_signals(app):\n identity_changed.connect(on_identity_changed, app)\n\n\ndef configure_errorhandlers(app):\n\n @app.errorhandler(401)\n def unauthorized(error):\n flash('Please login to see this page', 'error')\n return redirect(url_for('account.login'))\n\n\ndef configure_before_handlers(app):\n\n @app.before_request\n def authenticate():\n try:\n g.identity = session['identity']\n except Exception:\n g.identity = Identity(0, 'Login')\n\n\ndef configure_extensions(app):\n db.init_app(app)\n mail.init_app(app)\n cache.init_app(app)\n\n\ndef configure_context_processors(app):\n\n @app.context_processor\n def archives():\n archives = set()\n for dt in Post.query.from_self(Post.create_date).order_by().filter_by(\n author_id=g.identity.id):\n item = dt.create_date.year, dt.create_date.month\n archives.add(item)\n if len(archives) > 5:\n break\n archives = sorted(list(archives))\n return dict(archives=archives)\n\n\ndef configure_modules(app, modules):\n for module, url_prefix in modules:\n app.register_module(module, url_prefix=url_prefix)\n\n\ndef configure_template_filters(app):\n\n @app.template_filter()\n def timesince(value):\n return helpers.timesince(value)\n\n @app.template_filter()\n def endtags(value):\n return helpers.endtags(value)\n\n @app.template_filter()\n def gravatar(email, size):\n return helpers.gravatar(email, size)\n\n @app.template_filter()\n def format_date(date, s='full'):\n return helpers.format_date(date, s)\n\n @app.template_filter()\n def format_datetime(time, s='full'):\n return helpers.format_datetime(time, s)\n\n @app.template_filter()\n def format_yearmonth(date):\n return '%s-%s' % date\n\n\ndef configure_logging(app):\n mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config[\n 'DEFAULT_MAIL_SENDER'], app.config['ADMINS'], 'application error',\n (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']))\n mail_handler.setLevel(logging.ERROR)\n app.logger.addHandler(mail_handler)\n formatter = logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')\n debug_log = os.path.join(app.root_path, app.config['DEBUG_LOG'])\n debug_file_handler = RotatingFileHandler(debug_log, maxBytes=100000,\n backupCount=10)\n debug_file_handler.setLevel(logging.DEBUG)\n debug_file_handler.setFormatter(formatter)\n app.logger.addHandler(debug_file_handler)\n error_log = os.path.join(app.root_path, app.config['ERROR_LOG'])\n error_file_handler = RotatingFileHandler(error_log, maxBytes=100000,\n backupCount=10)\n error_file_handler.setLevel(logging.ERROR)\n error_file_handler.setFormatter(formatter)\n app.logger.addHandler(error_file_handler)\n", "step-5": "#!/usr/bin/env python\n#coding=utf-8\n\n\"\"\"\n __init__.py\n\n :license: BSD, see LICENSE for more details.\n\"\"\"\n\nimport os\nimport logging\nimport sys\n\nfrom logging.handlers import SMTPHandler, RotatingFileHandler\nfrom flask import Flask, g, session, request, flash, redirect, jsonify, url_for\nfrom flaskext.babel import Babel\n\nfrom bg import helpers\nfrom bg.extensions import db, mail, cache, photos, identity_changed, Identity\n\nfrom bg.views import frontend,admin,post,account\nfrom bg.models import Post\n\nDEFAULT_MODULES = (\n (frontend, \"\"),\n (post, \"/post\"),\n (account, \"/account\"),\n (admin, \"/admin\"),)\n\nDEFAULT_APP_NAME = 'bg'\n\ndef create_app(config=None, modules=None):\n\n if modules is None:\n modules = DEFAULT_MODULES\n\n app = Flask(DEFAULT_APP_NAME)\n\n #config\n app.config.from_pyfile(config)\n configure_extensions(app)\n\n configure_logging(app)\n configure_errorhandlers(app)\n configure_before_handlers(app)\n configure_template_filters(app)\n configure_context_processors(app)\n configure_signals(app)\n babel = Babel(app)\n\n # register module\n configure_modules(app, modules)\n\n return app\n\ndef on_identity_changed(app, identity):\n g.identity = identity\n session['identity'] = identity\n\ndef configure_signals(app):\n identity_changed.connect(on_identity_changed, app)\n\ndef configure_errorhandlers(app):\n\n @app.errorhandler(401)\n def unauthorized(error):\n #if request.is_xhr:\n # return jsonfiy(error=_(\"Login required\"))\n flash((\"Please login to see this page\"), \"error\")\n #return redirect(url_for(\"account.login\", next=request.path))\n return redirect(url_for(\"account.login\"))\n\n\ndef configure_before_handlers(app):\n\n @app.before_request\n def authenticate():\n try:\n g.identity = session['identity']\n except Exception:\n g.identity = Identity(0,'Login')\n\n\ndef configure_extensions(app):\n # configure extensions\n db.init_app(app)\n #db.app = app\n #db.create_all()\n mail.init_app(app)\n cache.init_app(app)\n #setup_themes(app)\n\ndef configure_context_processors(app):\n @app.context_processor\n def archives():\n archives = set()\n for dt in Post.query.from_self(Post.create_date).order_by().filter_by(author_id=g.identity.id):\n item = (dt.create_date.year, dt.create_date.month)\n archives.add(item)\n if len(archives) > 5:\n break\n archives = sorted(list(archives))\n return dict(archives=archives)\n\ndef configure_modules(app, modules):\n\n for module, url_prefix in modules:\n app.register_module(module, url_prefix=url_prefix)\n\ndef configure_template_filters(app):\n\n @app.template_filter()\n def timesince(value):\n return helpers.timesince(value)\n\n @app.template_filter()\n def endtags(value):\n return helpers.endtags(value)\n\n @app.template_filter()\n def gravatar(email,size):\n return helpers.gravatar(email,size)\n\n @app.template_filter()\n def format_date(date,s='full'):\n return helpers.format_date(date,s)\n\n @app.template_filter()\n def format_datetime(time,s='full'):\n return helpers.format_datetime(time,s)\n\n @app.template_filter()\n def format_yearmonth(date):\n return '%s-%s'%date\n\ndef configure_logging(app):\n\n mail_handler = \\\n SMTPHandler(app.config['MAIL_SERVER'],\n app.config['DEFAULT_MAIL_SENDER'],\n app.config['ADMINS'],\n 'application error',\n (\n app.config['MAIL_USERNAME'],\n app.config['MAIL_PASSWORD'],\n ))\n\n mail_handler.setLevel(logging.ERROR)\n app.logger.addHandler(mail_handler)\n\n formatter = logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s '\n '[in %(pathname)s:%(lineno)d]')\n\n debug_log = os.path.join(app.root_path,\n app.config['DEBUG_LOG'])\n\n debug_file_handler = \\\n RotatingFileHandler(debug_log,\n maxBytes=100000,\n backupCount=10)\n\n debug_file_handler.setLevel(logging.DEBUG)\n debug_file_handler.setFormatter(formatter)\n app.logger.addHandler(debug_file_handler)\n\n error_log = os.path.join(app.root_path,\n app.config['ERROR_LOG'])\n\n error_file_handler = \\\n RotatingFileHandler(error_log,\n maxBytes=100000,\n backupCount=10)\n\n error_file_handler.setLevel(logging.ERROR)\n error_file_handler.setFormatter(formatter)\n app.logger.addHandler(error_file_handler)\n\n", "step-ids": [ 6, 8, 9, 10, 13 ] }
[ 6, 8, 9, 10, 13 ]
from PyQt5.QtWidgets import * import sys import math Data = '' class Button: def __init__(self, text, results): self.b = QPushButton(str(text)) self.text = text self.results = results self.b.clicked.connect(lambda: self.handleInput( self.text)) # Important because we need to pass only function name with arguments here that is why we use lambda here def handleInput(self, v): global Data try: if self.results.text() == 'INVALID!': self.results.setText("") if self.results.text() != '': if self.results.text()[-1] in ['*', '+', '-', '/'] and v in ['-', '*', '+', '/', '√', 'CBRT', "SIN", "COS", "LOG", "MOD", "TAN", "MOD"]: return elif v == 'CBRT': self.results.setText(str(round(float(eval(self.results.text())) ** (1 / 3), 4), )) elif v == 'MOD': if '.' in self.results.text(): self.results.setText(str(abs(float(self.results.text())))) else: self.results.setText(str(abs(int(self.results.text())))) elif v == 'LOG': self.results.setText(str(math.log10(abs(float(eval(self.results.text())))))) elif v == 'SQUARE': if '.' in self.results.text(): self.results.setText(str(float(self.results.text()) ** 2)) else: self.results.setText(str(int(self.results.text()) ** 2)) elif v == "SIN": self.results.setText(str(math.sin(float(eval(self.results.text()))))) elif v == "COS": self.results.setText(str(math.cos(float(eval(self.results.text()))))) elif v == "TAN": self.results.setText(str(math.tan(float(eval(self.results.text()))))) elif v == 'x!': if '.' in str(eval(self.results.text())): self.results.setText("INVALID!") else: self.results.setText(str(math.factorial(abs(int(eval(self.results.text())))))) elif self.results.text()[-1] == '/' and v == 0: return elif v == "=": if self.results.text()[-1] in ['*', '-', '.', '+', '/']: return res = eval(self.results.text()) self.results.setText(str(res)) elif v == "AC": self.results.setText("") elif v == "DEL": self.results.setText(self.results.text()[:-1]) elif v == "√" and self.results.text() != '': self.results.setText(str(float(self.results.text()) ** 0.5)) elif v == "√" and self.results.text() == '': return else: current_value = self.results.text() new_value = current_value + str(v) self.results.setText(new_value) else: if type(v) == int: current_value = self.results.text() new_value = current_value + str(v) self.results.setText(new_value) except: self.results.setText("INVALID!") Data = self.results.text() class Widget1(): def setup(self, MainWindow, res): self.widget = QWidget() self.grid = QGridLayout() self.results = QLineEdit() self.results.setText(res) row = 3 col = 0 self.cb = QComboBox() self.cb.addItems(["Basic Mode", "Advanced Mode"]) self.grid.addWidget(self.cb, 0, 1, 1, 2) self.grid.addWidget(self.results, 1, 0, 2, 4) buttons = ["AC", "DEL", "√", "/", 7, 8, 9, "*", 4, 5, 6, "-", 1, 2, 3, "+", 0, ".", "="] for button in buttons: if col > 3: col = 0 row += 1 buttonObject = Button(button, self.results) if button == 0: self.grid.addWidget(buttonObject.b, row, col, 1, 2) col += 1 else: self.grid.addWidget(buttonObject.b, row, col, 1, 1) col += 1 self.widget.setLayout(self.grid) MainWindow.setCentralWidget(self.widget) class Widget2(): def setup(self, MainWindow, res): self.widget = QWidget() self.grid = QGridLayout() self.results = QLineEdit() self.results.setText(res) row = 3 col = 0 self.cb = QComboBox() self.cb.addItems(["Advance Mode", "Normal Mode"]) self.grid.addWidget(self.cb, 0, 1, 1, 2) self.grid.addWidget(self.results, 1, 0, 2, 4) buttons = ["AC", "DEL", "SIN", "COS", 7, 8, 9, "MOD", 4, 5, 6, "TAN", 1, 2, 3, "LOG", 0, "SQUARE", "CBRT", 'x!'] for button in buttons: if col > 3: col = 0 row += 1 buttonObject = Button(button, self.results) self.grid.addWidget(buttonObject.b, row, col, 1, 1) col += 1 self.widget.setLayout(self.grid) MainWindow.setCentralWidget(self.widget) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Calculator") self.widget1 = Widget1() self.widget2 = Widget2() self.startWidget1("") def startWidget1(self, res): global Data self.widget1.setup(self, res) Data = self.widget1.results.text() self.widget1.cb.currentIndexChanged.connect(self.selectionchange1) self.show() def startWidget2(self, res): global Data self.widget2.setup(self, res) Data = self.widget2.results.text() self.widget2.cb.currentIndexChanged.connect(self.selectionchange2) self.show() def selectionchange1(self, i): global Data res = Data self.startWidget2(res) def selectionchange2(self, i): global Data res = Data self.startWidget1(res) if __name__ == "__main__": app = QApplication(sys.argv) w = MainWindow() sys.exit(app.exec_())
normal
{ "blob_id": "b08cface601ee07125090f3ae03a3120974688f2", "index": 8765, "step-1": "<mask token>\n\n\nclass Widget2:\n\n def setup(self, MainWindow, res):\n self.widget = QWidget()\n self.grid = QGridLayout()\n self.results = QLineEdit()\n self.results.setText(res)\n row = 3\n col = 0\n self.cb = QComboBox()\n self.cb.addItems(['Advance Mode', 'Normal Mode'])\n self.grid.addWidget(self.cb, 0, 1, 1, 2)\n self.grid.addWidget(self.results, 1, 0, 2, 4)\n buttons = ['AC', 'DEL', 'SIN', 'COS', 7, 8, 9, 'MOD', 4, 5, 6,\n 'TAN', 1, 2, 3, 'LOG', 0, 'SQUARE', 'CBRT', 'x!']\n for button in buttons:\n if col > 3:\n col = 0\n row += 1\n buttonObject = Button(button, self.results)\n self.grid.addWidget(buttonObject.b, row, col, 1, 1)\n col += 1\n self.widget.setLayout(self.grid)\n MainWindow.setCentralWidget(self.widget)\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle('Calculator')\n self.widget1 = Widget1()\n self.widget2 = Widget2()\n self.startWidget1('')\n\n def startWidget1(self, res):\n global Data\n self.widget1.setup(self, res)\n Data = self.widget1.results.text()\n self.widget1.cb.currentIndexChanged.connect(self.selectionchange1)\n self.show()\n\n def startWidget2(self, res):\n global Data\n self.widget2.setup(self, res)\n Data = self.widget2.results.text()\n self.widget2.cb.currentIndexChanged.connect(self.selectionchange2)\n self.show()\n\n def selectionchange1(self, i):\n global Data\n res = Data\n self.startWidget2(res)\n\n def selectionchange2(self, i):\n global Data\n res = Data\n self.startWidget1(res)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Widget1:\n <mask token>\n\n\nclass Widget2:\n\n def setup(self, MainWindow, res):\n self.widget = QWidget()\n self.grid = QGridLayout()\n self.results = QLineEdit()\n self.results.setText(res)\n row = 3\n col = 0\n self.cb = QComboBox()\n self.cb.addItems(['Advance Mode', 'Normal Mode'])\n self.grid.addWidget(self.cb, 0, 1, 1, 2)\n self.grid.addWidget(self.results, 1, 0, 2, 4)\n buttons = ['AC', 'DEL', 'SIN', 'COS', 7, 8, 9, 'MOD', 4, 5, 6,\n 'TAN', 1, 2, 3, 'LOG', 0, 'SQUARE', 'CBRT', 'x!']\n for button in buttons:\n if col > 3:\n col = 0\n row += 1\n buttonObject = Button(button, self.results)\n self.grid.addWidget(buttonObject.b, row, col, 1, 1)\n col += 1\n self.widget.setLayout(self.grid)\n MainWindow.setCentralWidget(self.widget)\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle('Calculator')\n self.widget1 = Widget1()\n self.widget2 = Widget2()\n self.startWidget1('')\n\n def startWidget1(self, res):\n global Data\n self.widget1.setup(self, res)\n Data = self.widget1.results.text()\n self.widget1.cb.currentIndexChanged.connect(self.selectionchange1)\n self.show()\n\n def startWidget2(self, res):\n global Data\n self.widget2.setup(self, res)\n Data = self.widget2.results.text()\n self.widget2.cb.currentIndexChanged.connect(self.selectionchange2)\n self.show()\n\n def selectionchange1(self, i):\n global Data\n res = Data\n self.startWidget2(res)\n\n def selectionchange2(self, i):\n global Data\n res = Data\n self.startWidget1(res)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Button:\n <mask token>\n <mask token>\n\n\nclass Widget1:\n\n def setup(self, MainWindow, res):\n self.widget = QWidget()\n self.grid = QGridLayout()\n self.results = QLineEdit()\n self.results.setText(res)\n row = 3\n col = 0\n self.cb = QComboBox()\n self.cb.addItems(['Basic Mode', 'Advanced Mode'])\n self.grid.addWidget(self.cb, 0, 1, 1, 2)\n self.grid.addWidget(self.results, 1, 0, 2, 4)\n buttons = ['AC', 'DEL', '√', '/', 7, 8, 9, '*', 4, 5, 6, '-', 1, 2,\n 3, '+', 0, '.', '=']\n for button in buttons:\n if col > 3:\n col = 0\n row += 1\n buttonObject = Button(button, self.results)\n if button == 0:\n self.grid.addWidget(buttonObject.b, row, col, 1, 2)\n col += 1\n else:\n self.grid.addWidget(buttonObject.b, row, col, 1, 1)\n col += 1\n self.widget.setLayout(self.grid)\n MainWindow.setCentralWidget(self.widget)\n\n\nclass Widget2:\n\n def setup(self, MainWindow, res):\n self.widget = QWidget()\n self.grid = QGridLayout()\n self.results = QLineEdit()\n self.results.setText(res)\n row = 3\n col = 0\n self.cb = QComboBox()\n self.cb.addItems(['Advance Mode', 'Normal Mode'])\n self.grid.addWidget(self.cb, 0, 1, 1, 2)\n self.grid.addWidget(self.results, 1, 0, 2, 4)\n buttons = ['AC', 'DEL', 'SIN', 'COS', 7, 8, 9, 'MOD', 4, 5, 6,\n 'TAN', 1, 2, 3, 'LOG', 0, 'SQUARE', 'CBRT', 'x!']\n for button in buttons:\n if col > 3:\n col = 0\n row += 1\n buttonObject = Button(button, self.results)\n self.grid.addWidget(buttonObject.b, row, col, 1, 1)\n col += 1\n self.widget.setLayout(self.grid)\n MainWindow.setCentralWidget(self.widget)\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle('Calculator')\n self.widget1 = Widget1()\n self.widget2 = Widget2()\n self.startWidget1('')\n\n def startWidget1(self, res):\n global Data\n self.widget1.setup(self, res)\n Data = self.widget1.results.text()\n self.widget1.cb.currentIndexChanged.connect(self.selectionchange1)\n self.show()\n\n def startWidget2(self, res):\n global Data\n self.widget2.setup(self, res)\n Data = self.widget2.results.text()\n self.widget2.cb.currentIndexChanged.connect(self.selectionchange2)\n self.show()\n\n def selectionchange1(self, i):\n global Data\n res = Data\n self.startWidget2(res)\n\n def selectionchange2(self, i):\n global Data\n res = Data\n self.startWidget1(res)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass Button:\n\n def __init__(self, text, results):\n self.b = QPushButton(str(text))\n self.text = text\n self.results = results\n self.b.clicked.connect(lambda : self.handleInput(self.text))\n\n def handleInput(self, v):\n global Data\n try:\n if self.results.text() == 'INVALID!':\n self.results.setText('')\n if self.results.text() != '':\n if self.results.text()[-1] in ['*', '+', '-', '/'] and v in [\n '-', '*', '+', '/', '√', 'CBRT', 'SIN', 'COS', 'LOG',\n 'MOD', 'TAN', 'MOD']:\n return\n elif v == 'CBRT':\n self.results.setText(str(round(float(eval(self.results.\n text())) ** (1 / 3), 4)))\n elif v == 'MOD':\n if '.' in self.results.text():\n self.results.setText(str(abs(float(self.results.\n text()))))\n else:\n self.results.setText(str(abs(int(self.results.text())))\n )\n elif v == 'LOG':\n self.results.setText(str(math.log10(abs(float(eval(self\n .results.text()))))))\n elif v == 'SQUARE':\n if '.' in self.results.text():\n self.results.setText(str(float(self.results.text()) **\n 2))\n else:\n self.results.setText(str(int(self.results.text()) ** 2)\n )\n elif v == 'SIN':\n self.results.setText(str(math.sin(float(eval(self.\n results.text())))))\n elif v == 'COS':\n self.results.setText(str(math.cos(float(eval(self.\n results.text())))))\n elif v == 'TAN':\n self.results.setText(str(math.tan(float(eval(self.\n results.text())))))\n elif v == 'x!':\n if '.' in str(eval(self.results.text())):\n self.results.setText('INVALID!')\n else:\n self.results.setText(str(math.factorial(abs(int(\n eval(self.results.text()))))))\n elif self.results.text()[-1] == '/' and v == 0:\n return\n elif v == '=':\n if self.results.text()[-1] in ['*', '-', '.', '+', '/']:\n return\n res = eval(self.results.text())\n self.results.setText(str(res))\n elif v == 'AC':\n self.results.setText('')\n elif v == 'DEL':\n self.results.setText(self.results.text()[:-1])\n elif v == '√' and self.results.text() != '':\n self.results.setText(str(float(self.results.text()) ** 0.5)\n )\n elif v == '√' and self.results.text() == '':\n return\n else:\n current_value = self.results.text()\n new_value = current_value + str(v)\n self.results.setText(new_value)\n elif type(v) == int:\n current_value = self.results.text()\n new_value = current_value + str(v)\n self.results.setText(new_value)\n except:\n self.results.setText('INVALID!')\n Data = self.results.text()\n\n\nclass Widget1:\n\n def setup(self, MainWindow, res):\n self.widget = QWidget()\n self.grid = QGridLayout()\n self.results = QLineEdit()\n self.results.setText(res)\n row = 3\n col = 0\n self.cb = QComboBox()\n self.cb.addItems(['Basic Mode', 'Advanced Mode'])\n self.grid.addWidget(self.cb, 0, 1, 1, 2)\n self.grid.addWidget(self.results, 1, 0, 2, 4)\n buttons = ['AC', 'DEL', '√', '/', 7, 8, 9, '*', 4, 5, 6, '-', 1, 2,\n 3, '+', 0, '.', '=']\n for button in buttons:\n if col > 3:\n col = 0\n row += 1\n buttonObject = Button(button, self.results)\n if button == 0:\n self.grid.addWidget(buttonObject.b, row, col, 1, 2)\n col += 1\n else:\n self.grid.addWidget(buttonObject.b, row, col, 1, 1)\n col += 1\n self.widget.setLayout(self.grid)\n MainWindow.setCentralWidget(self.widget)\n\n\nclass Widget2:\n\n def setup(self, MainWindow, res):\n self.widget = QWidget()\n self.grid = QGridLayout()\n self.results = QLineEdit()\n self.results.setText(res)\n row = 3\n col = 0\n self.cb = QComboBox()\n self.cb.addItems(['Advance Mode', 'Normal Mode'])\n self.grid.addWidget(self.cb, 0, 1, 1, 2)\n self.grid.addWidget(self.results, 1, 0, 2, 4)\n buttons = ['AC', 'DEL', 'SIN', 'COS', 7, 8, 9, 'MOD', 4, 5, 6,\n 'TAN', 1, 2, 3, 'LOG', 0, 'SQUARE', 'CBRT', 'x!']\n for button in buttons:\n if col > 3:\n col = 0\n row += 1\n buttonObject = Button(button, self.results)\n self.grid.addWidget(buttonObject.b, row, col, 1, 1)\n col += 1\n self.widget.setLayout(self.grid)\n MainWindow.setCentralWidget(self.widget)\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle('Calculator')\n self.widget1 = Widget1()\n self.widget2 = Widget2()\n self.startWidget1('')\n\n def startWidget1(self, res):\n global Data\n self.widget1.setup(self, res)\n Data = self.widget1.results.text()\n self.widget1.cb.currentIndexChanged.connect(self.selectionchange1)\n self.show()\n\n def startWidget2(self, res):\n global Data\n self.widget2.setup(self, res)\n Data = self.widget2.results.text()\n self.widget2.cb.currentIndexChanged.connect(self.selectionchange2)\n self.show()\n\n def selectionchange1(self, i):\n global Data\n res = Data\n self.startWidget2(res)\n\n def selectionchange2(self, i):\n global Data\n res = Data\n self.startWidget1(res)\n\n\n<mask token>\n", "step-5": "from PyQt5.QtWidgets import *\nimport sys\nimport math\n\nData = ''\n\n\nclass Button:\n def __init__(self, text, results):\n self.b = QPushButton(str(text))\n self.text = text\n self.results = results\n self.b.clicked.connect(lambda: self.handleInput(\n self.text)) # Important because we need to pass only function name with arguments here that is why we use lambda here\n\n def handleInput(self, v):\n global Data\n try:\n if self.results.text() == 'INVALID!':\n self.results.setText(\"\")\n if self.results.text() != '':\n if self.results.text()[-1] in ['*', '+', '-', '/'] and v in ['-', '*', '+', '/', '√', 'CBRT', \"SIN\",\n \"COS\", \"LOG\", \"MOD\", \"TAN\", \"MOD\"]:\n return\n elif v == 'CBRT':\n self.results.setText(str(round(float(eval(self.results.text())) ** (1 / 3), 4), ))\n elif v == 'MOD':\n if '.' in self.results.text():\n self.results.setText(str(abs(float(self.results.text()))))\n else:\n self.results.setText(str(abs(int(self.results.text()))))\n elif v == 'LOG':\n self.results.setText(str(math.log10(abs(float(eval(self.results.text()))))))\n elif v == 'SQUARE':\n if '.' in self.results.text():\n self.results.setText(str(float(self.results.text()) ** 2))\n else:\n self.results.setText(str(int(self.results.text()) ** 2))\n elif v == \"SIN\":\n self.results.setText(str(math.sin(float(eval(self.results.text())))))\n elif v == \"COS\":\n self.results.setText(str(math.cos(float(eval(self.results.text())))))\n elif v == \"TAN\":\n self.results.setText(str(math.tan(float(eval(self.results.text())))))\n elif v == 'x!':\n if '.' in str(eval(self.results.text())):\n self.results.setText(\"INVALID!\")\n else:\n self.results.setText(str(math.factorial(abs(int(eval(self.results.text()))))))\n elif self.results.text()[-1] == '/' and v == 0:\n return\n elif v == \"=\":\n if self.results.text()[-1] in ['*', '-', '.', '+', '/']:\n return\n res = eval(self.results.text())\n self.results.setText(str(res))\n elif v == \"AC\":\n self.results.setText(\"\")\n elif v == \"DEL\":\n self.results.setText(self.results.text()[:-1])\n elif v == \"√\" and self.results.text() != '':\n self.results.setText(str(float(self.results.text()) ** 0.5))\n elif v == \"√\" and self.results.text() == '':\n return\n else:\n current_value = self.results.text()\n new_value = current_value + str(v)\n self.results.setText(new_value)\n else:\n if type(v) == int:\n current_value = self.results.text()\n new_value = current_value + str(v)\n self.results.setText(new_value)\n except:\n self.results.setText(\"INVALID!\")\n Data = self.results.text()\n\n\nclass Widget1():\n def setup(self, MainWindow, res):\n self.widget = QWidget()\n self.grid = QGridLayout()\n self.results = QLineEdit()\n self.results.setText(res)\n\n row = 3\n col = 0\n self.cb = QComboBox()\n self.cb.addItems([\"Basic Mode\", \"Advanced Mode\"])\n self.grid.addWidget(self.cb, 0, 1, 1, 2)\n self.grid.addWidget(self.results, 1, 0, 2, 4)\n buttons = [\"AC\", \"DEL\", \"√\", \"/\",\n 7, 8, 9, \"*\",\n 4, 5, 6, \"-\",\n 1, 2, 3, \"+\",\n 0, \".\", \"=\"]\n for button in buttons:\n if col > 3:\n col = 0\n row += 1\n\n buttonObject = Button(button, self.results)\n\n if button == 0:\n self.grid.addWidget(buttonObject.b, row, col, 1, 2)\n col += 1\n else:\n self.grid.addWidget(buttonObject.b, row, col, 1, 1)\n\n col += 1\n\n self.widget.setLayout(self.grid)\n MainWindow.setCentralWidget(self.widget)\n\n\nclass Widget2():\n def setup(self, MainWindow, res):\n self.widget = QWidget()\n self.grid = QGridLayout()\n self.results = QLineEdit()\n self.results.setText(res)\n\n row = 3\n col = 0\n self.cb = QComboBox()\n self.cb.addItems([\"Advance Mode\", \"Normal Mode\"])\n self.grid.addWidget(self.cb, 0, 1, 1, 2)\n self.grid.addWidget(self.results, 1, 0, 2, 4)\n buttons = [\"AC\", \"DEL\", \"SIN\", \"COS\",\n 7, 8, 9, \"MOD\",\n 4, 5, 6, \"TAN\",\n 1, 2, 3, \"LOG\",\n 0, \"SQUARE\", \"CBRT\", 'x!']\n for button in buttons:\n if col > 3:\n col = 0\n row += 1\n buttonObject = Button(button, self.results)\n\n self.grid.addWidget(buttonObject.b, row, col, 1, 1)\n\n col += 1\n\n self.widget.setLayout(self.grid)\n MainWindow.setCentralWidget(self.widget)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"Calculator\")\n self.widget1 = Widget1()\n self.widget2 = Widget2()\n self.startWidget1(\"\")\n\n def startWidget1(self, res):\n global Data\n self.widget1.setup(self, res)\n Data = self.widget1.results.text()\n self.widget1.cb.currentIndexChanged.connect(self.selectionchange1)\n self.show()\n\n def startWidget2(self, res):\n global Data\n self.widget2.setup(self, res)\n Data = self.widget2.results.text()\n self.widget2.cb.currentIndexChanged.connect(self.selectionchange2)\n self.show()\n\n def selectionchange1(self, i):\n global Data\n res = Data\n self.startWidget2(res)\n\n def selectionchange2(self, i):\n global Data\n res = Data\n self.startWidget1(res)\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n w = MainWindow()\n sys.exit(app.exec_())\n\n\n\n\n", "step-ids": [ 8, 9, 11, 13, 17 ] }
[ 8, 9, 11, 13, 17 ]
import random my_randoms = random.sample(100, 10) print(my_randoms)
normal
{ "blob_id": "d39f6fca80f32a4d13764eb5cfb29999785b1d16", "index": 1629, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(my_randoms)\n", "step-3": "<mask token>\nmy_randoms = random.sample(100, 10)\nprint(my_randoms)\n", "step-4": "import random\nmy_randoms = random.sample(100, 10)\nprint(my_randoms)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def hdfs_get_filelist(blob_path, delimiter='_'): """ Lists hdfs dir and returns named tuples with information of file based on its filename. """ def hdfs_listdir(blob_path): command = 'hdfs dfs -ls ' + blob_path p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() files = [item.rstrip('\n').split()[-1] for item in p.stdout.readlines() ] if len(files) > 0: files.pop(0) qty_files = len(files) return files, qty_files files, qty_files = hdfs_listdir(blob_path) kpis = [] if qty_files > 0: KPI = namedtuple('KPI', ['filepath', 'filename', 'kpi_name', 'initial_date', 'final_date', 'key', 'extension']) for file in files: filename, ext = basename(file), splitext(basename(file))[1] if ext == '.json': splits = 3 kpi = KPI(filepath=file, filename=filename, kpi_name= filename.rsplit(delimiter, splits)[0], initial_date= filename.rsplit(delimiter, splits)[1], final_date= filename.rsplit(delimiter, splits)[2], key=splitext( filename.rsplit(delimiter, splits)[3])[0], extension=ext) else: splits = 1 kpi = KPI(filepath=file, filename=filename, kpi_name= filename.rsplit(delimiter, splits)[0], initial_date= None, final_date=None, key=splitext(filename.rsplit( delimiter, splits)[1])[0], extension=ext) kpis.append(kpi) return kpis, len(kpis) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def hdfs_get_filelist(blob_path, delimiter='_'): """ Lists hdfs dir and returns named tuples with information of file based on its filename. """ def hdfs_listdir(blob_path): command = 'hdfs dfs -ls ' + blob_path p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() files = [item.rstrip('\n').split()[-1] for item in p.stdout.readlines() ] if len(files) > 0: files.pop(0) qty_files = len(files) return files, qty_files files, qty_files = hdfs_listdir(blob_path) kpis = [] if qty_files > 0: KPI = namedtuple('KPI', ['filepath', 'filename', 'kpi_name', 'initial_date', 'final_date', 'key', 'extension']) for file in files: filename, ext = basename(file), splitext(basename(file))[1] if ext == '.json': splits = 3 kpi = KPI(filepath=file, filename=filename, kpi_name= filename.rsplit(delimiter, splits)[0], initial_date= filename.rsplit(delimiter, splits)[1], final_date= filename.rsplit(delimiter, splits)[2], key=splitext( filename.rsplit(delimiter, splits)[3])[0], extension=ext) else: splits = 1 kpi = KPI(filepath=file, filename=filename, kpi_name= filename.rsplit(delimiter, splits)[0], initial_date= None, final_date=None, key=splitext(filename.rsplit( delimiter, splits)[1])[0], extension=ext) kpis.append(kpi) return kpis, len(kpis) kpis, files = hdfs_get_filelist( 'wasbs://hdiprojsupplydatalake-2018-07-12t15-58-09-078z@hdiprojsupplydatalake.blob.core.windows.net/estrutura_final/' ) <|reserved_special_token_1|> import subprocess from collections import namedtuple from os.path import basename, splitext def hdfs_get_filelist(blob_path, delimiter='_'): """ Lists hdfs dir and returns named tuples with information of file based on its filename. """ def hdfs_listdir(blob_path): command = 'hdfs dfs -ls ' + blob_path p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() files = [item.rstrip('\n').split()[-1] for item in p.stdout.readlines() ] if len(files) > 0: files.pop(0) qty_files = len(files) return files, qty_files files, qty_files = hdfs_listdir(blob_path) kpis = [] if qty_files > 0: KPI = namedtuple('KPI', ['filepath', 'filename', 'kpi_name', 'initial_date', 'final_date', 'key', 'extension']) for file in files: filename, ext = basename(file), splitext(basename(file))[1] if ext == '.json': splits = 3 kpi = KPI(filepath=file, filename=filename, kpi_name= filename.rsplit(delimiter, splits)[0], initial_date= filename.rsplit(delimiter, splits)[1], final_date= filename.rsplit(delimiter, splits)[2], key=splitext( filename.rsplit(delimiter, splits)[3])[0], extension=ext) else: splits = 1 kpi = KPI(filepath=file, filename=filename, kpi_name= filename.rsplit(delimiter, splits)[0], initial_date= None, final_date=None, key=splitext(filename.rsplit( delimiter, splits)[1])[0], extension=ext) kpis.append(kpi) return kpis, len(kpis) kpis, files = hdfs_get_filelist( 'wasbs://hdiprojsupplydatalake-2018-07-12t15-58-09-078z@hdiprojsupplydatalake.blob.core.windows.net/estrutura_final/' ) <|reserved_special_token_1|> import subprocess from collections import namedtuple from os.path import basename, splitext def hdfs_get_filelist(blob_path, delimiter="_"): """ Lists hdfs dir and returns named tuples with information of file based on its filename. """ def hdfs_listdir(blob_path): command = 'hdfs dfs -ls ' + blob_path p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() files = [item.rstrip("\n").split()[-1] for item in p.stdout.readlines()] if len(files) > 0: files.pop(0) # remove summary from ls: "found n items". qty_files = len(files) return files, qty_files files, qty_files = hdfs_listdir(blob_path) kpis = [] # If there are items in dir. if qty_files > 0: KPI = namedtuple('KPI', ["filepath", "filename", "kpi_name", "initial_date", "final_date", "key", "extension"]) for file in files: filename, ext = basename(file), splitext(basename(file))[1] if ext == ".json": splits = 3 kpi = KPI( filepath=file , filename=filename , kpi_name=filename.rsplit(delimiter, splits)[0] , initial_date=filename.rsplit(delimiter, splits)[1] , final_date=filename.rsplit(delimiter, splits)[2] , key=splitext(filename.rsplit(delimiter, splits)[3])[0] , extension=ext ) else: # ext != ".json": splits = 1 kpi = KPI( filepath=file , filename=filename , kpi_name=filename.rsplit(delimiter, splits)[0] , initial_date=None , final_date=None , key=splitext(filename.rsplit(delimiter, splits)[1])[0] , extension=ext ) kpis.append(kpi) return kpis, len(kpis) kpis, files = hdfs_get_filelist("wasbs://hdiprojsupplydatalake-2018-07-12t15-58-09-078z@hdiprojsupplydatalake.blob.core.windows.net/estrutura_final/")
flexible
{ "blob_id": "6909e70db4f907e26ad604f95c79a405010907bd", "index": 2086, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef hdfs_get_filelist(blob_path, delimiter='_'):\n \"\"\" Lists hdfs dir and returns named tuples with information of file based on its filename. \"\"\"\n\n def hdfs_listdir(blob_path):\n command = 'hdfs dfs -ls ' + blob_path\n p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n p.wait()\n files = [item.rstrip('\\n').split()[-1] for item in p.stdout.readlines()\n ]\n if len(files) > 0:\n files.pop(0)\n qty_files = len(files)\n return files, qty_files\n files, qty_files = hdfs_listdir(blob_path)\n kpis = []\n if qty_files > 0:\n KPI = namedtuple('KPI', ['filepath', 'filename', 'kpi_name',\n 'initial_date', 'final_date', 'key', 'extension'])\n for file in files:\n filename, ext = basename(file), splitext(basename(file))[1]\n if ext == '.json':\n splits = 3\n kpi = KPI(filepath=file, filename=filename, kpi_name=\n filename.rsplit(delimiter, splits)[0], initial_date=\n filename.rsplit(delimiter, splits)[1], final_date=\n filename.rsplit(delimiter, splits)[2], key=splitext(\n filename.rsplit(delimiter, splits)[3])[0], extension=ext)\n else:\n splits = 1\n kpi = KPI(filepath=file, filename=filename, kpi_name=\n filename.rsplit(delimiter, splits)[0], initial_date=\n None, final_date=None, key=splitext(filename.rsplit(\n delimiter, splits)[1])[0], extension=ext)\n kpis.append(kpi)\n return kpis, len(kpis)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef hdfs_get_filelist(blob_path, delimiter='_'):\n \"\"\" Lists hdfs dir and returns named tuples with information of file based on its filename. \"\"\"\n\n def hdfs_listdir(blob_path):\n command = 'hdfs dfs -ls ' + blob_path\n p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n p.wait()\n files = [item.rstrip('\\n').split()[-1] for item in p.stdout.readlines()\n ]\n if len(files) > 0:\n files.pop(0)\n qty_files = len(files)\n return files, qty_files\n files, qty_files = hdfs_listdir(blob_path)\n kpis = []\n if qty_files > 0:\n KPI = namedtuple('KPI', ['filepath', 'filename', 'kpi_name',\n 'initial_date', 'final_date', 'key', 'extension'])\n for file in files:\n filename, ext = basename(file), splitext(basename(file))[1]\n if ext == '.json':\n splits = 3\n kpi = KPI(filepath=file, filename=filename, kpi_name=\n filename.rsplit(delimiter, splits)[0], initial_date=\n filename.rsplit(delimiter, splits)[1], final_date=\n filename.rsplit(delimiter, splits)[2], key=splitext(\n filename.rsplit(delimiter, splits)[3])[0], extension=ext)\n else:\n splits = 1\n kpi = KPI(filepath=file, filename=filename, kpi_name=\n filename.rsplit(delimiter, splits)[0], initial_date=\n None, final_date=None, key=splitext(filename.rsplit(\n delimiter, splits)[1])[0], extension=ext)\n kpis.append(kpi)\n return kpis, len(kpis)\n\n\nkpis, files = hdfs_get_filelist(\n 'wasbs://hdiprojsupplydatalake-2018-07-12t15-58-09-078z@hdiprojsupplydatalake.blob.core.windows.net/estrutura_final/'\n )\n", "step-4": "import subprocess\nfrom collections import namedtuple\nfrom os.path import basename, splitext\n\n\ndef hdfs_get_filelist(blob_path, delimiter='_'):\n \"\"\" Lists hdfs dir and returns named tuples with information of file based on its filename. \"\"\"\n\n def hdfs_listdir(blob_path):\n command = 'hdfs dfs -ls ' + blob_path\n p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n p.wait()\n files = [item.rstrip('\\n').split()[-1] for item in p.stdout.readlines()\n ]\n if len(files) > 0:\n files.pop(0)\n qty_files = len(files)\n return files, qty_files\n files, qty_files = hdfs_listdir(blob_path)\n kpis = []\n if qty_files > 0:\n KPI = namedtuple('KPI', ['filepath', 'filename', 'kpi_name',\n 'initial_date', 'final_date', 'key', 'extension'])\n for file in files:\n filename, ext = basename(file), splitext(basename(file))[1]\n if ext == '.json':\n splits = 3\n kpi = KPI(filepath=file, filename=filename, kpi_name=\n filename.rsplit(delimiter, splits)[0], initial_date=\n filename.rsplit(delimiter, splits)[1], final_date=\n filename.rsplit(delimiter, splits)[2], key=splitext(\n filename.rsplit(delimiter, splits)[3])[0], extension=ext)\n else:\n splits = 1\n kpi = KPI(filepath=file, filename=filename, kpi_name=\n filename.rsplit(delimiter, splits)[0], initial_date=\n None, final_date=None, key=splitext(filename.rsplit(\n delimiter, splits)[1])[0], extension=ext)\n kpis.append(kpi)\n return kpis, len(kpis)\n\n\nkpis, files = hdfs_get_filelist(\n 'wasbs://hdiprojsupplydatalake-2018-07-12t15-58-09-078z@hdiprojsupplydatalake.blob.core.windows.net/estrutura_final/'\n )\n", "step-5": "import subprocess\nfrom collections import namedtuple\nfrom os.path import basename, splitext\n\n\ndef hdfs_get_filelist(blob_path, delimiter=\"_\"):\n \"\"\" Lists hdfs dir and returns named tuples with information of file based on its filename. \"\"\"\n\n def hdfs_listdir(blob_path):\n command = 'hdfs dfs -ls ' + blob_path\n p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n p.wait()\n files = [item.rstrip(\"\\n\").split()[-1] for item in p.stdout.readlines()]\n if len(files) > 0:\n files.pop(0) # remove summary from ls: \"found n items\".\n qty_files = len(files)\n return files, qty_files\n\n files, qty_files = hdfs_listdir(blob_path)\n kpis = []\n # If there are items in dir.\n if qty_files > 0:\n KPI = namedtuple('KPI', [\"filepath\", \"filename\", \"kpi_name\", \"initial_date\", \"final_date\", \"key\", \"extension\"])\n for file in files:\n filename, ext = basename(file), splitext(basename(file))[1]\n if ext == \".json\":\n splits = 3\n kpi = KPI(\n filepath=file\n , filename=filename\n , kpi_name=filename.rsplit(delimiter, splits)[0]\n , initial_date=filename.rsplit(delimiter, splits)[1]\n , final_date=filename.rsplit(delimiter, splits)[2]\n , key=splitext(filename.rsplit(delimiter, splits)[3])[0]\n , extension=ext\n )\n else: # ext != \".json\":\n splits = 1\n kpi = KPI(\n filepath=file\n , filename=filename\n , kpi_name=filename.rsplit(delimiter, splits)[0]\n , initial_date=None\n , final_date=None\n , key=splitext(filename.rsplit(delimiter, splits)[1])[0]\n , extension=ext\n )\n kpis.append(kpi)\n return kpis, len(kpis)\n\n\nkpis, files = hdfs_get_filelist(\"wasbs://hdiprojsupplydatalake-2018-07-12t15-58-09-078z@hdiprojsupplydatalake.blob.core.windows.net/estrutura_final/\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def transform_word(word): """ 将低频词转为四种形式之一。 """ if any(c.isdigit() for c in word): return '_NUMERIC_' if word.isupper(): return '_ALL_CAP_' if word[-1].isupper(): return '_LAST_CAP_' return '_RARE_' def sub_rare(fname, out_name): count_dict = defaultdict(int) with open(fname) as f: for line in f: line = line.strip() if not line: continue word = line.partition(' ')[0] count_dict[word] += 1 fout = open(out_name, 'w') with open(fname) as f: for line in f: line = line.strip() if not line: fout.write('\n') continue word, sep, tag = line.partition(' ') if count_dict[word] < 5: word = transform_word(word) fout.write('%s %s\n' % (word, tag)) fout.close() return <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def transform_word(word): """ 将低频词转为四种形式之一。 """ if any(c.isdigit() for c in word): return '_NUMERIC_' if word.isupper(): return '_ALL_CAP_' if word[-1].isupper(): return '_LAST_CAP_' return '_RARE_' def sub_rare(fname, out_name): count_dict = defaultdict(int) with open(fname) as f: for line in f: line = line.strip() if not line: continue word = line.partition(' ')[0] count_dict[word] += 1 fout = open(out_name, 'w') with open(fname) as f: for line in f: line = line.strip() if not line: fout.write('\n') continue word, sep, tag = line.partition(' ') if count_dict[word] < 5: word = transform_word(word) fout.write('%s %s\n' % (word, tag)) fout.close() return if __name__ == '__main__': fname = sys.argv[1] sub_rare(fname, fname + '.sub_rare') <|reserved_special_token_1|> import sys from collections import defaultdict def transform_word(word): """ 将低频词转为四种形式之一。 """ if any(c.isdigit() for c in word): return '_NUMERIC_' if word.isupper(): return '_ALL_CAP_' if word[-1].isupper(): return '_LAST_CAP_' return '_RARE_' def sub_rare(fname, out_name): count_dict = defaultdict(int) with open(fname) as f: for line in f: line = line.strip() if not line: continue word = line.partition(' ')[0] count_dict[word] += 1 fout = open(out_name, 'w') with open(fname) as f: for line in f: line = line.strip() if not line: fout.write('\n') continue word, sep, tag = line.partition(' ') if count_dict[word] < 5: word = transform_word(word) fout.write('%s %s\n' % (word, tag)) fout.close() return if __name__ == '__main__': fname = sys.argv[1] sub_rare(fname, fname + '.sub_rare') <|reserved_special_token_1|> #!/usr/bin/env python #encoding:utf8 import sys from collections import defaultdict def transform_word(word): ''' 将低频词转为四种形式之一。 ''' if any(c.isdigit() for c in word): return '_NUMERIC_' if word.isupper(): return '_ALL_CAP_' if word[-1].isupper(): return '_LAST_CAP_' return '_RARE_' def sub_rare(fname, out_name): count_dict = defaultdict(int) # 先统计词频。 with open(fname) as f: for line in f: line = line.strip() if not line: continue word = line.partition(' ')[0] count_dict[word] += 1 # 然后替换低频词。 fout = open(out_name, 'w') with open(fname) as f: for line in f: line = line.strip() if not line: fout.write('\n') continue word, sep, tag = line.partition(' ') if count_dict[word] < 5: # word = '_RARE_' word = transform_word(word) fout.write('%s %s\n' % (word, tag)) fout.close() return if __name__ == '__main__': fname = sys.argv[1] sub_rare(fname, fname + '.sub_rare')
flexible
{ "blob_id": "92a1f86ce8cc9563d455f9b1336dbcd298f01b6d", "index": 1747, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef transform_word(word):\n \"\"\"\n 将低频词转为四种形式之一。\n \"\"\"\n if any(c.isdigit() for c in word):\n return '_NUMERIC_'\n if word.isupper():\n return '_ALL_CAP_'\n if word[-1].isupper():\n return '_LAST_CAP_'\n return '_RARE_'\n\n\ndef sub_rare(fname, out_name):\n count_dict = defaultdict(int)\n with open(fname) as f:\n for line in f:\n line = line.strip()\n if not line:\n continue\n word = line.partition(' ')[0]\n count_dict[word] += 1\n fout = open(out_name, 'w')\n with open(fname) as f:\n for line in f:\n line = line.strip()\n if not line:\n fout.write('\\n')\n continue\n word, sep, tag = line.partition(' ')\n if count_dict[word] < 5:\n word = transform_word(word)\n fout.write('%s %s\\n' % (word, tag))\n fout.close()\n return\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef transform_word(word):\n \"\"\"\n 将低频词转为四种形式之一。\n \"\"\"\n if any(c.isdigit() for c in word):\n return '_NUMERIC_'\n if word.isupper():\n return '_ALL_CAP_'\n if word[-1].isupper():\n return '_LAST_CAP_'\n return '_RARE_'\n\n\ndef sub_rare(fname, out_name):\n count_dict = defaultdict(int)\n with open(fname) as f:\n for line in f:\n line = line.strip()\n if not line:\n continue\n word = line.partition(' ')[0]\n count_dict[word] += 1\n fout = open(out_name, 'w')\n with open(fname) as f:\n for line in f:\n line = line.strip()\n if not line:\n fout.write('\\n')\n continue\n word, sep, tag = line.partition(' ')\n if count_dict[word] < 5:\n word = transform_word(word)\n fout.write('%s %s\\n' % (word, tag))\n fout.close()\n return\n\n\nif __name__ == '__main__':\n fname = sys.argv[1]\n sub_rare(fname, fname + '.sub_rare')\n", "step-4": "import sys\nfrom collections import defaultdict\n\n\ndef transform_word(word):\n \"\"\"\n 将低频词转为四种形式之一。\n \"\"\"\n if any(c.isdigit() for c in word):\n return '_NUMERIC_'\n if word.isupper():\n return '_ALL_CAP_'\n if word[-1].isupper():\n return '_LAST_CAP_'\n return '_RARE_'\n\n\ndef sub_rare(fname, out_name):\n count_dict = defaultdict(int)\n with open(fname) as f:\n for line in f:\n line = line.strip()\n if not line:\n continue\n word = line.partition(' ')[0]\n count_dict[word] += 1\n fout = open(out_name, 'w')\n with open(fname) as f:\n for line in f:\n line = line.strip()\n if not line:\n fout.write('\\n')\n continue\n word, sep, tag = line.partition(' ')\n if count_dict[word] < 5:\n word = transform_word(word)\n fout.write('%s %s\\n' % (word, tag))\n fout.close()\n return\n\n\nif __name__ == '__main__':\n fname = sys.argv[1]\n sub_rare(fname, fname + '.sub_rare')\n", "step-5": "#!/usr/bin/env python\n#encoding:utf8\nimport sys\nfrom collections import defaultdict\n\ndef transform_word(word):\n '''\n 将低频词转为四种形式之一。\n '''\n if any(c.isdigit() for c in word):\n return '_NUMERIC_'\n if word.isupper():\n return '_ALL_CAP_'\n if word[-1].isupper():\n return '_LAST_CAP_'\n return '_RARE_'\ndef sub_rare(fname, out_name):\n count_dict = defaultdict(int)\n # 先统计词频。\n with open(fname) as f:\n for line in f:\n line = line.strip()\n if not line:\n continue\n word = line.partition(' ')[0]\n count_dict[word] += 1\n # 然后替换低频词。\n fout = open(out_name, 'w')\n with open(fname) as f:\n for line in f:\n line = line.strip()\n if not line:\n fout.write('\\n')\n continue\n word, sep, tag = line.partition(' ')\n if count_dict[word] < 5:\n # word = '_RARE_'\n word = transform_word(word)\n fout.write('%s %s\\n' % (word, tag))\n fout.close()\n return\n\nif __name__ == '__main__':\n fname = sys.argv[1]\n sub_rare(fname, fname + '.sub_rare')\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
<|reserved_special_token_0|> class CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins .RetrieveModelMixin): queryset = Comment.objects.all() def get_serializer_class(self): if self.action == 'retrieve': if self.get_object().level < 3: return CommentSerializer return AllCommentSerializer <|reserved_special_token_1|> <|reserved_special_token_0|> class PostViewSet(viewsets.ModelViewSet): <|reserved_special_token_0|> <|reserved_special_token_0|> class CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins .RetrieveModelMixin): queryset = Comment.objects.all() def get_serializer_class(self): if self.action == 'retrieve': if self.get_object().level < 3: return CommentSerializer return AllCommentSerializer <|reserved_special_token_1|> <|reserved_special_token_0|> class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() class CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins .RetrieveModelMixin): queryset = Comment.objects.all() def get_serializer_class(self): if self.action == 'retrieve': if self.get_object().level < 3: return CommentSerializer return AllCommentSerializer <|reserved_special_token_1|> from rest_framework import viewsets, mixins from .models import Comment, Post from .serializer import CommentSerializer, PostSerializer, AllCommentSerializer class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() class CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins .RetrieveModelMixin): queryset = Comment.objects.all() def get_serializer_class(self): if self.action == 'retrieve': if self.get_object().level < 3: return CommentSerializer return AllCommentSerializer
flexible
{ "blob_id": "9bc13c608c079cbf23ed04f29edd1fd836214cde", "index": 282, "step-1": "<mask token>\n\n\nclass CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins\n .RetrieveModelMixin):\n queryset = Comment.objects.all()\n\n def get_serializer_class(self):\n if self.action == 'retrieve':\n if self.get_object().level < 3:\n return CommentSerializer\n return AllCommentSerializer\n", "step-2": "<mask token>\n\n\nclass PostViewSet(viewsets.ModelViewSet):\n <mask token>\n <mask token>\n\n\nclass CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins\n .RetrieveModelMixin):\n queryset = Comment.objects.all()\n\n def get_serializer_class(self):\n if self.action == 'retrieve':\n if self.get_object().level < 3:\n return CommentSerializer\n return AllCommentSerializer\n", "step-3": "<mask token>\n\n\nclass PostViewSet(viewsets.ModelViewSet):\n serializer_class = PostSerializer\n queryset = Post.objects.all()\n\n\nclass CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins\n .RetrieveModelMixin):\n queryset = Comment.objects.all()\n\n def get_serializer_class(self):\n if self.action == 'retrieve':\n if self.get_object().level < 3:\n return CommentSerializer\n return AllCommentSerializer\n", "step-4": "from rest_framework import viewsets, mixins\nfrom .models import Comment, Post\nfrom .serializer import CommentSerializer, PostSerializer, AllCommentSerializer\n\n\nclass PostViewSet(viewsets.ModelViewSet):\n serializer_class = PostSerializer\n queryset = Post.objects.all()\n\n\nclass CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins\n .RetrieveModelMixin):\n queryset = Comment.objects.all()\n\n def get_serializer_class(self):\n if self.action == 'retrieve':\n if self.get_object().level < 3:\n return CommentSerializer\n return AllCommentSerializer\n", "step-5": null, "step-ids": [ 3, 4, 5, 6 ] }
[ 3, 4, 5, 6 ]
import numpy as np from scipy.stats import multivariate_normal from functions.io_data import read_data, write_data np.random.seed(0) class IsingModel(): def __init__(self, image, J, rate, sigma): self.width = image.shape[0] self.height = image.shape[1] self._J = J self._rate = rate self._sigma = sigma self.image, self.logodds = self.presenting_image(image) def presenting_image(self, image): logodds = multivariate_normal.logpdf(image.flatten(), mean=+1, cov=self._sigma ** 2) - multivariate_normal.logpdf(image.flatten(), mean=-1, cov=self._sigma ** 2) logodds = np.reshape(logodds, image.shape) pr_plus1 = 1 / (1 + np.exp(-1*logodds)) # sigmoid(logodds) # plus 1 -> +1 -> 1 / (1 + exp(logodds)) -> sigmoid(x) = 1 / (1 + exp{x}) return 2 * pr_plus1 - 1, logodds def neighbors(self, x, y): nbrs = [] if x == 0: nbrs.append(self.image[self.width - 1, y]) else: nbrs.append(self.image[x - 1, y]) if x == self.width - 1: nbrs.append(self.image[0, y]) else: nbrs.append(self.image[x + 1, y]) if y == 0: nbrs.append(self.image[x, self.height - 1]) else: nbrs.append(self.image[x, y - 1]) if y == self.height - 1: nbrs.append(self.image[x, 0]) else: nbrs.append(self.image[x, y + 1]) return nbrs def interaction_potentials(self, x, y): nbrs = self.neighbors(x, y) return sum(nbrs) def variational_inference(self, x, y): E = self._J * self.interaction_potentials(x, y) self.image[x, y] = (1 - self._rate) * self.image[x, y] + self._rate * np.tanh(E + 0.5 * self.logodds[x, y]) def denoising(image, iterations, rate, sigma, J=3): ising = IsingModel(image, J=J, rate=rate, sigma=sigma) for i in range(iterations): for x in range(image.shape[0]): for y in range(image.shape[1]): ising.variational_inference(x, y) return ising.image if __name__ == "__main__": for img in range(1,5): print("Denoising for image " + str(img)) data, image = read_data("../a1/"+str(img)+"_noise.txt", True) print(data.shape) print(image.shape) image[image == 0] = -1 image[image == 255] = 1 iterations = 15 J = 3 sigma = 2 rate = 0.5 d_img = denoising(image, iterations=iterations, rate=rate, sigma=sigma) d_img[d_img >= 0] = 255 d_img[d_img < 0] = 0 print(d_img.shape) height = d_img.shape[0] width = d_img.shape[1] counter = 0 for i in range(0, width): for j in range(0, height): data[counter][2] = d_img[j][i][0] counter = counter + 1 write_data(data, "../output/vi/"+str(img)+"_denoise.txt") read_data("../output/vi/"+str(img)+"_denoise.txt", True, save=True, save_name="../output/vi/"+str(img)+"_denoise.png") print("Finished writing data. Please check "+str(img)+"_denoise.png \n")
normal
{ "blob_id": "6aa74826f9ca0803fa8c1d5af1d4cec4980e2ce6", "index": 9064, "step-1": "<mask token>\n\n\nclass IsingModel:\n\n def __init__(self, image, J, rate, sigma):\n self.width = image.shape[0]\n self.height = image.shape[1]\n self._J = J\n self._rate = rate\n self._sigma = sigma\n self.image, self.logodds = self.presenting_image(image)\n <mask token>\n <mask token>\n\n def interaction_potentials(self, x, y):\n nbrs = self.neighbors(x, y)\n return sum(nbrs)\n\n def variational_inference(self, x, y):\n E = self._J * self.interaction_potentials(x, y)\n self.image[x, y] = (1 - self._rate) * self.image[x, y\n ] + self._rate * np.tanh(E + 0.5 * self.logodds[x, y])\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass IsingModel:\n\n def __init__(self, image, J, rate, sigma):\n self.width = image.shape[0]\n self.height = image.shape[1]\n self._J = J\n self._rate = rate\n self._sigma = sigma\n self.image, self.logodds = self.presenting_image(image)\n <mask token>\n\n def neighbors(self, x, y):\n nbrs = []\n if x == 0:\n nbrs.append(self.image[self.width - 1, y])\n else:\n nbrs.append(self.image[x - 1, y])\n if x == self.width - 1:\n nbrs.append(self.image[0, y])\n else:\n nbrs.append(self.image[x + 1, y])\n if y == 0:\n nbrs.append(self.image[x, self.height - 1])\n else:\n nbrs.append(self.image[x, y - 1])\n if y == self.height - 1:\n nbrs.append(self.image[x, 0])\n else:\n nbrs.append(self.image[x, y + 1])\n return nbrs\n\n def interaction_potentials(self, x, y):\n nbrs = self.neighbors(x, y)\n return sum(nbrs)\n\n def variational_inference(self, x, y):\n E = self._J * self.interaction_potentials(x, y)\n self.image[x, y] = (1 - self._rate) * self.image[x, y\n ] + self._rate * np.tanh(E + 0.5 * self.logodds[x, y])\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass IsingModel:\n\n def __init__(self, image, J, rate, sigma):\n self.width = image.shape[0]\n self.height = image.shape[1]\n self._J = J\n self._rate = rate\n self._sigma = sigma\n self.image, self.logodds = self.presenting_image(image)\n\n def presenting_image(self, image):\n logodds = multivariate_normal.logpdf(image.flatten(), mean=+1, cov=\n self._sigma ** 2) - multivariate_normal.logpdf(image.flatten(),\n mean=-1, cov=self._sigma ** 2)\n logodds = np.reshape(logodds, image.shape)\n pr_plus1 = 1 / (1 + np.exp(-1 * logodds))\n return 2 * pr_plus1 - 1, logodds\n\n def neighbors(self, x, y):\n nbrs = []\n if x == 0:\n nbrs.append(self.image[self.width - 1, y])\n else:\n nbrs.append(self.image[x - 1, y])\n if x == self.width - 1:\n nbrs.append(self.image[0, y])\n else:\n nbrs.append(self.image[x + 1, y])\n if y == 0:\n nbrs.append(self.image[x, self.height - 1])\n else:\n nbrs.append(self.image[x, y - 1])\n if y == self.height - 1:\n nbrs.append(self.image[x, 0])\n else:\n nbrs.append(self.image[x, y + 1])\n return nbrs\n\n def interaction_potentials(self, x, y):\n nbrs = self.neighbors(x, y)\n return sum(nbrs)\n\n def variational_inference(self, x, y):\n E = self._J * self.interaction_potentials(x, y)\n self.image[x, y] = (1 - self._rate) * self.image[x, y\n ] + self._rate * np.tanh(E + 0.5 * self.logodds[x, y])\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass IsingModel:\n\n def __init__(self, image, J, rate, sigma):\n self.width = image.shape[0]\n self.height = image.shape[1]\n self._J = J\n self._rate = rate\n self._sigma = sigma\n self.image, self.logodds = self.presenting_image(image)\n\n def presenting_image(self, image):\n logodds = multivariate_normal.logpdf(image.flatten(), mean=+1, cov=\n self._sigma ** 2) - multivariate_normal.logpdf(image.flatten(),\n mean=-1, cov=self._sigma ** 2)\n logodds = np.reshape(logodds, image.shape)\n pr_plus1 = 1 / (1 + np.exp(-1 * logodds))\n return 2 * pr_plus1 - 1, logodds\n\n def neighbors(self, x, y):\n nbrs = []\n if x == 0:\n nbrs.append(self.image[self.width - 1, y])\n else:\n nbrs.append(self.image[x - 1, y])\n if x == self.width - 1:\n nbrs.append(self.image[0, y])\n else:\n nbrs.append(self.image[x + 1, y])\n if y == 0:\n nbrs.append(self.image[x, self.height - 1])\n else:\n nbrs.append(self.image[x, y - 1])\n if y == self.height - 1:\n nbrs.append(self.image[x, 0])\n else:\n nbrs.append(self.image[x, y + 1])\n return nbrs\n\n def interaction_potentials(self, x, y):\n nbrs = self.neighbors(x, y)\n return sum(nbrs)\n\n def variational_inference(self, x, y):\n E = self._J * self.interaction_potentials(x, y)\n self.image[x, y] = (1 - self._rate) * self.image[x, y\n ] + self._rate * np.tanh(E + 0.5 * self.logodds[x, y])\n\n\ndef denoising(image, iterations, rate, sigma, J=3):\n ising = IsingModel(image, J=J, rate=rate, sigma=sigma)\n for i in range(iterations):\n for x in range(image.shape[0]):\n for y in range(image.shape[1]):\n ising.variational_inference(x, y)\n return ising.image\n\n\n<mask token>\n", "step-5": "import numpy as np\nfrom scipy.stats import multivariate_normal\nfrom functions.io_data import read_data, write_data\n\nnp.random.seed(0)\n\nclass IsingModel():\n\n def __init__(self, image, J, rate, sigma):\n self.width = image.shape[0]\n self.height = image.shape[1]\n self._J = J\n self._rate = rate\n self._sigma = sigma\n\n self.image, self.logodds = self.presenting_image(image)\n\n def presenting_image(self, image):\n logodds = multivariate_normal.logpdf(image.flatten(), mean=+1, cov=self._sigma ** 2) - multivariate_normal.logpdf(image.flatten(), mean=-1, cov=self._sigma ** 2)\n logodds = np.reshape(logodds, image.shape)\n pr_plus1 = 1 / (1 + np.exp(-1*logodds)) # sigmoid(logodds) # plus 1 -> +1 -> 1 / (1 + exp(logodds)) -> sigmoid(x) = 1 / (1 + exp{x})\n return 2 * pr_plus1 - 1, logodds\n\n def neighbors(self, x, y):\n nbrs = []\n\n if x == 0:\n nbrs.append(self.image[self.width - 1, y])\n else:\n nbrs.append(self.image[x - 1, y])\n\n if x == self.width - 1:\n nbrs.append(self.image[0, y])\n else:\n nbrs.append(self.image[x + 1, y])\n\n if y == 0:\n nbrs.append(self.image[x, self.height - 1])\n else:\n nbrs.append(self.image[x, y - 1])\n\n if y == self.height - 1:\n nbrs.append(self.image[x, 0])\n else:\n nbrs.append(self.image[x, y + 1])\n\n return nbrs\n\n def interaction_potentials(self, x, y):\n nbrs = self.neighbors(x, y)\n return sum(nbrs)\n\n def variational_inference(self, x, y):\n E = self._J * self.interaction_potentials(x, y)\n self.image[x, y] = (1 - self._rate) * self.image[x, y] + self._rate * np.tanh(E + 0.5 * self.logodds[x, y])\n\n\ndef denoising(image, iterations, rate, sigma, J=3):\n ising = IsingModel(image, J=J, rate=rate, sigma=sigma)\n\n for i in range(iterations):\n for x in range(image.shape[0]):\n for y in range(image.shape[1]):\n ising.variational_inference(x, y)\n\n return ising.image\n\nif __name__ == \"__main__\":\n for img in range(1,5):\n print(\"Denoising for image \" + str(img))\n data, image = read_data(\"../a1/\"+str(img)+\"_noise.txt\", True)\n\n print(data.shape)\n print(image.shape)\n\n image[image == 0] = -1\n image[image == 255] = 1\n\n iterations = 15\n J = 3\n sigma = 2\n rate = 0.5\n\n d_img = denoising(image, iterations=iterations, rate=rate, sigma=sigma)\n\n d_img[d_img >= 0] = 255\n d_img[d_img < 0] = 0\n\n print(d_img.shape)\n height = d_img.shape[0]\n width = d_img.shape[1]\n counter = 0\n\n for i in range(0, width):\n for j in range(0, height):\n data[counter][2] = d_img[j][i][0]\n counter = counter + 1\n\n write_data(data, \"../output/vi/\"+str(img)+\"_denoise.txt\")\n read_data(\"../output/vi/\"+str(img)+\"_denoise.txt\", True, save=True, save_name=\"../output/vi/\"+str(img)+\"_denoise.png\")\n print(\"Finished writing data. Please check \"+str(img)+\"_denoise.png \\n\")", "step-ids": [ 4, 5, 6, 7, 10 ] }
[ 4, 5, 6, 7, 10 ]
from unittest import TestCase, main class Solution: def productExceptSelf(self, nums): right, rs = 1, [1]*len(nums) for i in range(1,len(nums)): rs[i] = nums[i-1]*rs[i-1] for i in range(len(nums)-1, -1, -1): rs[i], right = rs[i]*right, right*nums[i] return rs class testsolution(TestCase): def setUp(self): self.solution = Solution() self.inout = [ ([1,2,3,4], [24,12,8,6]), ([4,5,1,8,2], [80,64,320,40,160]) ] def test_productExceptSelf(self): for p1, p2 in self.inout: with self.subTest(input=p1, expected=p2): self.assertEqual(self.solution.productExceptSelf(p1), p2) if __name__ == "__main__": main()
normal
{ "blob_id": "9e34fcec3af746af37cb68fd8617c706cc1066f6", "index": 1743, "step-1": "<mask token>\n\n\nclass testsolution(TestCase):\n\n def setUp(self):\n self.solution = Solution()\n self.inout = [([1, 2, 3, 4], [24, 12, 8, 6]), ([4, 5, 1, 8, 2], [80,\n 64, 320, 40, 160])]\n\n def test_productExceptSelf(self):\n for p1, p2 in self.inout:\n with self.subTest(input=p1, expected=p2):\n self.assertEqual(self.solution.productExceptSelf(p1), p2)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n\n\nclass testsolution(TestCase):\n\n def setUp(self):\n self.solution = Solution()\n self.inout = [([1, 2, 3, 4], [24, 12, 8, 6]), ([4, 5, 1, 8, 2], [80,\n 64, 320, 40, 160])]\n\n def test_productExceptSelf(self):\n for p1, p2 in self.inout:\n with self.subTest(input=p1, expected=p2):\n self.assertEqual(self.solution.productExceptSelf(p1), p2)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Solution:\n\n def productExceptSelf(self, nums):\n right, rs = 1, [1] * len(nums)\n for i in range(1, len(nums)):\n rs[i] = nums[i - 1] * rs[i - 1]\n for i in range(len(nums) - 1, -1, -1):\n rs[i], right = rs[i] * right, right * nums[i]\n return rs\n\n\nclass testsolution(TestCase):\n\n def setUp(self):\n self.solution = Solution()\n self.inout = [([1, 2, 3, 4], [24, 12, 8, 6]), ([4, 5, 1, 8, 2], [80,\n 64, 320, 40, 160])]\n\n def test_productExceptSelf(self):\n for p1, p2 in self.inout:\n with self.subTest(input=p1, expected=p2):\n self.assertEqual(self.solution.productExceptSelf(p1), p2)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass Solution:\n\n def productExceptSelf(self, nums):\n right, rs = 1, [1] * len(nums)\n for i in range(1, len(nums)):\n rs[i] = nums[i - 1] * rs[i - 1]\n for i in range(len(nums) - 1, -1, -1):\n rs[i], right = rs[i] * right, right * nums[i]\n return rs\n\n\nclass testsolution(TestCase):\n\n def setUp(self):\n self.solution = Solution()\n self.inout = [([1, 2, 3, 4], [24, 12, 8, 6]), ([4, 5, 1, 8, 2], [80,\n 64, 320, 40, 160])]\n\n def test_productExceptSelf(self):\n for p1, p2 in self.inout:\n with self.subTest(input=p1, expected=p2):\n self.assertEqual(self.solution.productExceptSelf(p1), p2)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "from unittest import TestCase, main\n\nclass Solution:\n def productExceptSelf(self, nums):\n right, rs = 1, [1]*len(nums)\n for i in range(1,len(nums)): rs[i] = nums[i-1]*rs[i-1]\n for i in range(len(nums)-1, -1, -1): rs[i], right = rs[i]*right, right*nums[i]\n return rs\n\nclass testsolution(TestCase):\n def setUp(self):\n self.solution = Solution()\n self.inout = [\n ([1,2,3,4], [24,12,8,6]),\n ([4,5,1,8,2], [80,64,320,40,160])\n ]\n def test_productExceptSelf(self):\n for p1, p2 in self.inout:\n with self.subTest(input=p1, expected=p2):\n self.assertEqual(self.solution.productExceptSelf(p1), p2)\n\nif __name__ == \"__main__\":\n main()", "step-ids": [ 3, 4, 5, 6, 8 ] }
[ 3, 4, 5, 6, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def divide_img(img_path, img_name, save_path): imgg = img_path + '\\' + img_name print(imgg) img = cv2.imread(imgg) print(img) h = img.shape[0] w = img.shape[1] n = 8 m = 8 print('h={},w={},n={},m={}'.format(h, w, n, m)) dis_h = int(np.floor(h / n)) dis_w = int(np.floor(w / m)) num = 0 for i in range(n): for j in range(m): num += 1 print('i,j={}{}'.format(i, j)) sub = img[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :] cv2.imwrite(save_path + '_{}.tif'.format(num), sub) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def divide_img(img_path, img_name, save_path): imgg = img_path + '\\' + img_name print(imgg) img = cv2.imread(imgg) print(img) h = img.shape[0] w = img.shape[1] n = 8 m = 8 print('h={},w={},n={},m={}'.format(h, w, n, m)) dis_h = int(np.floor(h / n)) dis_w = int(np.floor(w / m)) num = 0 for i in range(n): for j in range(m): num += 1 print('i,j={}{}'.format(i, j)) sub = img[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :] cv2.imwrite(save_path + '_{}.tif'.format(num), sub) if __name__ == '__main__': img_path = 'E:\\个人文件夹\\土地利用编码\\tif' save_path = 'E:\\个人文件夹\\土地利用编码\\tif1' img_list = os.listdir(img_path) for name in img_list: print(name) divide_img(img_path, name, save_path) <|reserved_special_token_1|> import os import matplotlib.pyplot as plt import cv2 import numpy as np def divide_img(img_path, img_name, save_path): imgg = img_path + '\\' + img_name print(imgg) img = cv2.imread(imgg) print(img) h = img.shape[0] w = img.shape[1] n = 8 m = 8 print('h={},w={},n={},m={}'.format(h, w, n, m)) dis_h = int(np.floor(h / n)) dis_w = int(np.floor(w / m)) num = 0 for i in range(n): for j in range(m): num += 1 print('i,j={}{}'.format(i, j)) sub = img[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :] cv2.imwrite(save_path + '_{}.tif'.format(num), sub) if __name__ == '__main__': img_path = 'E:\\个人文件夹\\土地利用编码\\tif' save_path = 'E:\\个人文件夹\\土地利用编码\\tif1' img_list = os.listdir(img_path) for name in img_list: print(name) divide_img(img_path, name, save_path) <|reserved_special_token_1|> import os import matplotlib.pyplot as plt import cv2 import numpy as np def divide_img(img_path, img_name, save_path): imgg = img_path +'\\' +img_name print(imgg) img = cv2.imread(imgg) print(img) # img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) h = img.shape[0] w = img.shape[1] n = 8 m = 8 print('h={},w={},n={},m={}'.format(h, w, n, m)) dis_h = int(np.floor(h / n)) dis_w = int(np.floor(w / m)) num = 0 for i in range(n): for j in range(m): num += 1 print('i,j={}{}'.format(i, j)) sub = img[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :] cv2.imwrite(save_path + '_{}.tif'.format(num), sub) if __name__ == '__main__': img_path = r'E:\个人文件夹\土地利用编码\tif' save_path = r'E:\个人文件夹\土地利用编码\tif1' img_list = os.listdir(img_path) for name in img_list: print(name) divide_img(img_path, name, save_path)
flexible
{ "blob_id": "03f3fcb38877570dea830a56460061bd3ccb8927", "index": 8830, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef divide_img(img_path, img_name, save_path):\n imgg = img_path + '\\\\' + img_name\n print(imgg)\n img = cv2.imread(imgg)\n print(img)\n h = img.shape[0]\n w = img.shape[1]\n n = 8\n m = 8\n print('h={},w={},n={},m={}'.format(h, w, n, m))\n dis_h = int(np.floor(h / n))\n dis_w = int(np.floor(w / m))\n num = 0\n for i in range(n):\n for j in range(m):\n num += 1\n print('i,j={}{}'.format(i, j))\n sub = img[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :]\n cv2.imwrite(save_path + '_{}.tif'.format(num), sub)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef divide_img(img_path, img_name, save_path):\n imgg = img_path + '\\\\' + img_name\n print(imgg)\n img = cv2.imread(imgg)\n print(img)\n h = img.shape[0]\n w = img.shape[1]\n n = 8\n m = 8\n print('h={},w={},n={},m={}'.format(h, w, n, m))\n dis_h = int(np.floor(h / n))\n dis_w = int(np.floor(w / m))\n num = 0\n for i in range(n):\n for j in range(m):\n num += 1\n print('i,j={}{}'.format(i, j))\n sub = img[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :]\n cv2.imwrite(save_path + '_{}.tif'.format(num), sub)\n\n\nif __name__ == '__main__':\n img_path = 'E:\\\\个人文件夹\\\\土地利用编码\\\\tif'\n save_path = 'E:\\\\个人文件夹\\\\土地利用编码\\\\tif1'\n img_list = os.listdir(img_path)\n for name in img_list:\n print(name)\n divide_img(img_path, name, save_path)\n", "step-4": "import os\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\n\n\ndef divide_img(img_path, img_name, save_path):\n imgg = img_path + '\\\\' + img_name\n print(imgg)\n img = cv2.imread(imgg)\n print(img)\n h = img.shape[0]\n w = img.shape[1]\n n = 8\n m = 8\n print('h={},w={},n={},m={}'.format(h, w, n, m))\n dis_h = int(np.floor(h / n))\n dis_w = int(np.floor(w / m))\n num = 0\n for i in range(n):\n for j in range(m):\n num += 1\n print('i,j={}{}'.format(i, j))\n sub = img[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :]\n cv2.imwrite(save_path + '_{}.tif'.format(num), sub)\n\n\nif __name__ == '__main__':\n img_path = 'E:\\\\个人文件夹\\\\土地利用编码\\\\tif'\n save_path = 'E:\\\\个人文件夹\\\\土地利用编码\\\\tif1'\n img_list = os.listdir(img_path)\n for name in img_list:\n print(name)\n divide_img(img_path, name, save_path)\n", "step-5": "import os\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\n\n\ndef divide_img(img_path, img_name, save_path):\n imgg = img_path +'\\\\' +img_name\n print(imgg)\n img = cv2.imread(imgg)\n print(img)\n # img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n h = img.shape[0]\n w = img.shape[1]\n n = 8\n m = 8\n print('h={},w={},n={},m={}'.format(h, w, n, m))\n dis_h = int(np.floor(h / n))\n dis_w = int(np.floor(w / m))\n num = 0\n for i in range(n):\n for j in range(m):\n num += 1\n print('i,j={}{}'.format(i, j))\n sub = img[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :]\n cv2.imwrite(save_path + '_{}.tif'.format(num), sub)\n\n\nif __name__ == '__main__':\n\n img_path = r'E:\\个人文件夹\\土地利用编码\\tif'\n save_path = r'E:\\个人文件夹\\土地利用编码\\tif1'\n img_list = os.listdir(img_path)\n for name in img_list:\n print(name)\n divide_img(img_path, name, save_path)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# import libraries import pandas as pd import matplotlib.pyplot as plt import numpy as np import warnings import pickle from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn.metrics import mean_squared_error import math from sklearn.model_selection import cross_validate # read the csv file dataset = pd.read_csv('heart.csv') #copy the dataset df = dataset.copy() # make X and Y X = df.drop(['target'], axis=1).values Y = df.target.values # correleation matrix corr_mat = df.corr() # split based on training and test dataset x_train, x_test, y_train, y_test = \ train_test_split(X,Y,test_size =0.3,random_state=1234,stratify=Y) # Logistic regression lr = LogisticRegression() lr.fit(x_train, y_train) y_predict = lr.predict(x_test) train_score = lr.score(x_train, y_train) test_score = lr.score(x_test, y_test) # accuracy score acc_score = accuracy_score(y_test, y_predict) rmse = math.sqrt(mean_squared_error(y_test, y_predict)) # Cross validation lr_cross = LogisticRegression() cv_results_lr = cross_validate(lr_cross, X, Y, cv=10, return_train_score=True) test_cv_avg = np.average(cv_results_lr['test_score']) train_cv_avg = np.average(cv_results_lr['train_score']) pickle.dump(lr, open('model.pkl','wb'))
normal
{ "blob_id": "1508697f93114d7f20182a3e9c1df5617904529a", "index": 8725, "step-1": "<mask token>\n", "step-2": "<mask token>\nlr.fit(x_train, y_train)\n<mask token>\npickle.dump(lr, open('model.pkl', 'wb'))\n", "step-3": "<mask token>\ndataset = pd.read_csv('heart.csv')\ndf = dataset.copy()\nX = df.drop(['target'], axis=1).values\nY = df.target.values\ncorr_mat = df.corr()\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.3,\n random_state=1234, stratify=Y)\nlr = LogisticRegression()\nlr.fit(x_train, y_train)\ny_predict = lr.predict(x_test)\ntrain_score = lr.score(x_train, y_train)\ntest_score = lr.score(x_test, y_test)\nacc_score = accuracy_score(y_test, y_predict)\nrmse = math.sqrt(mean_squared_error(y_test, y_predict))\nlr_cross = LogisticRegression()\ncv_results_lr = cross_validate(lr_cross, X, Y, cv=10, return_train_score=True)\ntest_cv_avg = np.average(cv_results_lr['test_score'])\ntrain_cv_avg = np.average(cv_results_lr['train_score'])\npickle.dump(lr, open('model.pkl', 'wb'))\n", "step-4": "import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport warnings\nimport pickle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import mean_squared_error\nimport math\nfrom sklearn.model_selection import cross_validate\ndataset = pd.read_csv('heart.csv')\ndf = dataset.copy()\nX = df.drop(['target'], axis=1).values\nY = df.target.values\ncorr_mat = df.corr()\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.3,\n random_state=1234, stratify=Y)\nlr = LogisticRegression()\nlr.fit(x_train, y_train)\ny_predict = lr.predict(x_test)\ntrain_score = lr.score(x_train, y_train)\ntest_score = lr.score(x_test, y_test)\nacc_score = accuracy_score(y_test, y_predict)\nrmse = math.sqrt(mean_squared_error(y_test, y_predict))\nlr_cross = LogisticRegression()\ncv_results_lr = cross_validate(lr_cross, X, Y, cv=10, return_train_score=True)\ntest_cv_avg = np.average(cv_results_lr['test_score'])\ntrain_cv_avg = np.average(cv_results_lr['train_score'])\npickle.dump(lr, open('model.pkl', 'wb'))\n", "step-5": "# import libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport warnings\nimport pickle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import mean_squared_error\nimport math\nfrom sklearn.model_selection import cross_validate\n\n\n# read the csv file\ndataset = pd.read_csv('heart.csv')\n\n#copy the dataset\ndf = dataset.copy()\n\n# make X and Y\nX = df.drop(['target'], axis=1).values\nY = df.target.values\n\n\n# correleation matrix\ncorr_mat = df.corr()\n\n\n# split based on training and test dataset\n\nx_train, x_test, y_train, y_test = \\\n train_test_split(X,Y,test_size =0.3,random_state=1234,stratify=Y)\n \n\n# Logistic regression\n\nlr = LogisticRegression()\nlr.fit(x_train, y_train)\n\ny_predict = lr.predict(x_test)\n\ntrain_score = lr.score(x_train, y_train)\ntest_score = lr.score(x_test, y_test)\n\n\n# accuracy score\n\nacc_score = accuracy_score(y_test, y_predict)\n\n\nrmse = math.sqrt(mean_squared_error(y_test, y_predict))\n\n\n# Cross validation\n\nlr_cross = LogisticRegression()\n\ncv_results_lr = cross_validate(lr_cross, X, Y, cv=10, return_train_score=True)\n\ntest_cv_avg = np.average(cv_results_lr['test_score'])\ntrain_cv_avg = np.average(cv_results_lr['train_score'])\n\npickle.dump(lr, open('model.pkl','wb'))\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#! /usr/bin/env python import tensorflow as tf import numpy as np import os import time import datetime import data_helpers from text_rnn import TextRNN from tensorflow.contrib import learn # Parameters # ================================================== # Data loading params flags = tf.app.flags FLAGS = flags.FLAGS # Model Hyperparameters tf.flags.DEFINE_integer("embedding_dim", 100, "Dimensionality of character embedding (default: 100)") tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)") # Training parameters tf.flags.DEFINE_integer("batch_size", 128, "Batch Size (default: 64)") tf.flags.DEFINE_integer("num_epochs", 100, "Number of training epochs (default: 200)") tf.flags.DEFINE_integer("evaluate_every", 500, "Evaluate model on dev set after this many steps (default: 100)") tf.flags.DEFINE_integer("checkpoint_every", 500, "Save model after this many steps (default: 100)") tf.flags.DEFINE_integer("num_checkpoints", 3, "Number of checkpoints to store (default: 5)") # Misc Parameters tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") # Data Preparation # ================================================== # Load data print("\nLoading train data...") x_train, y_train = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_train.txt', '../data/toxic_no_train.txt') print("x_train length:{0}, y_train shape:{1}".format(len(x_train), y_train.shape)) print(x_train[0], y_train[0]) print("\nLoading dev data...") x_dev, y_dev = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt') print("x_dev length:{0}, y_dev shape:{1}".format(len(x_dev), y_dev.shape)) print(x_dev[-1], y_dev[-1]) x = x_train+x_dev print("x length:{0}".format(len(x))) # Build vocabulary # max_sent_length, sent = max([(len(i.split(" ")),i) for i in x]) # print("Max sent length = {0}".format(max_sent_length)) # print("Sent with max length = {0}".format(sent)) max_sent_length = 80 vocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length) x = np.array(list(vocab_processor.fit_transform(x))) #x is an iterable, [n_samples, max_sent_length] Word-id matrix. print("Shape of word-id matrix: {0}".format(x.shape)) #Transform x_train and x_dev to word-id matrix x_train = np.array(list(vocab_processor.transform(x_train))) print("Shape of x_train matrix: {0}".format(x_train.shape)) x_dev = np.array(list(vocab_processor.transform(x_dev))) print("Shape of x_dev matrix: {0}".format(x_dev.shape)) # Randomly shuffle data np.random.seed(10) shuffle_indices = np.random.permutation(np.arange(len(y_train))) x_train = x_train[shuffle_indices] y_train = y_train[shuffle_indices] del x vocabsize = len(vocab_processor.vocabulary_) print("Vocabulary Size: {:d}".format(vocabsize)) # Training # ================================================== with tf.Graph().as_default(): session_conf = tf.ConfigProto( allow_soft_placement=FLAGS.allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): rnn = TextRNN( sequence_length=x_train.shape[1], num_classes=y_train.shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim) # Define Training procedure global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.AdamOptimizer(1e-3) grads_and_vars = optimizer.compute_gradients(rnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) # Keep track of gradient values and sparsity (optional) grad_summaries = [] for g, v in grads_and_vars: if g is not None: grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(v.name), g) sparsity_summary = tf.summary.scalar("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) grad_summaries.append(grad_hist_summary) grad_summaries.append(sparsity_summary) grad_summaries_merged = tf.summary.merge(grad_summaries) # Output directory for models and summaries # timestamp = str(int(time.time())) # out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp)) out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs")) print("Writing to {}\n".format(out_dir)) # Summaries for loss and accuracy loss_summary = tf.summary.scalar("loss", rnn.loss) acc_summary = tf.summary.scalar("accuracy", rnn.accuracy) # Train Summaries train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged]) train_summary_dir = os.path.join(out_dir, "summaries", "train") train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph) # Dev summaries dev_summary_op = tf.summary.merge([loss_summary, acc_summary]) dev_summary_dir = os.path.join(out_dir, "summaries", "dev") dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph) # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints) # Write vocabulary vocab_processor.save(os.path.join(out_dir, "vocab")) # Initialize all variables sess.run(tf.global_variables_initializer()) vocabulary = vocab_processor.vocabulary_ initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary) sess.run(rnn.W_embed.assign(initEmbeddings)) for v in tf.trainable_variables(): print(v.name) def train_step(x_batch, y_batch): """ A single training step """ feed_dict = { rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.dropout_keep_prob: FLAGS.dropout_keep_prob } _, step, summaries, loss, accuracy = sess.run( [train_op, global_step, train_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() # print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) train_summary_writer.add_summary(summaries, step) return loss,accuracy def dev_step(x_batch, y_batch, writer=None): """ Evaluates model on a dev set """ feed_dict = { rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.dropout_keep_prob: 1.0 } step, summaries, loss, accuracy = sess.run( [global_step, dev_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) if writer: writer.add_summary(summaries, step) return accuracy # Create batches agnostic of class distributions batches = data_helpers.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) # Create batches aware of imbalance in class distributions # batches = data_helpers.makeBatches(x_train, y_train[:,1].tolist(), FLAGS.batch_size, FLAGS.num_epochs) # Training loop. For each batch... prev_val_acc = 0 for batch in batches: x_batch, y_batch = zip(*batch) train_loss, train_acc = train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) if current_step % FLAGS.evaluate_every == 0: print("\nTrain loss:{0}, Train accuracy:{1}".format(train_loss, train_acc)) print("Evaluation:") val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer) if val_acc > 0.95 and val_acc > prev_val_acc: save_path = saver.save(sess, checkpoint_prefix, global_step=current_step) print("Model checkpoint saved at {0}, accuracy={1}".format(save_path, round(val_acc, 3))) prev_val_acc = val_acc print("")
normal
{ "blob_id": "aa1a7de92b971b6d10d09b2f8ca2c55516e538e4", "index": 9904, "step-1": "<mask token>\n", "step-2": "<mask token>\ntf.flags.DEFINE_integer('embedding_dim', 100,\n 'Dimensionality of character embedding (default: 100)')\ntf.flags.DEFINE_float('dropout_keep_prob', 0.5,\n 'Dropout keep probability (default: 0.5)')\ntf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)')\ntf.flags.DEFINE_integer('num_epochs', 100,\n 'Number of training epochs (default: 200)')\ntf.flags.DEFINE_integer('evaluate_every', 500,\n 'Evaluate model on dev set after this many steps (default: 100)')\ntf.flags.DEFINE_integer('checkpoint_every', 500,\n 'Save model after this many steps (default: 100)')\ntf.flags.DEFINE_integer('num_checkpoints', 3,\n 'Number of checkpoints to store (default: 5)')\ntf.flags.DEFINE_boolean('allow_soft_placement', True,\n 'Allow device soft device placement')\ntf.flags.DEFINE_boolean('log_device_placement', False,\n 'Log placement of ops on devices')\nprint(\"\"\"\nLoading train data...\"\"\")\n<mask token>\nprint('x_train length:{0}, y_train shape:{1}'.format(len(x_train), y_train.\n shape))\nprint(x_train[0], y_train[0])\nprint(\"\"\"\nLoading dev data...\"\"\")\n<mask token>\nprint('x_dev length:{0}, y_dev shape:{1}'.format(len(x_dev), y_dev.shape))\nprint(x_dev[-1], y_dev[-1])\n<mask token>\nprint('x length:{0}'.format(len(x)))\n<mask token>\nprint('Shape of word-id matrix: {0}'.format(x.shape))\n<mask token>\nprint('Shape of x_train matrix: {0}'.format(x_train.shape))\n<mask token>\nprint('Shape of x_dev matrix: {0}'.format(x_dev.shape))\nnp.random.seed(10)\n<mask token>\ndel x\n<mask token>\nprint('Vocabulary Size: {:d}'.format(vocabsize))\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(allow_soft_placement=FLAGS.\n allow_soft_placement, log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n rnn = TextRNN(sequence_length=x_train.shape[1], num_classes=y_train\n .shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim\n )\n global_step = tf.Variable(0, name='global_step', trainable=False)\n optimizer = tf.train.AdamOptimizer(0.001)\n grads_and_vars = optimizer.compute_gradients(rnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=\n global_step)\n grad_summaries = []\n for g, v in grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram('{}/grad/hist'.\n format(v.name), g)\n sparsity_summary = tf.summary.scalar('{}/grad/sparsity'.\n format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n out_dir = os.path.abspath(os.path.join(os.path.curdir, 'runs'))\n print('Writing to {}\\n'.format(out_dir))\n loss_summary = tf.summary.scalar('loss', rnn.loss)\n acc_summary = tf.summary.scalar('accuracy', rnn.accuracy)\n train_summary_op = tf.summary.merge([loss_summary, acc_summary,\n grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, 'summaries', 'train')\n train_summary_writer = tf.summary.FileWriter(train_summary_dir,\n sess.graph)\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, 'summaries', 'dev')\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, 'checkpoints'))\n checkpoint_prefix = os.path.join(checkpoint_dir, 'model')\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.\n num_checkpoints)\n vocab_processor.save(os.path.join(out_dir, 'vocab'))\n sess.run(tf.global_variables_initializer())\n vocabulary = vocab_processor.vocabulary_\n initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary)\n sess.run(rnn.W_embed.assign(initEmbeddings))\n for v in tf.trainable_variables():\n print(v.name)\n\n def train_step(x_batch, y_batch):\n \"\"\"\n A single training step\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: FLAGS.dropout_keep_prob}\n _, step, summaries, loss, accuracy = sess.run([train_op,\n global_step, train_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n train_summary_writer.add_summary(summaries, step)\n return loss, accuracy\n\n def dev_step(x_batch, y_batch, writer=None):\n \"\"\"\n Evaluates model on a dev set\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: 1.0}\n step, summaries, loss, accuracy = sess.run([global_step,\n dev_summary_op, rnn.loss, rnn.accuracy], feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print('{}: step {}, loss {:g}, acc {:g}'.format(time_str, step,\n loss, accuracy))\n if writer:\n writer.add_summary(summaries, step)\n return accuracy\n batches = data_helpers.batch_iter(list(zip(x_train, y_train)),\n FLAGS.batch_size, FLAGS.num_epochs)\n prev_val_acc = 0\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n train_loss, train_acc = train_step(x_batch, y_batch)\n current_step = tf.train.global_step(sess, global_step)\n if current_step % FLAGS.evaluate_every == 0:\n print('\\nTrain loss:{0}, Train accuracy:{1}'.format(\n train_loss, train_acc))\n print('Evaluation:')\n val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer)\n if val_acc > 0.95 and val_acc > prev_val_acc:\n save_path = saver.save(sess, checkpoint_prefix,\n global_step=current_step)\n print('Model checkpoint saved at {0}, accuracy={1}'.\n format(save_path, round(val_acc, 3)))\n prev_val_acc = val_acc\n print('')\n", "step-3": "<mask token>\nflags = tf.app.flags\nFLAGS = flags.FLAGS\ntf.flags.DEFINE_integer('embedding_dim', 100,\n 'Dimensionality of character embedding (default: 100)')\ntf.flags.DEFINE_float('dropout_keep_prob', 0.5,\n 'Dropout keep probability (default: 0.5)')\ntf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)')\ntf.flags.DEFINE_integer('num_epochs', 100,\n 'Number of training epochs (default: 200)')\ntf.flags.DEFINE_integer('evaluate_every', 500,\n 'Evaluate model on dev set after this many steps (default: 100)')\ntf.flags.DEFINE_integer('checkpoint_every', 500,\n 'Save model after this many steps (default: 100)')\ntf.flags.DEFINE_integer('num_checkpoints', 3,\n 'Number of checkpoints to store (default: 5)')\ntf.flags.DEFINE_boolean('allow_soft_placement', True,\n 'Allow device soft device placement')\ntf.flags.DEFINE_boolean('log_device_placement', False,\n 'Log placement of ops on devices')\nprint(\"\"\"\nLoading train data...\"\"\")\nx_train, y_train = data_helpers.load_splitted_data_and_labels(\n '../data/toxic_yes_train.txt', '../data/toxic_no_train.txt')\nprint('x_train length:{0}, y_train shape:{1}'.format(len(x_train), y_train.\n shape))\nprint(x_train[0], y_train[0])\nprint(\"\"\"\nLoading dev data...\"\"\")\nx_dev, y_dev = data_helpers.load_splitted_data_and_labels(\n '../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt')\nprint('x_dev length:{0}, y_dev shape:{1}'.format(len(x_dev), y_dev.shape))\nprint(x_dev[-1], y_dev[-1])\nx = x_train + x_dev\nprint('x length:{0}'.format(len(x)))\nmax_sent_length = 80\nvocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length)\nx = np.array(list(vocab_processor.fit_transform(x)))\nprint('Shape of word-id matrix: {0}'.format(x.shape))\nx_train = np.array(list(vocab_processor.transform(x_train)))\nprint('Shape of x_train matrix: {0}'.format(x_train.shape))\nx_dev = np.array(list(vocab_processor.transform(x_dev)))\nprint('Shape of x_dev matrix: {0}'.format(x_dev.shape))\nnp.random.seed(10)\nshuffle_indices = np.random.permutation(np.arange(len(y_train)))\nx_train = x_train[shuffle_indices]\ny_train = y_train[shuffle_indices]\ndel x\nvocabsize = len(vocab_processor.vocabulary_)\nprint('Vocabulary Size: {:d}'.format(vocabsize))\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(allow_soft_placement=FLAGS.\n allow_soft_placement, log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n rnn = TextRNN(sequence_length=x_train.shape[1], num_classes=y_train\n .shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim\n )\n global_step = tf.Variable(0, name='global_step', trainable=False)\n optimizer = tf.train.AdamOptimizer(0.001)\n grads_and_vars = optimizer.compute_gradients(rnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=\n global_step)\n grad_summaries = []\n for g, v in grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram('{}/grad/hist'.\n format(v.name), g)\n sparsity_summary = tf.summary.scalar('{}/grad/sparsity'.\n format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n out_dir = os.path.abspath(os.path.join(os.path.curdir, 'runs'))\n print('Writing to {}\\n'.format(out_dir))\n loss_summary = tf.summary.scalar('loss', rnn.loss)\n acc_summary = tf.summary.scalar('accuracy', rnn.accuracy)\n train_summary_op = tf.summary.merge([loss_summary, acc_summary,\n grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, 'summaries', 'train')\n train_summary_writer = tf.summary.FileWriter(train_summary_dir,\n sess.graph)\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, 'summaries', 'dev')\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, 'checkpoints'))\n checkpoint_prefix = os.path.join(checkpoint_dir, 'model')\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.\n num_checkpoints)\n vocab_processor.save(os.path.join(out_dir, 'vocab'))\n sess.run(tf.global_variables_initializer())\n vocabulary = vocab_processor.vocabulary_\n initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary)\n sess.run(rnn.W_embed.assign(initEmbeddings))\n for v in tf.trainable_variables():\n print(v.name)\n\n def train_step(x_batch, y_batch):\n \"\"\"\n A single training step\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: FLAGS.dropout_keep_prob}\n _, step, summaries, loss, accuracy = sess.run([train_op,\n global_step, train_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n train_summary_writer.add_summary(summaries, step)\n return loss, accuracy\n\n def dev_step(x_batch, y_batch, writer=None):\n \"\"\"\n Evaluates model on a dev set\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: 1.0}\n step, summaries, loss, accuracy = sess.run([global_step,\n dev_summary_op, rnn.loss, rnn.accuracy], feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print('{}: step {}, loss {:g}, acc {:g}'.format(time_str, step,\n loss, accuracy))\n if writer:\n writer.add_summary(summaries, step)\n return accuracy\n batches = data_helpers.batch_iter(list(zip(x_train, y_train)),\n FLAGS.batch_size, FLAGS.num_epochs)\n prev_val_acc = 0\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n train_loss, train_acc = train_step(x_batch, y_batch)\n current_step = tf.train.global_step(sess, global_step)\n if current_step % FLAGS.evaluate_every == 0:\n print('\\nTrain loss:{0}, Train accuracy:{1}'.format(\n train_loss, train_acc))\n print('Evaluation:')\n val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer)\n if val_acc > 0.95 and val_acc > prev_val_acc:\n save_path = saver.save(sess, checkpoint_prefix,\n global_step=current_step)\n print('Model checkpoint saved at {0}, accuracy={1}'.\n format(save_path, round(val_acc, 3)))\n prev_val_acc = val_acc\n print('')\n", "step-4": "import tensorflow as tf\nimport numpy as np\nimport os\nimport time\nimport datetime\nimport data_helpers\nfrom text_rnn import TextRNN\nfrom tensorflow.contrib import learn\nflags = tf.app.flags\nFLAGS = flags.FLAGS\ntf.flags.DEFINE_integer('embedding_dim', 100,\n 'Dimensionality of character embedding (default: 100)')\ntf.flags.DEFINE_float('dropout_keep_prob', 0.5,\n 'Dropout keep probability (default: 0.5)')\ntf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)')\ntf.flags.DEFINE_integer('num_epochs', 100,\n 'Number of training epochs (default: 200)')\ntf.flags.DEFINE_integer('evaluate_every', 500,\n 'Evaluate model on dev set after this many steps (default: 100)')\ntf.flags.DEFINE_integer('checkpoint_every', 500,\n 'Save model after this many steps (default: 100)')\ntf.flags.DEFINE_integer('num_checkpoints', 3,\n 'Number of checkpoints to store (default: 5)')\ntf.flags.DEFINE_boolean('allow_soft_placement', True,\n 'Allow device soft device placement')\ntf.flags.DEFINE_boolean('log_device_placement', False,\n 'Log placement of ops on devices')\nprint(\"\"\"\nLoading train data...\"\"\")\nx_train, y_train = data_helpers.load_splitted_data_and_labels(\n '../data/toxic_yes_train.txt', '../data/toxic_no_train.txt')\nprint('x_train length:{0}, y_train shape:{1}'.format(len(x_train), y_train.\n shape))\nprint(x_train[0], y_train[0])\nprint(\"\"\"\nLoading dev data...\"\"\")\nx_dev, y_dev = data_helpers.load_splitted_data_and_labels(\n '../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt')\nprint('x_dev length:{0}, y_dev shape:{1}'.format(len(x_dev), y_dev.shape))\nprint(x_dev[-1], y_dev[-1])\nx = x_train + x_dev\nprint('x length:{0}'.format(len(x)))\nmax_sent_length = 80\nvocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length)\nx = np.array(list(vocab_processor.fit_transform(x)))\nprint('Shape of word-id matrix: {0}'.format(x.shape))\nx_train = np.array(list(vocab_processor.transform(x_train)))\nprint('Shape of x_train matrix: {0}'.format(x_train.shape))\nx_dev = np.array(list(vocab_processor.transform(x_dev)))\nprint('Shape of x_dev matrix: {0}'.format(x_dev.shape))\nnp.random.seed(10)\nshuffle_indices = np.random.permutation(np.arange(len(y_train)))\nx_train = x_train[shuffle_indices]\ny_train = y_train[shuffle_indices]\ndel x\nvocabsize = len(vocab_processor.vocabulary_)\nprint('Vocabulary Size: {:d}'.format(vocabsize))\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(allow_soft_placement=FLAGS.\n allow_soft_placement, log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n rnn = TextRNN(sequence_length=x_train.shape[1], num_classes=y_train\n .shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim\n )\n global_step = tf.Variable(0, name='global_step', trainable=False)\n optimizer = tf.train.AdamOptimizer(0.001)\n grads_and_vars = optimizer.compute_gradients(rnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=\n global_step)\n grad_summaries = []\n for g, v in grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram('{}/grad/hist'.\n format(v.name), g)\n sparsity_summary = tf.summary.scalar('{}/grad/sparsity'.\n format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n out_dir = os.path.abspath(os.path.join(os.path.curdir, 'runs'))\n print('Writing to {}\\n'.format(out_dir))\n loss_summary = tf.summary.scalar('loss', rnn.loss)\n acc_summary = tf.summary.scalar('accuracy', rnn.accuracy)\n train_summary_op = tf.summary.merge([loss_summary, acc_summary,\n grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, 'summaries', 'train')\n train_summary_writer = tf.summary.FileWriter(train_summary_dir,\n sess.graph)\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, 'summaries', 'dev')\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, 'checkpoints'))\n checkpoint_prefix = os.path.join(checkpoint_dir, 'model')\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.\n num_checkpoints)\n vocab_processor.save(os.path.join(out_dir, 'vocab'))\n sess.run(tf.global_variables_initializer())\n vocabulary = vocab_processor.vocabulary_\n initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary)\n sess.run(rnn.W_embed.assign(initEmbeddings))\n for v in tf.trainable_variables():\n print(v.name)\n\n def train_step(x_batch, y_batch):\n \"\"\"\n A single training step\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: FLAGS.dropout_keep_prob}\n _, step, summaries, loss, accuracy = sess.run([train_op,\n global_step, train_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n train_summary_writer.add_summary(summaries, step)\n return loss, accuracy\n\n def dev_step(x_batch, y_batch, writer=None):\n \"\"\"\n Evaluates model on a dev set\n \"\"\"\n feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.\n dropout_keep_prob: 1.0}\n step, summaries, loss, accuracy = sess.run([global_step,\n dev_summary_op, rnn.loss, rnn.accuracy], feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print('{}: step {}, loss {:g}, acc {:g}'.format(time_str, step,\n loss, accuracy))\n if writer:\n writer.add_summary(summaries, step)\n return accuracy\n batches = data_helpers.batch_iter(list(zip(x_train, y_train)),\n FLAGS.batch_size, FLAGS.num_epochs)\n prev_val_acc = 0\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n train_loss, train_acc = train_step(x_batch, y_batch)\n current_step = tf.train.global_step(sess, global_step)\n if current_step % FLAGS.evaluate_every == 0:\n print('\\nTrain loss:{0}, Train accuracy:{1}'.format(\n train_loss, train_acc))\n print('Evaluation:')\n val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer)\n if val_acc > 0.95 and val_acc > prev_val_acc:\n save_path = saver.save(sess, checkpoint_prefix,\n global_step=current_step)\n print('Model checkpoint saved at {0}, accuracy={1}'.\n format(save_path, round(val_acc, 3)))\n prev_val_acc = val_acc\n print('')\n", "step-5": "#! /usr/bin/env python\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport time\nimport datetime\nimport data_helpers\nfrom text_rnn import TextRNN\nfrom tensorflow.contrib import learn\n\n\n# Parameters\n# ==================================================\n\n# Data loading params\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n\n# Model Hyperparameters\ntf.flags.DEFINE_integer(\"embedding_dim\", 100, \"Dimensionality of character embedding (default: 100)\")\ntf.flags.DEFINE_float(\"dropout_keep_prob\", 0.5, \"Dropout keep probability (default: 0.5)\")\n\n# Training parameters\ntf.flags.DEFINE_integer(\"batch_size\", 128, \"Batch Size (default: 64)\")\ntf.flags.DEFINE_integer(\"num_epochs\", 100, \"Number of training epochs (default: 200)\")\ntf.flags.DEFINE_integer(\"evaluate_every\", 500, \"Evaluate model on dev set after this many steps (default: 100)\")\ntf.flags.DEFINE_integer(\"checkpoint_every\", 500, \"Save model after this many steps (default: 100)\")\ntf.flags.DEFINE_integer(\"num_checkpoints\", 3, \"Number of checkpoints to store (default: 5)\")\n\n# Misc Parameters\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\n\n# Data Preparation\n# ==================================================\n# Load data\nprint(\"\\nLoading train data...\")\nx_train, y_train = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_train.txt', '../data/toxic_no_train.txt')\nprint(\"x_train length:{0}, y_train shape:{1}\".format(len(x_train), y_train.shape))\nprint(x_train[0], y_train[0])\n\nprint(\"\\nLoading dev data...\")\nx_dev, y_dev = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt')\nprint(\"x_dev length:{0}, y_dev shape:{1}\".format(len(x_dev), y_dev.shape))\nprint(x_dev[-1], y_dev[-1])\n\nx = x_train+x_dev\nprint(\"x length:{0}\".format(len(x)))\n\n# Build vocabulary\n# max_sent_length, sent = max([(len(i.split(\" \")),i) for i in x])\n# print(\"Max sent length = {0}\".format(max_sent_length))\n# print(\"Sent with max length = {0}\".format(sent))\nmax_sent_length = 80\nvocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length)\nx = np.array(list(vocab_processor.fit_transform(x))) #x is an iterable, [n_samples, max_sent_length] Word-id matrix.\nprint(\"Shape of word-id matrix: {0}\".format(x.shape))\n\n#Transform x_train and x_dev to word-id matrix\nx_train = np.array(list(vocab_processor.transform(x_train)))\nprint(\"Shape of x_train matrix: {0}\".format(x_train.shape))\nx_dev = np.array(list(vocab_processor.transform(x_dev)))\nprint(\"Shape of x_dev matrix: {0}\".format(x_dev.shape))\n\n# Randomly shuffle data\nnp.random.seed(10)\nshuffle_indices = np.random.permutation(np.arange(len(y_train)))\nx_train = x_train[shuffle_indices]\ny_train = y_train[shuffle_indices]\n\ndel x\n\nvocabsize = len(vocab_processor.vocabulary_)\nprint(\"Vocabulary Size: {:d}\".format(vocabsize))\n\n# Training\n# ==================================================\n\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n rnn = TextRNN(\n sequence_length=x_train.shape[1],\n num_classes=y_train.shape[1],\n vocab_size=vocabsize,\n embedding_size=FLAGS.embedding_dim)\n\n # Define Training procedure\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n optimizer = tf.train.AdamOptimizer(1e-3)\n grads_and_vars = optimizer.compute_gradients(rnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\n\n # Keep track of gradient values and sparsity (optional)\n grad_summaries = []\n for g, v in grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram(\"{}/grad/hist\".format(v.name), g)\n sparsity_summary = tf.summary.scalar(\"{}/grad/sparsity\".format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n\n # Output directory for models and summaries\n # timestamp = str(int(time.time()))\n # out_dir = os.path.abspath(os.path.join(os.path.curdir, \"runs\", timestamp))\n out_dir = os.path.abspath(os.path.join(os.path.curdir, \"runs\"))\n print(\"Writing to {}\\n\".format(out_dir))\n\n # Summaries for loss and accuracy\n loss_summary = tf.summary.scalar(\"loss\", rnn.loss)\n acc_summary = tf.summary.scalar(\"accuracy\", rnn.accuracy)\n\n # Train Summaries\n train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, \"summaries\", \"train\")\n train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)\n\n # Dev summaries\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, \"summaries\", \"dev\")\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n\n # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints)\n\n # Write vocabulary\n vocab_processor.save(os.path.join(out_dir, \"vocab\"))\n\n # Initialize all variables\n sess.run(tf.global_variables_initializer())\n\n vocabulary = vocab_processor.vocabulary_\n initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary)\n sess.run(rnn.W_embed.assign(initEmbeddings))\n\n for v in tf.trainable_variables():\n print(v.name)\n\n def train_step(x_batch, y_batch):\n \"\"\"\n A single training step\n \"\"\"\n feed_dict = {\n rnn.input_x: x_batch,\n rnn.input_y: y_batch,\n rnn.dropout_keep_prob: FLAGS.dropout_keep_prob\n }\n _, step, summaries, loss, accuracy = sess.run(\n [train_op, global_step, train_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n # print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\n train_summary_writer.add_summary(summaries, step)\n\n return loss,accuracy\n\n def dev_step(x_batch, y_batch, writer=None):\n \"\"\"\n Evaluates model on a dev set\n \"\"\"\n feed_dict = {\n rnn.input_x: x_batch,\n rnn.input_y: y_batch,\n rnn.dropout_keep_prob: 1.0\n }\n step, summaries, loss, accuracy = sess.run(\n [global_step, dev_summary_op, rnn.loss, rnn.accuracy],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\n if writer:\n writer.add_summary(summaries, step)\n\n return accuracy\n\n # Create batches agnostic of class distributions\n batches = data_helpers.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)\n\n # Create batches aware of imbalance in class distributions\n # batches = data_helpers.makeBatches(x_train, y_train[:,1].tolist(), FLAGS.batch_size, FLAGS.num_epochs)\n\n # Training loop. For each batch...\n prev_val_acc = 0\n for batch in batches:\n x_batch, y_batch = zip(*batch)\n train_loss, train_acc = train_step(x_batch, y_batch)\n current_step = tf.train.global_step(sess, global_step)\n if current_step % FLAGS.evaluate_every == 0:\n print(\"\\nTrain loss:{0}, Train accuracy:{1}\".format(train_loss, train_acc))\n print(\"Evaluation:\")\n val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer)\n if val_acc > 0.95 and val_acc > prev_val_acc:\n save_path = saver.save(sess, checkpoint_prefix, global_step=current_step)\n print(\"Model checkpoint saved at {0}, accuracy={1}\".format(save_path, round(val_acc, 3)))\n prev_val_acc = val_acc\n\n print(\"\")", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# 1로 만들기 import sys N = int(sys.stdin.readline()) dp_table = [0 for _ in range(10**6 + 1)] dp_table[2], dp_table[3] = 1, 1 for i in range(4,N+1): two_per = 10**6 three_per = 10**6 if i % 3 ==0: three_per = dp_table[i//3] + 1 if i % 2 ==0: two_per = dp_table[i//2] + 1 minus = dp_table[i-1] + 1 dp_table[i] = min(minus, two_per, three_per) # print(i, dp_table[i]) print(dp_table[N])
normal
{ "blob_id": "34a8fc38ed875e1c564f535348dc0d5d88c76ab1", "index": 7281, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(4, N + 1):\n two_per = 10 ** 6\n three_per = 10 ** 6\n if i % 3 == 0:\n three_per = dp_table[i // 3] + 1\n if i % 2 == 0:\n two_per = dp_table[i // 2] + 1\n minus = dp_table[i - 1] + 1\n dp_table[i] = min(minus, two_per, three_per)\nprint(dp_table[N])\n", "step-3": "<mask token>\nN = int(sys.stdin.readline())\ndp_table = [(0) for _ in range(10 ** 6 + 1)]\ndp_table[2], dp_table[3] = 1, 1\nfor i in range(4, N + 1):\n two_per = 10 ** 6\n three_per = 10 ** 6\n if i % 3 == 0:\n three_per = dp_table[i // 3] + 1\n if i % 2 == 0:\n two_per = dp_table[i // 2] + 1\n minus = dp_table[i - 1] + 1\n dp_table[i] = min(minus, two_per, three_per)\nprint(dp_table[N])\n", "step-4": "import sys\nN = int(sys.stdin.readline())\ndp_table = [(0) for _ in range(10 ** 6 + 1)]\ndp_table[2], dp_table[3] = 1, 1\nfor i in range(4, N + 1):\n two_per = 10 ** 6\n three_per = 10 ** 6\n if i % 3 == 0:\n three_per = dp_table[i // 3] + 1\n if i % 2 == 0:\n two_per = dp_table[i // 2] + 1\n minus = dp_table[i - 1] + 1\n dp_table[i] = min(minus, two_per, three_per)\nprint(dp_table[N])\n", "step-5": "# 1로 만들기\nimport sys\nN = int(sys.stdin.readline())\ndp_table = [0 for _ in range(10**6 + 1)]\ndp_table[2], dp_table[3] = 1, 1\n\nfor i in range(4,N+1):\n two_per = 10**6\n three_per = 10**6\n if i % 3 ==0:\n three_per = dp_table[i//3] + 1\n if i % 2 ==0:\n two_per = dp_table[i//2] + 1\n minus = dp_table[i-1] + 1\n dp_table[i] = min(minus, two_per, three_per)\n # print(i, dp_table[i])\n\nprint(dp_table[N])", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import pyForp import pprint pp = pprint.PrettyPrinter(indent=4) def fib(n): if n < 2: return n return fib(n-2) + fib(n-1) forp = pyForp.pyForp() forp.start() print fib(2) forp.stop() pp.pprint(forp.dump())
normal
{ "blob_id": "80f9c4b7261a894aad2c738d976cfb8efc4d228c", "index": 4784, "step-1": "import pyForp\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\ndef fib(n):\n if n < 2:\n return n\n return fib(n-2) + fib(n-1)\n\nforp = pyForp.pyForp()\nforp.start()\nprint fib(2)\nforp.stop()\npp.pprint(forp.dump())\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]