예제 #1
0
    def __init__(self):
        """Конструктор класса"""

        self.cities = Cities()
        logging.basicConfig(
            format='%(asctime)s | %(levelname)-8s | %(message)s',
            level=logging.INFO)
예제 #2
0
def main():
    n = 4
    hyperparameter = 0.1
    c = Cities(n)
    h = Hopfield(c.c, hyperparameter)
    #h.go_to_minimum()
    #h.plot_energy()
    h.show_shortest_route()
예제 #3
0
파일: bot.py 프로젝트: mrbinwin/vk-bot
 def __init__(self, **kwargs):
     self.admin_vk_id = kwargs['admin_vk_id']
     self.antigate_key = kwargs['antigate_key']
     self.rucaptcha_key = kwargs['rucaptcha_key']
     self.vk_username = kwargs['username']
     self.vk_password = kwargs['password']
     self.vk_my_group = kwargs['vk_my_group']
     self._cities = Cities()
     if 'logger' in kwargs:
         self._logger = kwargs['logger']
예제 #4
0
 def get(self):
     user = users.get_current_user()
     p_obj = permissions.Permissions()
     userTypes = p_obj.getPermissions(user.email())
     if userTypes[1] == 1:
         self.redirect('/owner-home')
         return
     template = jinja_environment.get_template('register_owner.html')
     cities_obj = Cities()
     my_cities = cities_obj.getCitiesFromDb()
     parameters_for_template = {'user': user, 'cities': my_cities}
     self.response.write(template.render(parameters_for_template))
예제 #5
0
def main():
    uf_name = input("Digite o estado: ")
    population = input("Digite o limite de população: ")

    cities = Cities(uf_name, population)
    points = cities.list

    if (len(points) > 1):
        d, closest_points = get_closest_points(points)

        print("\nAs cidades mais próximas são: " + closest_points[0].name +
              " e " + closest_points[1].name)

        draw(points, closest_points)
    else:
        print("\nNão há cidades que se encaixam nas especificações!")
예제 #6
0
 def get(self):
     user = users.get_current_user()
     p_obj = permissions.Permissions()
     userTypes = p_obj.getPermissions(user.email())
     if userTypes[0] != 1:  #UPDATE TO CHECK IN DB
         parameters_for_template = {
             'message':
             'You don\'t have permissions to this page. Please try again later'
         }
         template = jinja_environment.get_template('error_page.html')
         self.response.write(template.render(parameters_for_template))
     else:
         cities_obj = Cities()
         my_owner_finder = owner_finder.OwnerFinder()
         my_cities = cities_obj.getCitiesFromDb()
         owners = my_owner_finder.getAllOwners('', 0, 0, user.email(), True)
         parameters_for_template = {
             'user': user,
             'cities': my_cities,
             'owners': owners
         }
         template = jinja_environment.get_template('filter_owners.html')
         self.response.write(template.render(parameters_for_template))
예제 #7
0
    def get(self):
        user = users.get_current_user()
        p_obj = permissions.Permissions()
        userTypes = p_obj.getPermissions(user.email())
        if userTypes[0] != 1:
            parameters_for_template = {
                'message':
                'You don\'t have permissions to this page. Please try again later'
            }
            template = jinja_environment.get_template('error_page.html')
            self.response.write(template.render(parameters_for_template))
        else:
            city = self.request.get('city')
            minAge = self.request.get('minAge')
            maxAge = self.request.get('maxAge')
            viewAll = True if self.request.get('all') == 'on' else False
            logging.error(viewAll)
            my_owner_finder = owner_finder.OwnerFinder()
            if viewAll:
                owners = my_owner_finder.getAllOwners('', 0, 0, user.email(),
                                                      viewAll)
            else:
                owners = my_owner_finder.getAllOwners(city, minAge, maxAge,
                                                      user.email(), viewAll)

        logging.error(owners)
        cities_obj = Cities()
        my_cities = cities_obj.getCitiesFromDb()
        my_cities.insert(0, 'All Cities')
        parameters_for_template = {
            'cities': my_cities,
            'user': user,
            'owners': owners
        }
        template = jinja_environment.get_template('filter_owners.html')
        self.response.write(template.render(parameters_for_template))
