prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>twist.py<|end_file_name|><|fim▁begin|>__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, <|fim_middle|> def name_method(self, method): self.method = method def __str__(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve() <|fim▁end|>
mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index]
<|file_name|>twist.py<|end_file_name|><|fim▁begin|>__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): <|fim_middle|> def __str__(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve() <|fim▁end|>
self.method = method
<|file_name|>twist.py<|end_file_name|><|fim▁begin|>__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): self.method = method def __str__(self): <|fim_middle|> # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve() <|fim▁end|>
return "A hyperelastic cube twisted by 30 degrees solved by " + self.method
<|file_name|>twist.py<|end_file_name|><|fim▁begin|>__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def <|fim_middle|>(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): self.method = method def __str__(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve() <|fim▁end|>
mesh
<|file_name|>twist.py<|end_file_name|><|fim▁begin|>__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def <|fim_middle|>(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): self.method = method def __str__(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve() <|fim▁end|>
dirichlet_values
<|file_name|>twist.py<|end_file_name|><|fim▁begin|>__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def <|fim_middle|>(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): self.method = method def __str__(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve() <|fim▁end|>
dirichlet_boundaries
<|file_name|>twist.py<|end_file_name|><|fim▁begin|>__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def <|fim_middle|>(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): self.method = method def __str__(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve() <|fim▁end|>
material_model
<|file_name|>twist.py<|end_file_name|><|fim▁begin|>__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def <|fim_middle|>(self, method): self.method = method def __str__(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve() <|fim▁end|>
name_method
<|file_name|>twist.py<|end_file_name|><|fim▁begin|>__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): self.method = method def <|fim_middle|>(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve() <|fim▁end|>
__str__
<|file_name|>73_Set_Matrix_Zeroes.py<|end_file_name|><|fim▁begin|>class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: foundzero = True matrix[i][j] = float("inf") if not foundzero: continue for j in xrange(width): if matrix[i][j] != float("inf"):<|fim▁hole|> for j in xrange(height): if matrix[j][i] == float("inf"): foundtarget = True break if not foundtarget: continue for j in xrange(height): matrix[j][i] = 0<|fim▁end|>
matrix[i][j] = 0 for i in xrange(width): foundtarget = False
<|file_name|>73_Set_Matrix_Zeroes.py<|end_file_name|><|fim▁begin|>class Solution(object): <|fim_middle|> <|fim▁end|>
def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: foundzero = True matrix[i][j] = float("inf") if not foundzero: continue for j in xrange(width): if matrix[i][j] != float("inf"): matrix[i][j] = 0 for i in xrange(width): foundtarget = False for j in xrange(height): if matrix[j][i] == float("inf"): foundtarget = True break if not foundtarget: continue for j in xrange(height): matrix[j][i] = 0
<|file_name|>73_Set_Matrix_Zeroes.py<|end_file_name|><|fim▁begin|>class Solution(object): def setZeroes(self, matrix): <|fim_middle|> <|fim▁end|>
""" :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: foundzero = True matrix[i][j] = float("inf") if not foundzero: continue for j in xrange(width): if matrix[i][j] != float("inf"): matrix[i][j] = 0 for i in xrange(width): foundtarget = False for j in xrange(height): if matrix[j][i] == float("inf"): foundtarget = True break if not foundtarget: continue for j in xrange(height): matrix[j][i] = 0
<|file_name|>73_Set_Matrix_Zeroes.py<|end_file_name|><|fim▁begin|>class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: <|fim_middle|> if not foundzero: continue for j in xrange(width): if matrix[i][j] != float("inf"): matrix[i][j] = 0 for i in xrange(width): foundtarget = False for j in xrange(height): if matrix[j][i] == float("inf"): foundtarget = True break if not foundtarget: continue for j in xrange(height): matrix[j][i] = 0 <|fim▁end|>
foundzero = True matrix[i][j] = float("inf")
<|file_name|>73_Set_Matrix_Zeroes.py<|end_file_name|><|fim▁begin|>class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: foundzero = True matrix[i][j] = float("inf") if not foundzero: <|fim_middle|> for j in xrange(width): if matrix[i][j] != float("inf"): matrix[i][j] = 0 for i in xrange(width): foundtarget = False for j in xrange(height): if matrix[j][i] == float("inf"): foundtarget = True break if not foundtarget: continue for j in xrange(height): matrix[j][i] = 0 <|fim▁end|>
continue
<|file_name|>73_Set_Matrix_Zeroes.py<|end_file_name|><|fim▁begin|>class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: foundzero = True matrix[i][j] = float("inf") if not foundzero: continue for j in xrange(width): if matrix[i][j] != float("inf"): <|fim_middle|> for i in xrange(width): foundtarget = False for j in xrange(height): if matrix[j][i] == float("inf"): foundtarget = True break if not foundtarget: continue for j in xrange(height): matrix[j][i] = 0 <|fim▁end|>
matrix[i][j] = 0
<|file_name|>73_Set_Matrix_Zeroes.py<|end_file_name|><|fim▁begin|>class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: foundzero = True matrix[i][j] = float("inf") if not foundzero: continue for j in xrange(width): if matrix[i][j] != float("inf"): matrix[i][j] = 0 for i in xrange(width): foundtarget = False for j in xrange(height): if matrix[j][i] == float("inf"): <|fim_middle|> if not foundtarget: continue for j in xrange(height): matrix[j][i] = 0 <|fim▁end|>
foundtarget = True break
<|file_name|>73_Set_Matrix_Zeroes.py<|end_file_name|><|fim▁begin|>class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: foundzero = True matrix[i][j] = float("inf") if not foundzero: continue for j in xrange(width): if matrix[i][j] != float("inf"): matrix[i][j] = 0 for i in xrange(width): foundtarget = False for j in xrange(height): if matrix[j][i] == float("inf"): foundtarget = True break if not foundtarget: <|fim_middle|> for j in xrange(height): matrix[j][i] = 0 <|fim▁end|>
continue
<|file_name|>73_Set_Matrix_Zeroes.py<|end_file_name|><|fim▁begin|>class Solution(object): def <|fim_middle|>(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ width,height = len(matrix[0]),len(matrix) for i in xrange(height): foundzero = False for j in xrange(width): if matrix[i][j] == 0: foundzero = True matrix[i][j] = float("inf") if not foundzero: continue for j in xrange(width): if matrix[i][j] != float("inf"): matrix[i][j] = 0 for i in xrange(width): foundtarget = False for j in xrange(height): if matrix[j][i] == float("inf"): foundtarget = True break if not foundtarget: continue for j in xrange(height): matrix[j][i] = 0 <|fim▁end|>
setZeroes
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector<|fim▁hole|> # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res<|fim▁end|>
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): <|fim_middle|> <|fim▁end|>
def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): <|fim_middle|> <|fim▁end|>
logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): <|fim_middle|> elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res <|fim▁end|>
file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): <|fim_middle|> logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res <|fim▁end|>
f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip()
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': <|fim_middle|> # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res <|fim▁end|>
self.set_not_eligible('Windows is currently not managed for DMI informations') return False
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists <|fim_middle|> <|fim▁end|>
res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: <|fim_middle|> for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res <|fim▁end|>
self.set_not_eligible('Cannot read dmi information') return False
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): <|fim_middle|> logger.debug('getdmidecode: completed, returning') return res <|fim▁end|>
buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def launch(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: <|fim_middle|> res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res <|fim▁end|>
logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res
<|file_name|>collector_dmidecode.py<|end_file_name|><|fim▁begin|>import os import re from opsbro.collector import Collector # DMI have lot of useful information that detectors can use to know lot about the platform/hardware class Dmidecode(Collector): def <|fim_middle|>(self): logger = self.logger logger.debug('getDmidecode: start') res = {} # Maybe we are in linux and we can directly read the linux_dmi_path = '/sys/class/dmi/id/' if os.path.exists(linux_dmi_path): file_names = os.listdir(linux_dmi_path) for fname in file_names: p = os.path.join(linux_dmi_path, fname) # There can be a link there, skip them if os.path.isfile(p): f = open(p, 'r') buf = f.read() f.close() res[fname] = buf.strip() logger.debug('getdmidecode: completed, returning') return res elif os.name == 'nt': self.set_not_eligible('Windows is currently not managed for DMI informations') return False # Ok not direct access, try to launch with else: # try dmidecode way, if exists res = self.execute_shell('LANG=C dmidecode -s') if res is False: self.set_not_eligible('Cannot read dmi information') return False for p in res.split('\n'): if re.search('^ ', p): buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip() if 'No such file or directory' in buf: logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.') self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.') return res res[p.replace('-', '_').strip()] = buf logger.debug('getdmidecode: completed, returning') return res <|fim▁end|>
launch
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self):<|fim▁hole|> """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg<|fim▁end|>
return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None):
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): <|fim_middle|> <|fim▁end|>
"""Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbos<|fim_middle|> ef __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
e_name = u'Retorno Correção' app_label = 'Corretor' d
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "<|fim_middle|> f altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
%s: %s" %(self.TIPOS[self.tipo][1],self.msg) de
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ <|fim_middle|> <|fim▁end|>
Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = R <|fim_middle|> elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
etornoCorrecao.TIPOS.correto correcao_msg = "Correto!"
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isins <|fim_middle|> self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
tance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao <|fim_middle|> if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao <|fim_middle|> if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao <|fim_middle|> if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao <|fim_middle|> self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicod<|fim_middle|> return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
e__(self):
<|file_name|>retorno.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_d<|fim_middle|>cesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg <|fim▁end|>
ados(self,su
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR:<|fim▁hole|> if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email})<|fim▁end|>
return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email})
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): <|fim_middle|> <|fim▁end|>
""" lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email})
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: <|fim_middle|> account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): <|fim_middle|> account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': <|fim_middle|> else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
return redirect(reverse('biz:index'))
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: <|fim_middle|> account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
return redirect(next_url)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': <|fim_middle|> return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: <|fim_middle|> if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
post_remember = True
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: <|fim_middle|> if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
log.info('Login failed - email length over') account_check = LOGIN_ERROR
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: <|fim_middle|> if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
log.info('Login failed - password length over') account_check = LOGIN_ERROR
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): <|fim_middle|> else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
user = User.objects.get(email=post_email, is_active=True)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: <|fim_middle|> if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: <|fim_middle|> if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email})
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): <|fim_middle|> else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): <|fim_middle|> if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
account_check = LOGIN_ADMIN
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): <|fim_middle|> if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
account_check = LOGIN_ADMIN
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): <|fim_middle|> if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
account_check = LOGIN_ADMIN
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): <|fim_middle|> if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
account_check = LOGIN_ADMIN
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime <|fim_middle|> else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days <|fim_middle|> else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
request.session.set_expiry(604800)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: <|fim_middle|> if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
request.session.set_expiry(0)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': <|fim_middle|> else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
return redirect(reverse('biz:index'))
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: <|fim_middle|> else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
return redirect(next_url)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: <|fim_middle|> else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
account_check = LOGIN_ERROR_AUTH
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: <|fim_middle|> return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
log.info('Login failed - password mismatch') account_check = LOGIN_ERROR
<|file_name|>views.py<|end_file_name|><|fim▁begin|>""" Views for contract feature """ import logging from edxmako.shortcuts import render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def <|fim_middle|>(request): """ lists content of Login """ next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get("password") post_remember = False if request.method == 'POST': next_url = request.POST.get("next", '') if "remember" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info("Login failed - password for {0} is invalid".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) <|fim▁end|>
index
<|file_name|>chatroomServer.py<|end_file_name|><|fim▁begin|>import socket import threading import time def tcplink(sock, addr): print 'Accept new connection from %s:%s...' % addr sock.send('Welcome!') while True: data = sock.recv(1024) time.sleep(1) if data == 'exit' or not data: break sock.send('Hello, %s!' % data) sock.close() print 'Connection from %s:%s closed.' % addr <|fim▁hole|> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8888)) s.listen(5) print 'Waiting for connection...' while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start()<|fim▁end|>
<|file_name|>chatroomServer.py<|end_file_name|><|fim▁begin|>import socket import threading import time def tcplink(sock, addr): <|fim_middle|> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8888)) s.listen(5) print 'Waiting for connection...' while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start() <|fim▁end|>
print 'Accept new connection from %s:%s...' % addr sock.send('Welcome!') while True: data = sock.recv(1024) time.sleep(1) if data == 'exit' or not data: break sock.send('Hello, %s!' % data) sock.close() print 'Connection from %s:%s closed.' % addr
<|file_name|>chatroomServer.py<|end_file_name|><|fim▁begin|>import socket import threading import time def tcplink(sock, addr): print 'Accept new connection from %s:%s...' % addr sock.send('Welcome!') while True: data = sock.recv(1024) time.sleep(1) if data == 'exit' or not data: <|fim_middle|> sock.send('Hello, %s!' % data) sock.close() print 'Connection from %s:%s closed.' % addr s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8888)) s.listen(5) print 'Waiting for connection...' while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start() <|fim▁end|>
break
<|file_name|>chatroomServer.py<|end_file_name|><|fim▁begin|>import socket import threading import time def <|fim_middle|>(sock, addr): print 'Accept new connection from %s:%s...' % addr sock.send('Welcome!') while True: data = sock.recv(1024) time.sleep(1) if data == 'exit' or not data: break sock.send('Hello, %s!' % data) sock.close() print 'Connection from %s:%s closed.' % addr s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8888)) s.listen(5) print 'Waiting for connection...' while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start() <|fim▁end|>
tcplink
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ############################################## # # This module contains some utilities # ############################################## class argpasser(object): """ ComEst use the arguments that are almost repeatedly. Therefore, it will be useful to create a customized arguemnt passer like this. """ def __init__(self, stamp_size_arcsec = 20.0, mag_dict = {"lo":20.0, "hi":25.0 }, hlr_dict = {"lo":0.35, "hi":0.75 }, fbulge_dict = {"lo":0.5 , "hi":0.9 }, q_dict = {"lo":0.4 , "hi":1.0 }, pos_ang_dict = {"lo":0.0 , "hi":180.0}, ngals_arcmin2 = 15.0, nsimimages = 50, ncpu = 2, ): """ :param stamp_size_arcsec: The size of the stamp of each simulated source by **GalSim**. The stamp is with the size of ``stamp_size_arcsec`` x ``stamp_size_arcsec`` (``stamp_size_arcsec`` in arcsec) where the **GalSim** will simulate one single source on. By default, it is ``stamp_size_arcsec = 15.0``. :param mag_dict: The magnitude range which **GalSim** will simulate sources. It must be in the form of ``{"lo": _value_, "hi": _value_}``, where _value_ is expressed in magnitude. By default, it is ``mag_dict = {"lo":20.0, "hi":25.0 }``. :param hlr_dict: The half light radius configuration of the sources simulated by **GalSim**. It is in the unit of arcsec. It has to be in the form of ``{"lo": _value_, "high": _value_}``. By default, it is ``hlr_dict = {"lo":0.35 , "hi":0.75 }``. :param fbulge_dict: The configuration of the fraction of the bulge component. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and 1 means the galaxy has zero fraction of light from the disk component. By default, it is ``fbulge_dict = {"lo":0.5 , "hi":0.9 }``. :param q_dict: The minor-to-major axis ratio configuration of the sources simulated by **GalSim**. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and ``q = 1`` means spherical. By default, it is ``q_dict = {"lo":0.4 , "hi":1.0 }``. :param pos_ang_dict: The position angle configuration of the sources simulated by **GalSim**. It is in the unit of degree. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,180.0] and it is counter-clockwise with +x is 0 degree. By default, it is ``pos_ang_dict={"lo":0.0 , "hi":180.0 }``. :param ngals_arcmin2: The projected number of the sources simulated by **GalSim** per arcmin square. You dont want to set this number too high because it will cause the problem from blending in the source detection. However, you dont want to lose the statistic power if you set this number too low. By defualt, it is ``ngals_arcmin2 = 15.0``. :param nsimimages: The number of the images you want to simulate. It will be saved in the multi-extension file with the code name ``sims_nameroot``. By default, it is ``nsimimages = 50``. :param ncpu: The number of cpu for parallel running. By default, it is ``ncpu = 2``. Please do not set this number higher than the CPU cores you have. """ self.stamp_size_arcsec = float(stamp_size_arcsec) self.mag_dict = mag_dict self.hlr_dict = hlr_dict self.fbulge_dict = fbulge_dict self.q_dict = q_dict self.pos_ang_dict = pos_ang_dict self.ngals_arcmin2 = float(ngals_arcmin2) self.nsimimages = int(nsimimages)<|fim▁hole|> return # i_am function def i_am(self): """ """ print "#", "stamp_size_arcsec:", self.stamp_size_arcsec print "#", "mag_dict:", self.mag_dict print "#", "hlr_dict:", self.hlr_dict print "#", "fbulge_dict:", self.fbulge_dict print "#", "q_dict:", self.q_dict print "#", "pos_ang_dict:", self.pos_ang_dict print "#", "ngals_arcmin2:", self.ngals_arcmin2 print "#", "nsimimages:", self.nsimimages print "#", "ncpu:", self.ncpu return<|fim▁end|>
self.ncpu = int(ncpu)
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ############################################## # # This module contains some utilities # ############################################## class argpasser(object): <|fim_middle|> <|fim▁end|>
""" ComEst use the arguments that are almost repeatedly. Therefore, it will be useful to create a customized arguemnt passer like this. """ def __init__(self, stamp_size_arcsec = 20.0, mag_dict = {"lo":20.0, "hi":25.0 }, hlr_dict = {"lo":0.35, "hi":0.75 }, fbulge_dict = {"lo":0.5 , "hi":0.9 }, q_dict = {"lo":0.4 , "hi":1.0 }, pos_ang_dict = {"lo":0.0 , "hi":180.0}, ngals_arcmin2 = 15.0, nsimimages = 50, ncpu = 2, ): """ :param stamp_size_arcsec: The size of the stamp of each simulated source by **GalSim**. The stamp is with the size of ``stamp_size_arcsec`` x ``stamp_size_arcsec`` (``stamp_size_arcsec`` in arcsec) where the **GalSim** will simulate one single source on. By default, it is ``stamp_size_arcsec = 15.0``. :param mag_dict: The magnitude range which **GalSim** will simulate sources. It must be in the form of ``{"lo": _value_, "hi": _value_}``, where _value_ is expressed in magnitude. By default, it is ``mag_dict = {"lo":20.0, "hi":25.0 }``. :param hlr_dict: The half light radius configuration of the sources simulated by **GalSim**. It is in the unit of arcsec. It has to be in the form of ``{"lo": _value_, "high": _value_}``. By default, it is ``hlr_dict = {"lo":0.35 , "hi":0.75 }``. :param fbulge_dict: The configuration of the fraction of the bulge component. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and 1 means the galaxy has zero fraction of light from the disk component. By default, it is ``fbulge_dict = {"lo":0.5 , "hi":0.9 }``. :param q_dict: The minor-to-major axis ratio configuration of the sources simulated by **GalSim**. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and ``q = 1`` means spherical. By default, it is ``q_dict = {"lo":0.4 , "hi":1.0 }``. :param pos_ang_dict: The position angle configuration of the sources simulated by **GalSim**. It is in the unit of degree. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,180.0] and it is counter-clockwise with +x is 0 degree. By default, it is ``pos_ang_dict={"lo":0.0 , "hi":180.0 }``. :param ngals_arcmin2: The projected number of the sources simulated by **GalSim** per arcmin square. You dont want to set this number too high because it will cause the problem from blending in the source detection. However, you dont want to lose the statistic power if you set this number too low. By defualt, it is ``ngals_arcmin2 = 15.0``. :param nsimimages: The number of the images you want to simulate. It will be saved in the multi-extension file with the code name ``sims_nameroot``. By default, it is ``nsimimages = 50``. :param ncpu: The number of cpu for parallel running. By default, it is ``ncpu = 2``. Please do not set this number higher than the CPU cores you have. """ self.stamp_size_arcsec = float(stamp_size_arcsec) self.mag_dict = mag_dict self.hlr_dict = hlr_dict self.fbulge_dict = fbulge_dict self.q_dict = q_dict self.pos_ang_dict = pos_ang_dict self.ngals_arcmin2 = float(ngals_arcmin2) self.nsimimages = int(nsimimages) self.ncpu = int(ncpu) return # i_am function def i_am(self): """ """ print "#", "stamp_size_arcsec:", self.stamp_size_arcsec print "#", "mag_dict:", self.mag_dict print "#", "hlr_dict:", self.hlr_dict print "#", "fbulge_dict:", self.fbulge_dict print "#", "q_dict:", self.q_dict print "#", "pos_ang_dict:", self.pos_ang_dict print "#", "ngals_arcmin2:", self.ngals_arcmin2 print "#", "nsimimages:", self.nsimimages print "#", "ncpu:", self.ncpu return
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ############################################## # # This module contains some utilities # ############################################## class argpasser(object): """ ComEst use the arguments that are almost repeatedly. Therefore, it will be useful to create a customized arguemnt passer like this. """ def __init__(self, stamp_size_arcsec = 20.0, mag_dict = {"lo":20.0, "hi":25.0 }, hlr_dict = {"lo":0.35, "hi":0.75 }, fbulge_dict = {"lo":0.5 , "hi":0.9 }, q_dict = {"lo":0.4 , "hi":1.0 }, pos_ang_dict = {"lo":0.0 , "hi":180.0}, ngals_arcmin2 = 15.0, nsimimages = 50, ncpu = 2, ): <|fim_middle|> # i_am function def i_am(self): """ """ print "#", "stamp_size_arcsec:", self.stamp_size_arcsec print "#", "mag_dict:", self.mag_dict print "#", "hlr_dict:", self.hlr_dict print "#", "fbulge_dict:", self.fbulge_dict print "#", "q_dict:", self.q_dict print "#", "pos_ang_dict:", self.pos_ang_dict print "#", "ngals_arcmin2:", self.ngals_arcmin2 print "#", "nsimimages:", self.nsimimages print "#", "ncpu:", self.ncpu return <|fim▁end|>
""" :param stamp_size_arcsec: The size of the stamp of each simulated source by **GalSim**. The stamp is with the size of ``stamp_size_arcsec`` x ``stamp_size_arcsec`` (``stamp_size_arcsec`` in arcsec) where the **GalSim** will simulate one single source on. By default, it is ``stamp_size_arcsec = 15.0``. :param mag_dict: The magnitude range which **GalSim** will simulate sources. It must be in the form of ``{"lo": _value_, "hi": _value_}``, where _value_ is expressed in magnitude. By default, it is ``mag_dict = {"lo":20.0, "hi":25.0 }``. :param hlr_dict: The half light radius configuration of the sources simulated by **GalSim**. It is in the unit of arcsec. It has to be in the form of ``{"lo": _value_, "high": _value_}``. By default, it is ``hlr_dict = {"lo":0.35 , "hi":0.75 }``. :param fbulge_dict: The configuration of the fraction of the bulge component. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and 1 means the galaxy has zero fraction of light from the disk component. By default, it is ``fbulge_dict = {"lo":0.5 , "hi":0.9 }``. :param q_dict: The minor-to-major axis ratio configuration of the sources simulated by **GalSim**. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and ``q = 1`` means spherical. By default, it is ``q_dict = {"lo":0.4 , "hi":1.0 }``. :param pos_ang_dict: The position angle configuration of the sources simulated by **GalSim**. It is in the unit of degree. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,180.0] and it is counter-clockwise with +x is 0 degree. By default, it is ``pos_ang_dict={"lo":0.0 , "hi":180.0 }``. :param ngals_arcmin2: The projected number of the sources simulated by **GalSim** per arcmin square. You dont want to set this number too high because it will cause the problem from blending in the source detection. However, you dont want to lose the statistic power if you set this number too low. By defualt, it is ``ngals_arcmin2 = 15.0``. :param nsimimages: The number of the images you want to simulate. It will be saved in the multi-extension file with the code name ``sims_nameroot``. By default, it is ``nsimimages = 50``. :param ncpu: The number of cpu for parallel running. By default, it is ``ncpu = 2``. Please do not set this number higher than the CPU cores you have. """ self.stamp_size_arcsec = float(stamp_size_arcsec) self.mag_dict = mag_dict self.hlr_dict = hlr_dict self.fbulge_dict = fbulge_dict self.q_dict = q_dict self.pos_ang_dict = pos_ang_dict self.ngals_arcmin2 = float(ngals_arcmin2) self.nsimimages = int(nsimimages) self.ncpu = int(ncpu) return
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ############################################## # # This module contains some utilities # ############################################## class argpasser(object): """ ComEst use the arguments that are almost repeatedly. Therefore, it will be useful to create a customized arguemnt passer like this. """ def __init__(self, stamp_size_arcsec = 20.0, mag_dict = {"lo":20.0, "hi":25.0 }, hlr_dict = {"lo":0.35, "hi":0.75 }, fbulge_dict = {"lo":0.5 , "hi":0.9 }, q_dict = {"lo":0.4 , "hi":1.0 }, pos_ang_dict = {"lo":0.0 , "hi":180.0}, ngals_arcmin2 = 15.0, nsimimages = 50, ncpu = 2, ): """ :param stamp_size_arcsec: The size of the stamp of each simulated source by **GalSim**. The stamp is with the size of ``stamp_size_arcsec`` x ``stamp_size_arcsec`` (``stamp_size_arcsec`` in arcsec) where the **GalSim** will simulate one single source on. By default, it is ``stamp_size_arcsec = 15.0``. :param mag_dict: The magnitude range which **GalSim** will simulate sources. It must be in the form of ``{"lo": _value_, "hi": _value_}``, where _value_ is expressed in magnitude. By default, it is ``mag_dict = {"lo":20.0, "hi":25.0 }``. :param hlr_dict: The half light radius configuration of the sources simulated by **GalSim**. It is in the unit of arcsec. It has to be in the form of ``{"lo": _value_, "high": _value_}``. By default, it is ``hlr_dict = {"lo":0.35 , "hi":0.75 }``. :param fbulge_dict: The configuration of the fraction of the bulge component. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and 1 means the galaxy has zero fraction of light from the disk component. By default, it is ``fbulge_dict = {"lo":0.5 , "hi":0.9 }``. :param q_dict: The minor-to-major axis ratio configuration of the sources simulated by **GalSim**. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and ``q = 1`` means spherical. By default, it is ``q_dict = {"lo":0.4 , "hi":1.0 }``. :param pos_ang_dict: The position angle configuration of the sources simulated by **GalSim**. It is in the unit of degree. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,180.0] and it is counter-clockwise with +x is 0 degree. By default, it is ``pos_ang_dict={"lo":0.0 , "hi":180.0 }``. :param ngals_arcmin2: The projected number of the sources simulated by **GalSim** per arcmin square. You dont want to set this number too high because it will cause the problem from blending in the source detection. However, you dont want to lose the statistic power if you set this number too low. By defualt, it is ``ngals_arcmin2 = 15.0``. :param nsimimages: The number of the images you want to simulate. It will be saved in the multi-extension file with the code name ``sims_nameroot``. By default, it is ``nsimimages = 50``. :param ncpu: The number of cpu for parallel running. By default, it is ``ncpu = 2``. Please do not set this number higher than the CPU cores you have. """ self.stamp_size_arcsec = float(stamp_size_arcsec) self.mag_dict = mag_dict self.hlr_dict = hlr_dict self.fbulge_dict = fbulge_dict self.q_dict = q_dict self.pos_ang_dict = pos_ang_dict self.ngals_arcmin2 = float(ngals_arcmin2) self.nsimimages = int(nsimimages) self.ncpu = int(ncpu) return # i_am function def i_am(self): <|fim_middle|> <|fim▁end|>
""" """ print "#", "stamp_size_arcsec:", self.stamp_size_arcsec print "#", "mag_dict:", self.mag_dict print "#", "hlr_dict:", self.hlr_dict print "#", "fbulge_dict:", self.fbulge_dict print "#", "q_dict:", self.q_dict print "#", "pos_ang_dict:", self.pos_ang_dict print "#", "ngals_arcmin2:", self.ngals_arcmin2 print "#", "nsimimages:", self.nsimimages print "#", "ncpu:", self.ncpu return
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ############################################## # # This module contains some utilities # ############################################## class argpasser(object): """ ComEst use the arguments that are almost repeatedly. Therefore, it will be useful to create a customized arguemnt passer like this. """ def <|fim_middle|>(self, stamp_size_arcsec = 20.0, mag_dict = {"lo":20.0, "hi":25.0 }, hlr_dict = {"lo":0.35, "hi":0.75 }, fbulge_dict = {"lo":0.5 , "hi":0.9 }, q_dict = {"lo":0.4 , "hi":1.0 }, pos_ang_dict = {"lo":0.0 , "hi":180.0}, ngals_arcmin2 = 15.0, nsimimages = 50, ncpu = 2, ): """ :param stamp_size_arcsec: The size of the stamp of each simulated source by **GalSim**. The stamp is with the size of ``stamp_size_arcsec`` x ``stamp_size_arcsec`` (``stamp_size_arcsec`` in arcsec) where the **GalSim** will simulate one single source on. By default, it is ``stamp_size_arcsec = 15.0``. :param mag_dict: The magnitude range which **GalSim** will simulate sources. It must be in the form of ``{"lo": _value_, "hi": _value_}``, where _value_ is expressed in magnitude. By default, it is ``mag_dict = {"lo":20.0, "hi":25.0 }``. :param hlr_dict: The half light radius configuration of the sources simulated by **GalSim**. It is in the unit of arcsec. It has to be in the form of ``{"lo": _value_, "high": _value_}``. By default, it is ``hlr_dict = {"lo":0.35 , "hi":0.75 }``. :param fbulge_dict: The configuration of the fraction of the bulge component. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and 1 means the galaxy has zero fraction of light from the disk component. By default, it is ``fbulge_dict = {"lo":0.5 , "hi":0.9 }``. :param q_dict: The minor-to-major axis ratio configuration of the sources simulated by **GalSim**. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and ``q = 1`` means spherical. By default, it is ``q_dict = {"lo":0.4 , "hi":1.0 }``. :param pos_ang_dict: The position angle configuration of the sources simulated by **GalSim**. It is in the unit of degree. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,180.0] and it is counter-clockwise with +x is 0 degree. By default, it is ``pos_ang_dict={"lo":0.0 , "hi":180.0 }``. :param ngals_arcmin2: The projected number of the sources simulated by **GalSim** per arcmin square. You dont want to set this number too high because it will cause the problem from blending in the source detection. However, you dont want to lose the statistic power if you set this number too low. By defualt, it is ``ngals_arcmin2 = 15.0``. :param nsimimages: The number of the images you want to simulate. It will be saved in the multi-extension file with the code name ``sims_nameroot``. By default, it is ``nsimimages = 50``. :param ncpu: The number of cpu for parallel running. By default, it is ``ncpu = 2``. Please do not set this number higher than the CPU cores you have. """ self.stamp_size_arcsec = float(stamp_size_arcsec) self.mag_dict = mag_dict self.hlr_dict = hlr_dict self.fbulge_dict = fbulge_dict self.q_dict = q_dict self.pos_ang_dict = pos_ang_dict self.ngals_arcmin2 = float(ngals_arcmin2) self.nsimimages = int(nsimimages) self.ncpu = int(ncpu) return # i_am function def i_am(self): """ """ print "#", "stamp_size_arcsec:", self.stamp_size_arcsec print "#", "mag_dict:", self.mag_dict print "#", "hlr_dict:", self.hlr_dict print "#", "fbulge_dict:", self.fbulge_dict print "#", "q_dict:", self.q_dict print "#", "pos_ang_dict:", self.pos_ang_dict print "#", "ngals_arcmin2:", self.ngals_arcmin2 print "#", "nsimimages:", self.nsimimages print "#", "ncpu:", self.ncpu return <|fim▁end|>
__init__
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ############################################## # # This module contains some utilities # ############################################## class argpasser(object): """ ComEst use the arguments that are almost repeatedly. Therefore, it will be useful to create a customized arguemnt passer like this. """ def __init__(self, stamp_size_arcsec = 20.0, mag_dict = {"lo":20.0, "hi":25.0 }, hlr_dict = {"lo":0.35, "hi":0.75 }, fbulge_dict = {"lo":0.5 , "hi":0.9 }, q_dict = {"lo":0.4 , "hi":1.0 }, pos_ang_dict = {"lo":0.0 , "hi":180.0}, ngals_arcmin2 = 15.0, nsimimages = 50, ncpu = 2, ): """ :param stamp_size_arcsec: The size of the stamp of each simulated source by **GalSim**. The stamp is with the size of ``stamp_size_arcsec`` x ``stamp_size_arcsec`` (``stamp_size_arcsec`` in arcsec) where the **GalSim** will simulate one single source on. By default, it is ``stamp_size_arcsec = 15.0``. :param mag_dict: The magnitude range which **GalSim** will simulate sources. It must be in the form of ``{"lo": _value_, "hi": _value_}``, where _value_ is expressed in magnitude. By default, it is ``mag_dict = {"lo":20.0, "hi":25.0 }``. :param hlr_dict: The half light radius configuration of the sources simulated by **GalSim**. It is in the unit of arcsec. It has to be in the form of ``{"lo": _value_, "high": _value_}``. By default, it is ``hlr_dict = {"lo":0.35 , "hi":0.75 }``. :param fbulge_dict: The configuration of the fraction of the bulge component. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and 1 means the galaxy has zero fraction of light from the disk component. By default, it is ``fbulge_dict = {"lo":0.5 , "hi":0.9 }``. :param q_dict: The minor-to-major axis ratio configuration of the sources simulated by **GalSim**. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,1] and ``q = 1`` means spherical. By default, it is ``q_dict = {"lo":0.4 , "hi":1.0 }``. :param pos_ang_dict: The position angle configuration of the sources simulated by **GalSim**. It is in the unit of degree. It must be in the form of ``{"lo": _value_, "high": _value_}``. Note that the _value_ has to be within [0,180.0] and it is counter-clockwise with +x is 0 degree. By default, it is ``pos_ang_dict={"lo":0.0 , "hi":180.0 }``. :param ngals_arcmin2: The projected number of the sources simulated by **GalSim** per arcmin square. You dont want to set this number too high because it will cause the problem from blending in the source detection. However, you dont want to lose the statistic power if you set this number too low. By defualt, it is ``ngals_arcmin2 = 15.0``. :param nsimimages: The number of the images you want to simulate. It will be saved in the multi-extension file with the code name ``sims_nameroot``. By default, it is ``nsimimages = 50``. :param ncpu: The number of cpu for parallel running. By default, it is ``ncpu = 2``. Please do not set this number higher than the CPU cores you have. """ self.stamp_size_arcsec = float(stamp_size_arcsec) self.mag_dict = mag_dict self.hlr_dict = hlr_dict self.fbulge_dict = fbulge_dict self.q_dict = q_dict self.pos_ang_dict = pos_ang_dict self.ngals_arcmin2 = float(ngals_arcmin2) self.nsimimages = int(nsimimages) self.ncpu = int(ncpu) return # i_am function def <|fim_middle|>(self): """ """ print "#", "stamp_size_arcsec:", self.stamp_size_arcsec print "#", "mag_dict:", self.mag_dict print "#", "hlr_dict:", self.hlr_dict print "#", "fbulge_dict:", self.fbulge_dict print "#", "q_dict:", self.q_dict print "#", "pos_ang_dict:", self.pos_ang_dict print "#", "ngals_arcmin2:", self.ngals_arcmin2 print "#", "nsimimages:", self.nsimimages print "#", "ncpu:", self.ncpu return <|fim▁end|>
i_am
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) <|fim▁hole|> numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()<|fim▁end|>
# Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U)
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V <|fim_middle|> def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()<|fim▁end|>
U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R)
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): <|fim_middle|> def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()<|fim▁end|>
if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): <|fim_middle|> ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()<|fim▁end|>
for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown))
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): <|fim_middle|> (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()<|fim▁end|>
return numpy.copy(true_R)
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def <|fim_middle|>(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()<|fim▁end|>
generate_dataset
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def <|fim_middle|>(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()<|fim▁end|>
add_noise
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def <|fim_middle|>(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()<|fim▁end|>
try_generate_M
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None,<|fim▁hole|> }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"])<|fim▁end|>
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): <|fim_middle|> class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } }
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase <|fim_middle|> <|fim▁end|>
FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"])
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): <|fim_middle|> @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"])
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): <|fim_middle|> @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code])
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): <|fim_middle|> #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code])
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): <|fim_middle|> @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code)
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 <|fim_middle|> <|fim▁end|>
dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"])
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def <|fim_middle|>(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
_get_datasets_settings
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def <|fim_middle|>(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
_load_files
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def <|fim_middle|>(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
test_load_datasets_first
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def <|fim_middle|>(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
test_load_datasets_update
<|file_name|>test_bea.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import io import os from dlstats.fetchers.bea import BEA as Fetcher import httpretty from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR from dlstats.tests.fetchers.base import BaseFetcherTestCase import unittest from unittest import mock RESOURCES_DIR = os.path.abspath(os.path.join(BASE_RESOURCES_DIR, "bea")) DATA_BEA_10101_An = { "filepath": os.path.abspath(os.path.join(RESOURCES_DIR, "nipa-section1.xls.zip")), "DSD": { "provider": "BEA", "filepath": None, "dataset_code": "nipa-section1-10101-a", "dsd_id": "nipa-section1-10101-a", "is_completed": True, "categories_key": "nipa-section1", "categories_parents": ["national", "nipa"], "categories_root": ["national", "nipa", "nipa-fa2004", "nipa-underlying"], "concept_keys": ['concept', 'frequency'], "codelist_keys": ['concept', 'frequency'], "codelist_count": { "concept": 25, "frequency": 1 }, "dimension_keys": ['concept', 'frequency'], "dimension_count": { "concept": 25, "frequency": 1 }, "attribute_keys": [], "attribute_count": None, }, "series_accept": 25, "series_reject_frequency": 0, "series_reject_empty": 0, "series_all_values": 1175, "series_key_first": "A191RL1-A", "series_key_last": "A191RP1-A", "series_sample": { 'provider_name': 'BEA', 'dataset_code': 'nipa-section1-10101-a', 'key': 'A191RL1-A', 'name': 'Gross domestic product - Annually', 'frequency': 'A', 'last_update': None, 'first_value': { 'value': '3.1', 'period': '1969', 'attributes': None, }, 'last_value': { 'value': '2.4', 'period': '2015', 'attributes': None, }, 'dimensions': { 'concept': 'a191rl1', "frequency": 'a' }, 'attributes': None, } } def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } } class FetcherTestCase(BaseFetcherTestCase): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase FETCHER_KLASS = Fetcher DATASETS = { 'nipa-section1-10101-a': DATA_BEA_10101_An } DATASET_FIRST = "nipa-fa2004-section1-101-a" DATASET_LAST = "nipa-underlying-section9-90500U-a" DEBUG_MODE = False def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code]) @httpretty.activate @unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test") def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code]) #@httpretty.activate @unittest.skipIf(True, "TODO") def <|fim_middle|>(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code) @httpretty.activate @mock.patch("dlstats.fetchers.bea.BEA._get_datasets_settings", _get_datasets_settings) def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101 dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertProvider() dataset = self.assertDataset(dataset_code) names = { 'a191rl1': 'Gross domestic product', 'dpcerl1': 'Personal consumption expenditures', 'dgdsrl1': 'Personal consumption expenditures - Goods', 'ddurrl1': 'Personal consumption expenditures - Goods - Durable goods', 'dndgrl1': 'Personal consumption expenditures - Goods - Nondurable goods', 'dserrl1': 'Personal consumption expenditures - Services', 'a006rl1': 'Gross private domestic investment', 'a007rl1': 'Gross private domestic investment - Fixed investment', 'a008rl1': 'Gross private domestic investment - Fixed investment - Nonresidential', 'y033rl1': 'Gross private domestic investment - Fixed investment - Nonresidential - Equipment', 'a011rl1': 'Gross private domestic investment - Fixed investment - Residential', 'a020rl1': 'Net exports of goods and services - Exports', 'a191rp1': 'Addendum: - Gross domestic product, current dollars' } for k, v in names.items(): self.assertTrue(k in dataset["codelists"]["concept"]) self.assertEquals(dataset["codelists"]["concept"][k], v) series_list = self.assertSeries(dataset_code) series_keys = {s["key"].lower(): s for s in series_list} for k, v in names.items(): search_k = "%s-a" % k search_name = "%s - Annually" % v self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k) self.assertEquals(series_keys[search_k]["name"], search_name) for series in series_list: self.assertEquals(series["last_update_ds"], dataset["last_update"]) <|fim▁end|>
test_build_data_tree