예제 #8
0
def index():
    from regnews import Regnews
    from mailboxing import Mailboxing
    from cities import Cities
    from province import Province
    from queuemail import Queuemail
    Province(db)
    Cities(db)
    Regnews(db)
    Mailboxing(db)
    Queuemail(db)

    wpoblacion = SQLFORM.widgets.autocomplete(request,
                                              db.cities.poblacion,
                                              limitby=(0, 10),
                                              min_length=2)
    wprovincia = SQLFORM.widgets.autocomplete(request,
                                              db.province.provincia,
                                              limitby=(0, 10),
                                              min_length=2)

    name = Field('name',
                 'string',
                 label="Nombre",
                 length=50,
                 requires=IS_NOT_EMPTY(
                     error_message="Debe identificarse con un nombre"),
                 widget=lambda field, value: SQLFORM.widgets.string.widget(
                     field, value, _placeholder='Nombre y apellidos'))
    email = Field('email',
                  'string',
                  length=128,
                  requires=[
                      IS_NOT_EMPTY(error_message="Un email es requerido"),
                      IS_EMAIL(error_message="email incorrecto")
                  ],
                  widget=lambda field, value: SQLFORM.widgets.string.widget(
                      field, value, _placeholder='ejemplo: [email protected]'))
    phone = Field('phone', 'string', length=18, notnull=False)
    poblacion = Field('city',
                      'string',
                      length=40,
                      notnull=False,
                      widget=wpoblacion)
    provincia = Field('province',
                      'string',
                      length=40,
                      notnull=False,
                      widget=wprovincia)
    rnews = Field('rnews', 'boolean', default=True)
    message = Field(
        'message',
        'text',
        notnull=True,
        requires=IS_NOT_EMPTY(
            error_message=
            "Por favor, díganos por qué quiere contactar con nosotros."))
    form = SQLFORM.factory(name,
                           rnews,
                           email,
                           phone,
                           poblacion,
                           provincia,
                           message,
                           submit_button='contactar',
                           formstyle='bootstrap')

    queuedata = []
    if form.validate(keepvalues=False):
        data = form.vars
        try:

            reg = db(db.regnews.email == data.email).select()
            if len(reg) == 0:
                id = db.regnews.insert(email=data.email,
                                       name=data.name,
                                       news=data.rnews,
                                       phone=data.phone,
                                       city=data.city,
                                       province=data.province)
                db.mailbox.insert(regnews=id, message=data.message)
            else:
                db.mailbox.insert(regnews=reg[0].id, message=data.message)
            db.commit()
        except:
            db.rollback()
            response.flash = 'Su petición de contacto no pudo registrarse. Inténtelo de nuevo.'
        #primero encolamos el mail al usuario que ha hecho la petición de contacto
        queuedata.append({
            'to':
            '%s' % data.email,
            'subject':
            'Confirmación de petición de contacto',
            'message':
            'Estimado %s,\n hemos recibido una petición de contacto por parte suya desde el formulario de contacto de Despacho Cifrado.\n\n Muchas gracias por su interés. Le responderemos en breve.\n\n Reciba un cordial saludo.\n--\nDespacho Cifrado'
            % data.name
        })
        #y ahora notificación a cada uno de los administradores
        mails = db(db.auth_membership.group_id == 1).select(
            db.auth_membership.ALL,
            db.auth_user.ALL,
            left=db.auth_user.on(
                db.auth_membership.user_id == db.auth_user.id))
        for m in mails:
            queuedata.append({
                'to':
                '%s' % m.auth_user.email,
                'subject':
                'Tienes una solicitud de contacto',
                'message':
                '%s con mail: %s y teléfono: %s  te ha enviado el siguiente mensaje: \n %s '
                % (data.name, data.email, data.phone, data.message)
            })
        try:
            logger.debug(queuedata)
            queue.queuemessage(queuedata)
        except Exception, ex:
            logger.debug("error al almacenar la cola de mensajes %s" % ex)
            pass
        session.flash = 'Su petición ha sido registrada'
        redirect(URL(request.application, 'default', 'index'))
예제 #9
0
from cities import Cities
from population import Population
from distance import DistanceResolver
import matplotlib.pyplot as plt
import matplotlib

cities_location = Cities()
population = Population(cities_location)

for _ in range(10000):
    population.next_generation()    

# resultado final
final_population = population.get_population()
best_solution = final_population[0]
best_chromosome = best_solution[0]
best_distance = best_solution[1]

print("Tamanho da população: {}".format(len(final_population)))
print("Taxa de mutação: 5%")
print("Número de cidades: {}".format(cities_location.get_cities_count()))
print("Melhor solução: {}".format(best_distance))

plt.plot(cities_location.get_cities()[0], cities_location.get_cities()[1], 'ro')

best_chromosome_cities = best_chromosome.get_cities()
best_path_x = []
best_path_y = []
for i in range(len(best_chromosome_cities)):
    city = cities_location.get_city(best_chromosome_cities[i])
    best_path_x.append(city.x)
예제 #10
0
def fiscal():
    from invoices import Fiscal
    from cities import Cities
    from province import Province
    Fiscal(db), Province(db), Cities(db)

    fiscal = db(db.fiscals.user == auth.user_id).select().first()
    logger.debug(fiscal)
    wpoblacion = SQLFORM.widgets.autocomplete(request,
                                              db.cities.poblacion,
                                              limitby=(0, 10),
                                              min_length=2)
    wprovincia = SQLFORM.widgets.autocomplete(request,
                                              db.province.provincia,
                                              limitby=(0, 10),
                                              min_length=2)
    if request.vars.wizard:
        wizard = request.vars.wizard
    else:
        wizard = False
    if fiscal:
        tax_identification = Field(
            'tax_identification',
            'string',
            label=XML(
                "<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"
            ),
            default=fiscal.tax_identification,
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        fiscalname = Field('fiscalname',
                           'string',
                           label=XML("<strong>Nombre empresa</strong>"),
                           default=fiscal.fiscalname,
                           length=128,
                           notnull=False)
        address = Field(
            'address',
            'string',
            label=XML("<strong>Dirección</strong>"),
            default=fiscal.address,
            length=250,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        city = Field(
            'city',
            'string',
            label=XML("<strong>Ciudad/Población</strong>"),
            default=fiscal.city,
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wpoblacion)
        province = Field('province',
                         'string',
                         label=XML("<strong>Provincia</strong>"),
                         default=fiscal.province,
                         notnull=False,
                         widget=wprovincia)
        country = Field(
            'country',
            'string',
            label=XML("<strong>Pais</strong>"),
            length=45,
            default=fiscal.country,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        postalcode = Field(
            'postal_code',
            'string',
            label=XML("<strong>Código postal</strong>"),
            default=fiscal.postal_code,
            length=10,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        phone = Field('phone',
                      'string',
                      label=XML("<strong>Teléfono de contacto</strong>"),
                      length=20,
                      default=fiscal.phone,
                      notnull=False)
    else:
        tax_identification = Field(
            'tax_identification',
            'string',
            label=XML(
                "<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"
            ),
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        fiscalname = Field('fiscalname',
                           'string',
                           label=XML("<strong>Nombre empresa</strong>"),
                           length=128,
                           notnull=False)
        address = Field(
            'address',
            'string',
            label=XML("<strong>Dirección</strong>"),
            length=196,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        city = Field(
            'city',
            'string',
            label=XML("<strong>Ciudad/Población</strong>"),
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wpoblacion)
        province = Field('province',
                         'string',
                         label=XML("<strong>Provincia</strong>"),
                         length=45,
                         notnull=False,
                         widget=wprovincia)
        country = Field(
            'country',
            'string',
            label=XML("<strong>Pais</strong>"),
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        postalcode = Field(
            'postal_code',
            'string',
            label=XML("<strong>Código postal</strong>"),
            length=10,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        phone = Field('phone',
                      'string',
                      label=XML("<strong>Teléfono de contacto</strong>"),
                      length=20,
                      notnull=False)

    form = SQLFORM.factory(tax_identification,
                           fiscalname,
                           address,
                           city,
                           province,
                           country,
                           postalcode,
                           phone,
                           submit_button=('enviar datos',
                                          'siguiente')[wizard == True],
                           formstyle='bootstrap3_inline')

    if form.validate(keepvalues=True):
        if fiscal:  #update
            db(db.fiscals.id == fiscal.id).update(
                tax_identification=form.vars.tax_identification,
                fiscalname=form.vars.fiscalname,
                address=form.vars.address,
                city=form.vars.city,
                province=form.vars.province,
                country=form.vars.country,
                postal_code=form.vars.postal_code,
                phone=form.vars.phone)
        else:  #insert
            db.fiscals.insert(user=auth.user_id,
                              tax_identification=form.vars.tax_identification,
                              fiscalname=form.vars.fiscalname,
                              address=form.vars.address,
                              city=form.vars.city,
                              province=form.vars.province,
                              country=form.vars.country,
                              postal_code=form.vars.postal_code,
                              phone=form.vars.phone)
        session.flash = "Datos enviados correctamente"
        if wizard:
            redirect(URL(request.application, 'payment', 'index'))
        else:
            redirect(URL('account'))

    elif form.errors:
        response.flash = 'Hay errores'

    form.element('input[name=city]')['_class'] = 'form-control'
    form.element('input[name=province]')['_class'] = 'form-control'
    form.element('div#no_table_tax_identification__row div.col-sm-9'
                 )['_class'] = 'col-sm-3'
    form.element(
        'div#no_table_fiscalname__row div.col-sm-9')['_class'] = 'col-sm-4'
    form.element('div#no_table_city__row div.col-sm-9')['_class'] = 'col-sm-4'
    form.element(
        'div#no_table_province__row div.col-sm-9')['_class'] = 'col-sm-3'
    form.element(
        'div#no_table_country__row div.col-sm-9')['_class'] = 'col-sm-2'
    form.element(
        'div#no_table_postal_code__row div.col-sm-9')['_class'] = 'col-sm-2'
    form.element('div#no_table_phone__row div.col-sm-9')['_class'] = 'col-sm-4'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'

    return dict(form=form)
예제 #11
0
def restart():
    global cities
    cities = Cities()
    return "Browser restart"
예제 #12
0
import os
import socket
import datetime
import copy
import gluon.contenttype
import gluon.fileutils

from blog import Blog, Draft, Images
from shops import Shop, DomainShop, PricePlan, Product, ContractedProduct, ProfilePlan, PricePlan, CustomerAgreement, Agreement
from invoices import Invoice, Order, Orderlist, Fiscal, CreditAccount, AccountingEntry, Budget, Budgetlist
from regnews import Regnews
from province import Province
from cities import Cities
Images(db), Blog(db, ckeditor), Draft(
    db, ckeditor), Regnews(db), Province(db), Cities(db)
Shop(db), PricePlan(db), DomainShop(db), Product(db)
ProfilePlan(db), PricePlan(db), CustomerAgreement(db), Agreement(db)
Invoice(db), Order(db), Orderlist(db), Budget(db), Budgetlist(db), Fiscal(
    db), ContractedProduct(db), CreditAccount(db), AccountingEntry(db)

try:
    import pygraphviz as pgv
except ImportError:
    pgv = None

# ## critical --- make a copy of the environment

global_env = copy.copy(globals())
global_env['datetime'] = datetime
예제 #13
0
def newcustomer():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):

		from invoices import Fiscal
		from cities import Cities
		from province import Province
		Fiscal(db),	Province(db), Cities(db)

		wpoblacion = SQLFORM.widgets.autocomplete(request, db.cities.poblacion, limitby=(0,10), min_length=2)
		wprovincia = SQLFORM.widgets.autocomplete(request, db.province.provincia, limitby=(0,10), min_length=2)
		first_name = Field('first_name', 'string', label=XML("<strong>Nombre</strong>"), length=128, notnull=True, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
		last_name = Field('last_name', 'string', label=XML("<strong>Apellidos</strong>"), length=128, notnull=True, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
		password = Field('password', label = XML("<strong>Contraseña</strong>"), requires=[IS_NOT_EMPTY(error_message="No olvide esta dato")])
		email = Field('email',  label=XML('<strong>Email</strong>'), length=128,  notnull=True, requires=[IS_NOT_EMPTY(), IS_EMAIL(error_message='No puede estar vacío.'), IS_NOT_IN_DB(db,'auth_user.email')])
		tax_identification = Field('tax_identification', 'string', label=XML("<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"),length=45, notnull=False)
		fiscalname = Field('fiscalname', 'string', label=XML("<strong>Nombre empresa</strong>") ,length =128, notnull=False)
		address = Field('address', 'string', label=XML("<strong>Dirección</strong>"), length =196, notnull=False)
		city = Field('city', 'string',   label=XML("<strong>Ciudad/Población</strong>"), length=45, notnull=False, widget=wpoblacion)
		province = Field('province', 'string',   label=XML("<strong>Provincia</strong>"), length=45, notnull=False, widget=wprovincia)
		country = Field('country', 'string', label=XML("<strong>Pais</strong>"), length =45, notnull=False)
		postalcode = Field('postal_code', 'string', label=XML("<strong>Código postal</strong>"), length=10, notnull=False)
		phone = Field('phone', 'string', label=XML("<strong>Teléfono</strong>"), length=20, notnull=False)

		form = SQLFORM.factory(first_name, last_name, password, email, tax_identification, fiscalname, address, city, province, country, postalcode, phone, submit_button = 'enviar datos', formstyle='bootstrap3_inline')



		if form.validate(keepvalues=True):

			try:
				userid=db.auth_user.insert(first_name=form.vars.first_name,
									last_name=form.vars.last_name,
									password=CRYPT(key=Auth.get_or_create_key(), digest_alg='pbkdf2(1000,20,sha512)', salt=True)(form.vars.password)[0],
									email=form.vars.email)
				if userid:
					db.fiscals.insert(	user=userid, 
										tax_identification=form.vars.tax_identification, 
										fiscalname=form.vars.fiscalname,
										address=form.vars.address, 
										city=form.vars.city,
										province=form.vars.province,
										country=form.vars.country, 
										postal_code=form.vars.postal_code,
										phone=form.vars.phone)
					auth.add_membership(db(db.auth_group.role=="clientes").select().first()["id"], userid)
					db.commit()
				else:
					response.flash="no se ha creado al usario"

			except Exception, ex:
				logger.debug("No se pudo crear al nuevo cliente: %s" % ex)
				db.rollback()
				response.flash = 'Hubo un error: %s' % ex
			redirect(URL('administrator','editcustomer', args=userid))
		elif form.errors:
			response.flash = 'Hay errores'
		else:
			response.flash = 'Por favor completa los campos'
		
		form.element('input[name=city]')['_class']='form-control'
		form.element('input[name=province]')['_class']='form-control'
		
		return dict(form=form)
예제 #14
0
from cities import Cities

city = Cities()

#city.elimina_ciudad(8)

#city.inserta_ciudad('HHH', 'CytiName', 'capitale', 'MMN')

#city.modifica_ciudad(7, 'IN', 'Pais India', 'Capital de India', 'DDG')

print(city)
예제 #15
0
파일: paths.py 프로젝트: sw561/map_path
#!/usr/bin/env python

from cities import Cities, Equirectangular, Lambert, Mollweide, distance

# Example of using the cities module without plotting (much faster)
# Distance are by default in km unless use_miles is set to True
m = Cities(plot=False, use_miles=1)
print m.distance("London", "Los Angeles")
print m.distance("London", "Beijing")

# Use of miles / km can be switched after initialisation
# m.use_miles = True
# m.use_miles = False

# Cities instances initialised like this can't be used to plot
try:
    m.plot_path("London", "Beijing")
except TypeError as e:
    print e
else:
    print "Didn't catch exception here"

# Exceptions due to cities not being in the database can be caught
from cities import DatabaseKeyError
try:
    print m.distance("London", "Fake")
except DatabaseKeyError as e:
    print e
else:
    print "Didn't catch exception here"
예제 #16
0
# -*- coding: latin1 -*-
'''
Created on May 28, 2018

@author: Jesús Molina
'''

import time

from cities import Cities
from convoy_control import ConvoyControl

if __name__ == '__main__':

    game_time = 12
    main_city = Cities("Nuka Town", 20, 20, 20,
                       100)  #wood, oil, water, discontent.
    my_convoy_control = ConvoyControl()
    my_convoy_control.create_convoy("Slipknot", 100,
                                    10)  #name, health, number of escorts.
    my_convoy_control.create_convoy("Slayer", 100, 5)
    my_convoy_control.set_convoy_times("Slipknot", 13, 12)

    while True:

        print "\n"
        print "Time: " + str(game_time) + ":00"
        print "\n"

        my_convoy_control.time_control(game_time)

        print main_city
예제 #17
0
def myaccount():
    from invoices import Fiscal
    from cities import Cities
    from province import Province
    Fiscal(db), Province(db), Cities(db),

    customer = db(db.auth_user.id == auth.user_id).select(
        db.auth_user.id,
        db.auth_user.first_name,
        db.auth_user.last_name,
        db.auth_user.email,
        db.fiscals.ALL,
        left=[db.fiscals.on(db.fiscals.user == db.auth_user.id)]).first()

    wpoblacion = SQLFORM.widgets.autocomplete(request,
                                              db.cities.poblacion,
                                              limitby=(0, 10),
                                              min_length=2)
    wprovincia = SQLFORM.widgets.autocomplete(request,
                                              db.province.provincia,
                                              limitby=(0, 10),
                                              min_length=2)

    if customer != None:

        first_name = Field(
            'first_name',
            'string',
            label=XML("<strong>Nombre</strong>"),
            length=128,
            notnull=True,
            default=customer.auth_user.first_name,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        last_name = Field(
            'last_name',
            'string',
            label=XML("<strong>Apellidos</strong>"),
            length=128,
            notnull=True,
            default=customer.auth_user.last_name,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        email = Field('email',
                      label=XML('<strong>Email</strong>'),
                      length=128,
                      writable=False,
                      notnull=True,
                      default=customer.auth_user.email,
                      requires=[
                          IS_NOT_EMPTY(),
                          IS_EMAIL(error_message='No puede estar vacío.')
                      ])
        tax_identification = Field(
            'tax_identification',
            'string',
            label=XML(
                "<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"
            ),
            length=45,
            notnull=True,
            default=customer.fiscals.tax_identification,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        fiscalname = Field('fiscalname',
                           'string',
                           label=XML("<strong>Nombre empresa</strong>"),
                           length=128,
                           notnull=False,
                           default=customer.fiscals.fiscalname)
        address = Field(
            'address',
            'string',
            label=XML("<strong>Dirección</strong>"),
            length=196,
            notnull=True,
            default=customer.fiscals.address,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        city = Field(
            'city',
            'string',
            label=XML("<strong>Ciudad/Población</strong>"),
            length=45,
            notnull=True,
            default=customer.fiscals.city,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wpoblacion)
        province = Field(
            'province',
            'string',
            label=XML("<strong>Provincia</strong>"),
            length=45,
            notnull=True,
            default=customer.fiscals.province,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wprovincia)
        country = Field(
            'country',
            'string',
            label=XML("<strong>Pais</strong>"),
            length=45,
            notnull=True,
            default=customer.fiscals.country,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        postalcode = Field('postal_code',
                           'string',
                           label=XML("<strong>Código postal</strong>"),
                           length=10,
                           notnull=False,
                           default=customer.fiscals.postal_code)
        phone = Field('phone',
                      'string',
                      label=XML("<strong>Teléfono</strong>"),
                      length=20,
                      notnull=False,
                      default=customer.fiscals.phone)

        form = SQLFORM.factory(first_name,
                               last_name,
                               email,
                               tax_identification,
                               fiscalname,
                               address,
                               city,
                               province,
                               country,
                               postalcode,
                               phone,
                               submit_button='modificar datos',
                               formstyle='bootstrap3_inline')

        if form.validate(keepvalues=True):

            try:
                db(db.auth_user.id == customer.auth_user.id).update(
                    first_name=form.vars.first_name,
                    last_name=form.vars.last_name)
                db(db.fiscals.id == customer.fiscals.id).update(
                    tax_identification=form.vars.tax_identification,
                    fiscalname=form.vars.fiscalname,
                    address=form.vars.address,
                    city=form.vars.city,
                    province=form.vars.province,
                    country=form.vars.country,
                    postal_code=form.vars.postal_code,
                    phone=form.vars.phone)
                db.commit()
            except Exception, ex:
                logger.debug(
                    "No se pudo modificar los datos del usuario/fiscal: %s" %
                    ex)
                db.rollback()
                response.flash = 'Hubo un error: %s' % ex
            response.flash = "Datos modificados correctamente"
        elif form.errors:
            response.flash = 'Hay errores'
        else:
            response.flash = 'Por favor completa los campos'

        form.element('input[name=city]')['_class'] = 'form-control'
        form.element('input[name=province]')['_class'] = 'form-control'

        form.element('input[name=city]')['_class'] = 'form-control'
        form.element('input[name=province]')['_class'] = 'form-control'
        form.element(
            'div#no_table_first_name__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element(
            'div#no_table_last_name__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element('div#no_table_tax_identification__row div.col-sm-9'
                     )['_class'] = 'col-sm-3'
        form.element(
            'div#no_table_fiscalname__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element(
            'div#no_table_city__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element(
            'div#no_table_province__row div.col-sm-9')['_class'] = 'col-sm-3'
        form.element(
            'div#no_table_country__row div.col-sm-9')['_class'] = 'col-sm-2'
        form.element('div#no_table_postal_code__row div.col-sm-9'
                     )['_class'] = 'col-sm-2'
        form.element(
            'div#no_table_phone__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element('label#no_table_first_name__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_last_name__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element(
            'label#no_table_email__label')['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_fiscalname__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_tax_identification__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_address__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element(
            'label#no_table_city__label')['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_province__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_country__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_postal_code__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element(
            'label#no_table_phone__label')['_class'] = 'col-sm-2 control-label'
        form.element('div#submit_record__row div.col-sm-9'
                     )['_class'] = 'col-sm-9 col-sm-offset-2'
        return dict(form=form, userid=customer.auth_user.id)
예제 #18
0
def editcustomer():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		if request.args(0):
			from invoices import Fiscal, Order, Orderlist, Invoice, Budget, AccountingEntry, CreditAccount
			from shops import ContractedProduct, Product, Shop
			from cities import Cities
			from province import Province
			Fiscal(db),	Province(db), Cities(db), ContractedProduct(db), Product(db), Shop(db), Order(db), Orderlist(db), AccountingEntry(db), CreditAccount(db),  Invoice(db), Budget(db)
			
			customer=db(db.auth_user.id==request.args(0)).select(	db.auth_user.id,
																	db.auth_user.first_name,
																	db.auth_user.last_name,
																	db.auth_user.email,
																	db.fiscals.ALL,
																	left=[db.fiscals.on(db.fiscals.user==db.auth_user.id)]).first()
			
			wpoblacion = SQLFORM.widgets.autocomplete(request, db.cities.poblacion, limitby=(0,10), min_length=2)
			wprovincia = SQLFORM.widgets.autocomplete(request, db.province.provincia, limitby=(0,10), min_length=2)


			inc=datetime.timedelta(days=30)
			
			contractedproducts = db((db.contractedproducts.user==request.args(0)) & 
									(	(db.contractedproducts.expiration+inc>=datetime.datetime.now()) | 
										(db.contractedproducts.expiration==None)	)).select(	db.contractedproducts.ALL,
																							db.products.ALL,
																							db.shop.ALL,
																							db.auth_user.ALL,
																							db.fiscals.ALL,
																							left=[	db.products.on(db.products.id==db.contractedproducts.product),
																									db.shop.on(db.shop.id==db.contractedproducts.shop),
																									db.auth_user.on(db.auth_user.id==db.contractedproducts.user),
																									db.fiscals.on(db.fiscals.user==db.auth_user.id)],
																							orderby=~db.contractedproducts.expiration)

			invoices = db( db.invoices.user==request.args(0)).select(db.invoices.ALL,
																	db.orders.id,
																	db.orders.status,
																	left=[  db.orders.on(db.orders.invoice==db.invoices.id)],
																	orderby=~db.invoices.id,
																	groupby=db.orders.id
																	)
			

			budgets = db((db.budgets.user==request.args(0)) & (db.budgets.status!="Creando")).select(db.budgets.ALL, orderby=~db.budgets.id)

			orders= db((db.orders.invoice==None) & (db.orders.user==request.args(0))).select(orderby=~db.orders.id)

			if customer!=None:

				first_name= Field('first_name', 'string', label=XML("<strong>Nombre</strong>"), length=128, notnull=True, default=customer.auth_user.first_name, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
				last_name= Field('last_name', 'string', label=XML("<strong>Apellidos</strong>"), length=128, notnull=True, default=customer.auth_user.last_name, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
				email=Field('email',  label=XML('<strong>Email</strong>'), length=128,  writable=False, notnull=True, default=customer.auth_user.email, requires=[IS_NOT_EMPTY(), IS_EMAIL(error_message='No puede estar vacío.')])
				tax_identification = Field('tax_identification', 'string', label=XML("<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"),length=45, notnull=True, default=customer.fiscals.tax_identification, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
				fiscalname=Field('fiscalname', 'string', label=XML("<strong>Nombre empresa</strong>") ,length =128, notnull=False, default=customer.fiscals.fiscalname)
				address=Field('address', 'string', label=XML("<strong>Dirección</strong>"), length =196, notnull=True, default=customer.fiscals.address, requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
				city= Field('city', 'string',   label=XML("<strong>Ciudad/Población</strong>"), length=45, notnull=True, default=customer.fiscals.city, requires=IS_NOT_EMPTY(error_message="no olvide este dato"), widget=wpoblacion)
				province = Field('province', 'string',   label=XML("<strong>Provincia</strong>"), length=45, notnull=True, default=customer.fiscals.province, requires=IS_NOT_EMPTY(error_message="no olvide este dato"), widget=wprovincia)
				country=Field('country', 'string', label=XML("<strong>Pais</strong>"), length =45, notnull=True, default=customer.fiscals.country, requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
				postalcode=Field('postal_code', 'string', label=XML("<strong>Código postal</strong>"), length=10, notnull=False, default=customer.fiscals.postal_code)
				phone=Field('phone', 'string', label=XML("<strong>Teléfono</strong>"), length=20, notnull=False, default=customer.fiscals.phone)

				form = SQLFORM.factory(first_name, last_name, email, tax_identification, fiscalname, address, city, province, country, postalcode, phone, submit_button = 'enviar datos', formstyle='bootstrap3_inline')



				if form.validate(keepvalues=True):

					try:
						db(db.auth_user.id==customer.auth_user.id).update(first_name=form.vars.first_name,
																		  last_name=form.vars.last_name)
						db(db.fiscals.id==customer.fiscals.id).update(tax_identification=form.vars.tax_identification, 
															fiscalname=form.vars.fiscalname,
															address=form.vars.address, 
															city=form.vars.city,
															province=form.vars.province,
															country=form.vars.country, 
															postal_code=form.vars.postal_code,
															phone=form.vars.phone)
						db.commit()
					except Exception, ex:
						logger.debug("No se pudo modificar los datos del usuario/fiscal: %s" % ex)
						db.rollback()
						response.flash = 'Hubo un error: %s' % ex				
					response.flash="Datos enviados correctamente"
				elif form.errors:
					response.flash = 'Hay errores'

				
				form.element('input[name=city]')['_class']='form-control'
				form.element('input[name=province]')['_class']='form-control'


				creditaccount=db(db.creditaccounts.user==customer.auth_user.id).select().first()
				accountingentries=None

				if creditaccount:
					accountingentries = db(	(db.accountingentries.creditaccount==creditaccount.id) &
											(db.accountingentries.active==True) ).select(	db.accountingentries.ALL, 
																							db.orders.ALL,
																							db.invoices.ALL,
																							db.products.name,
																							join=[	db.orderlist.on(db.accountingentries.orderlist==db.orderlist.id),
																									db.products.on(db.products.id==db.orderlist.product),
																									db.orders.on(db.orders.id==db.orderlist.g_order),
																									db.invoices.on(db.invoices.id==db.orders.invoice)],
																							orderby=~db.accountingentries.id)




				return dict(form=form, contractedproducts=contractedproducts, invoices=invoices, budgets=budgets, orders=orders, userid=customer.auth_user.id, accountingentries=accountingentries, creditaccount=creditaccount)

			else:
				redirect(URL('administrator','newcustomer'))
		else:
			redirect(URL('administrator','users'))
예제 #19
0
from cities import Cities
ciudades = Cities()

menu = '''\n****************************
*       MENU PAISES        *
****************************
*                          *
*  i) Insertar País        *
*  e) Eliminar País        *
*  m) Modificar País       *
*  p) Imprimir Paises      *
*  x) Salir                *
*                          *
****************************'''


def main():
    opcion = 0
    while opcion != 'X':
        print(menu)
        opcion = input("Que deseas hacer?").upper()

        if opcion == 'I':
            print("******* Insertar Paises******")
            ISO3 = input("Introduce la clave ISO3 del nuevo País:  ")
            CountryName = input("Introduce el nombre del nuevo País:  ")
            Capital = input("Introduce la capital  del nuevo País:  ")
            CurrencyCode = input("Introduce el código de su moneda:  ")
            r = ciudades.inserta_ciudad(ISO3, CountryName, Capital,
                                        CurrencyCode)
            if (r == 0):
예제 #20
0
def handler(event, context):
    body_cities = None
    body_distances = None
    population_size = 20
    mutation_rate = 1  # 1% - taxa de mutação
    generations = 1000  # critério de parada
    time_distances = []

    if event:
        event = json.loads(event['body'])
        population_size = int(event['populationSize'])
        mutation_rate = int(event["mutationRate"])
        generations = int(event["generations"])
        body_cities = event['cities']
        body_distances = event["distances"]

    try:
        c = Cities()
        if body_cities and body_distances:
            c.set_cities(body_cities, body_distances)
        else:
            c.test()  # carrega cidades para testes

        cities_list = c.get_cities()

        for city in cities_list:
            print("Distâncias da cidade: %s\n******" % city.name)
            time_distances.append(city.distances)
            print(city.distances)
            for index, distance in enumerate(city.distances):
                print("De %s --> %s = %s" %
                      (city.name, cities_list[index].name, distance))

        ga = GeneticAlgorithm(population_size)
        result = ga.resolve(mutation_rate, generations, time_distances,
                            cities_list)

        print({
            'generation': result[0],
            'travelled_distance': result[1],
            'chromosome': result[2],
            'cities': c.chromose_to_cities(result[2])
        })

        return {
            'statusCode':
            200,
            'headers': {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json'
            },
            'body':
            json.dumps({
                'generation': result[0],
                'travelled_distance': result[1],
                'chromosome': result[2],
                'cities': c.chromose_to_cities(result[2])
            })
        }

    except ImportError:
        print(ImportError)
        return {
            'statusCode': 500,
            'body': json.dumps({'message': "Erro ao executar"})
        }
예제 #21
0
from celery import Celery
from cities import Cities
from selenium.common.exceptions import SessionNotCreatedException

MAX_TRIES = 2

app = Celery('tasks', backend='rpc://', broker='pyamqp://guest@localhost//')
cities = Cities()


@app.task
def add(x, y):
    return x + y


@app.task
def nyc_zone(address, zip, retry=0):
    try:
        return cities.nyc.get_zone(address, zip)
    except SessionNotCreatedException:
        if retry < MAX_TRIES:
            restart()
            return nyc_zone(address, zip, retry + 1)
        else:
            return "NYC lookup failed"


@app.task
def dc_zone(address, zip):
    try:
        return cities.dc.get_zone(address, zip)