Ejemplo n.º 1
0
def openInputXLS(evt):
    if os.path.isfile(mywin['txtInputXLS'].value):
        #startcommand = 'start excel "' + mywin['txtInputXLS'].value + '"'
        startcommand = '"' + mywin['txtInputXLS'].value + '"'
        os.popen(startcommand)
    else:
        gui.alert("Please select a valid Input XLS first.")
def doScrape(evt):
    if num_of_search_criteria_enetered(evt) < 2:
        gui.alert("Enter at least two search criteria")
        return
    if not os.path.isdir(mywin['txtOutputDir'].value):
        os.makedirs(mywin['txtOutputDir'].value)
    config.outputDir = mywin['txtOutputDir'].value

    try:
        if mywin['chkRunInBrowser'].value:
            gui.alert("You have chosen to execute scraping in browser.\nPlease do no touch your mouse or keyboard during scraping.")
        else:
            if not gui.confirm("Scraping will run in background. Please be patient.\nDo you want to proceed?"):
                return
        config.RunInBrowser = mywin['chkRunInBrowser'].value
        # gui.alert("Scraping results. Please wait.")
        mywin.minimized = True
        ret_value = Scraping_Main.doScrape()
        mywin.minimized = False
        if ret_value == 1:
            gui.alert("Scraping Done !!!")
        elif ret_value == "NO_RESULTS":
            gui.alert("Your search query returned zero results !!!")
        else:
            gui.alert("There were some problems with the scraping. Please report to developer.")
    except:
        logger.exception(sys.exc_info())
    finally:
        mywin.minimized = False
    pass
Ejemplo n.º 3
0
 def on_btnEnviar_click(self, event):
     try:
         ok = no = 0
         self.progreso(0)
         for i, item in self.get_selected_items():
             if not item['cae'] in ("", "NULL"):
                 archivo = self.generar_factura(item)
                 if item.get('email'):
                     self.enviar_mail(item, archivo)
                     ok += 1
                 else:
                     no += 1
                     self.log("No se envia factura %s por no tener EMAIL" %
                              item['cbt_numero'])
             else:
                 self.log("No se envia factura %s por no tener CAE" %
                          item['cbt_numero'])
                 no += 1
             self.progreso(i)
         self.progreso(len(self.items))
         gui.alert(
             'Proceso finalizado OK!\n\nEnviados: %d\nNo enviados: %d' %
             (ok, no), 'Envio de Email')
     except Exception as e:
         self.error('Excepción', str(e))
Ejemplo n.º 4
0
def doAutoFlagging(evt):
    if os.path.isfile(mywin['txtInputXLS'].value):
        if not os.path.isdir(mywin['txtOutputImages'].value):
            os.makedirs(mywin['txtOutputImages'].value)
        config.inputXLSPath = mywin['txtInputXLS'].value
        config.outputXLSPath = mywin['txtOutputXLS'].value
        config.outputImagesPath = mywin['txtOutputImages'].value
        mywin['btnOpenOutput'].enabled = False
        mywin.minimized = True
        mywin.enabled = False
        # noinspection PyBroadException
        try:
            retValue = CL_AutoFlagging.main()
            mywin.enabled = True
            mywin.minimized = False
            mywin['btnOpenOutput'].enabled = True

            if retValue == 1:
                mbResponse = gui.confirm(
                    message="Thanks for using CL_AutoFlagging by K Team \nDo you want to open output file?",
                    title="Flagging Complete !",
                )
                if mbResponse:
                    openOutputXLS(evt)
        except:
            module_logger.exception(sys.exc_info())
        finally:
            mywin.enabled = True
            mywin.minimized = False
    else:
        gui.alert("Please select a valid Input XLS first.")
Ejemplo n.º 5
0
def openOutputXLS(evt):
    if os.path.isfile(mywin['txtOutputXLS'].value):
        #startcommand = 'start excel "' + mywin['txtOutputXLS'].value + '"'
        startcommand = '"' + mywin['txtOutputXLS'].value + '"'
        os.popen(startcommand)
    else:
        gui.alert("Output XLS first does not exist.")
Ejemplo n.º 6
0
 def grabar(self, fn=None):
     try:
         if fn is None and salida:
             if salida.startswith("-") and self.paths:
                 fn = os.path.splitext(self.paths[0])[0] + salida
             else:
                 fn = salida
         elif not fn:
             raise RuntimeError(
                 "Debe indicar un nombre de archivo para grabar")
         if fn.lower().endswith(".csv") or fn.lower().endswith(".xlsx"):
             formato_csv.escribir([self.cols] +
                                  [[item[k] for k in self.cols]
                                   for item in self.items], fn)
         else:
             regs = formato_csv.desaplanar([self.cols] +
                                           [[item[k] for k in self.cols]
                                            for item in self.items])
             if fn.endswith(".xml"):
                 formato_xml.escribir(regs, fn)
             elif fn.endswith(".txt"):
                 formato_txt.escribir(regs, fn)
             elif fn.endswith(".dbf"):
                 formato_dbf.escribir(regs,
                                      conf_dbf,
                                      carpeta=os.path.dirname(fn))
             elif fn.endswith(".json"):
                 formato_json.escribir(regs, fn)
             else:
                 self.error('Formato de archivo desconocido', str(fn))
         gui.alert('Se guardó con éxito el archivo:\n%s' % (str(fn), ),
                   'Guardar')
     except Exception as e:
         self.error('Excepción', str(e))
Ejemplo n.º 7
0
 def verifica_ws(self):
     if not self.ws:
         gui.alert("Debe seleccionar el webservice a utilizar!",
                   'Advertencia')
         raise RuntimeError()
     if not self.token or not self.sign:
         gui.alert("Debe autenticarse con AFIP!", 'Advertencia')
         raise RuntimeError()
     self.ws.Dummy()
Ejemplo n.º 8
0
    def on_menu_consultas_getCAE_click(self, event):
        self.verifica_ws()
        options = [
            v for k, v in sorted([(k, v) for k, v in list(self.tipos.items())])
        ]
        result = gui.single_choice(
            options,
            "Tipo de comprobante",
            "Consulta Comprobante",
        )
        if not result:
            return
        tipocbte = [k for k, v in list(self.tipos.items()) if v == result][0]
        result = gui.prompt("Punto de venta", "Consulta Comprobante", '2')
        if not result:
            return
        ptovta = result
        result = gui.prompt("Nº de comprobante", "Consulta Comprobante", '2')
        if not result:
            return
        nrocbte = result

        try:
            if self.webservice == "wsfe":
                cae = 'no soportado'
            elif self.webservice == "wsfev1":
                cae = "%s (wsfev1)" % self.ws.CompConsultar(
                    tipocbte, ptovta, nrocbte)
                self.log('CAE: %s' % self.ws.CAE)
                self.log('FechaCbte: %s' % self.ws.FechaCbte)
                self.log('PuntoVenta: %s' % self.ws.PuntoVenta)
                self.log('CbteNro: %s' % self.ws.CbteNro)
                self.log('ImpTotal: %s' % self.ws.ImpTotal)
                self.log('ImpNeto: %s' % self.ws.ImpNeto)
                self.log('ImptoLiq: %s' % self.ws.ImptoLiq)
                self.log('EmisionTipo: %s' % self.ws.EmisionTipo)
            elif self.webservice == "wsfexv1":
                cae = "%s (wsfexv1)" % self.ws.GetCMP(tipocbte, ptovta,
                                                      nrocbte)
                self.log('CAE: %s' % self.ws.CAE)
                self.log('FechaCbte: %s' % self.ws.FechaCbte)
                self.log('PuntoVenta: %s' % self.ws.PuntoVenta)
                self.log('CbteNro: %s' % self.ws.CbteNro)
                self.log('ImpTotal: %s' % self.ws.ImpTotal)

            gui.alert(
                "CAE: %s\n"
                "Tipo: %s (%s)\nPunto de Venta: %s\nNumero: %s\nFecha: %s" %
                (cae, self.tipos[tipocbte], tipocbte, ptovta, nrocbte,
                 self.ws.FechaCbte), 'Consulta Comprobante')

        except SoapFault as e:
            self.log(self.client.xml_request)
            self.log(self.client.xml_response)
            self.error(e.faultcode, e.faultstring.encode("ascii", "ignore"))
        except Exception as e:
            self.error('Excepción', str(str(e), "latin1", "ignore"))
Ejemplo n.º 9
0
def send(evt):
    "Process an outgoing communication"
    # get the text written by the user (input textbox control)
    msg = ctrl_input.value
    # send the message (replace with socket/queue/etc.)
    gui.alert(msg, "Message")
    # record the message (update the UI)
    log(msg)
    ctrl_input.value = ""
    ctrl_input.set_focus()
Ejemplo n.º 10
0
def send(evt):
    "Process an outgoing communication"
    # get the text written by the user (input textbox control)
    msg = ctrl_input.value
    # send the message (replace with socket/queue/etc.)
    gui.alert(msg, "Message")
    # record the message (update the UI)
    log(msg)
    ctrl_input.value = ""
    ctrl_input.set_focus()
Ejemplo n.º 11
0
def save_entropy_plain():
    obj = {"entropy": hexlify(entropy).decode('utf-8')}
    with open(reckless_fname, "w") as f:
        f.write(json.dumps(obj))
    with open(reckless_fname, "r") as f:
        d = json.loads(f.read())
    if "entropy" in d  and d["entropy"] == hexlify(entropy).decode('utf-8'):
        gui.alert("Success!", "Your key is saved in the memory now")
    else:
        gui.error("Something went wrong")
Ejemplo n.º 12
0
 def on_menu_consultas_dummy_click(self, event):
     ##self.verifica_ws()
     try:
         if self.webservice in ("wsfev1", "wsfexv1"):
             self.ws.Dummy()
             msg = "AppServ %s\nDbServer %s\nAuthServer %s" % (
                 self.ws.AppServerStatus, self.ws.DbServerStatus,
                 self.ws.AuthServerStatus)
             location = self.ws.client.location
         else:
             msg = "%s no soportado" % self.webservice
             location = ""
         gui.alert(msg, location)
     except Exception as e:
         self.error('Excepción', str(str(e), "latin1", "ignore"))
Ejemplo n.º 13
0
 def on_menu_consultas_lastID_click(self, event):
     ##self.verifica_ws()
     try:
         if self.webservice == "wsfexv1":
             ultnro = self.ws.GetLastID()
         else:
             ultnro = None
         gui.alert("Último ID (máximo): %s" % (ultnro),
                   'Consulta Último ID')
     except SoapFault as e:
         self.log(self.client.xml_request)
         self.log(self.client.xml_response)
         self.error(e.faultcode, e.faultstring.encode("ascii", "ignore"))
     except Exception as e:
         self.error('Excepción', str(e))
Ejemplo n.º 14
0
	def button_press_update(self, evt):
		param = {}
		controles = self.controls
		for d in controles.iterkeys():
			ctrl = panel['record'][controles[d]['name']]
			if d != 'id':
				param[controles[d]['field']] = ctrl.value
			else:
				valorid = ctrl.value
		
		if not self.nuevo:
			self.db(self.db[self.tabla]._id==valorid).update(**param)
		else:
			self.db[self.tabla].insert(**param)
		
		self.db.commit()
		gui.alert("Datos grabados correctamente")
		if DEBUG:
			print self.db._lastsql
Ejemplo n.º 15
0
def actualizar(evt):
    "Agregar o actualizar los datos del cliente"
    nro_doc = panel['nro_doc'].value.replace('-','')
    tipo_doc = panel['tipo_doc'].value
    denominacion = panel['nombre'].value
    cat_iva = panel['cat_iva'].value
    direccion = panel['domicilio'].value
    email = panel['email'].value
    imp_ganancias = panel['ganancias'].value
    imp_iva = panel['impiva'].value
    monotributo = panel['monotributo'].value if cat_iva == 6 else 'NI'
    integrante_soc = 'S' if panel['intsociedad'].value else 'N'
    empleador = 'S' if panel['empleador'].value else 'N'
	
    if padron.Guardar(tipo_doc, nro_doc, denominacion, cat_iva, 
                     direccion, email, imp_ganancias, imp_iva,
                     monotributo, integrante_soc, empleador):
        gui.alert(u"Se ha guardado la informacion correctamente")
    else:
        gui.alert(u"Se ha producido un errror y no se guardo la informacion")
Ejemplo n.º 16
0
def actualizar(evt):
    "Agregar o actualizar los datos del cliente"
    nro_doc = panel['nro_doc'].value.replace('-', '')
    tipo_doc = panel['tipo_doc'].value
    denominacion = panel['nombre'].value
    cat_iva = panel['cat_iva'].value
    direccion = panel['domicilio'].value
    email = panel['email'].value
    imp_ganancias = panel['ganancias'].value
    imp_iva = panel['impiva'].value
    monotributo = panel['monotributo'].value if cat_iva == 6 else 'NI'
    integrante_soc = 'S' if panel['intsociedad'].value else 'N'
    empleador = 'S' if panel['empleador'].value else 'N'

    if padron.Guardar(tipo_doc, nro_doc, denominacion, cat_iva, direccion,
                      email, imp_ganancias, imp_iva, monotributo,
                      integrante_soc, empleador):
        gui.alert(u"Se ha guardado la informacion correctamente")
    else:
        gui.alert(u"Se ha producido un errror y no se guardo la informacion")
Ejemplo n.º 17
0
def save_entropy_encrypted():
    try:
        Key.iv = get_random_bytes(16)
        entropy_encrypted = entropy_encrypt(entropy)
        hmac_entropy_encrypted = hmac_sha512(Key.key, entropy_encrypted)
        obj = {
            "entropy": hexlify(entropy_encrypted).decode('utf-8'),
            "iv": hexlify(Key.iv).decode('utf-8'),
            "hmac": hexlify(hmac_entropy_encrypted).decode('utf-8')
        }
        with open(reckless_fname, "w") as f:
            f.write(json.dumps(obj))
        with open(reckless_fname, "r") as f:
            d = json.loads(f.read())
        if "entropy" in d and d["entropy"] == hexlify(entropy_encrypted).decode('utf-8') and \
                unhexlify(d["hmac"]) == hmac_entropy_encrypted and entropy == entropy_decrypt(entropy_encrypted):
            gui.alert("Success!", "Your encrypted key is saved in the memory now")
        else:
            gui.error("Something went wrong")
    except Exception as e:
        gui.error("Fail: %r" % e)
Ejemplo n.º 18
0
def count_load(evt):

    a = mywin['edit_count'].value
    try:
        a = int(a)
        f = open('data.txt', 'w')
        pickle.dump(a, f)
        f.close()
        f = open('data.txt', 'r')
        var1 = pickle.load(f)
        #print var1, "Bombs So Far At:", time.ctime()

        bombnum = a
        mywin['count'].left = '860'
        if (9 < a < 100):
            mywin['count'].left = '790'
        if (99 < a < 1000):
            mywin['count'].left = '720'
        if (999 < a):
            mywin['count'].left = '660'
        #mywin['count'].left = '660'
        mywin['count'].size = (0, 0)
        mywin['count'].text = u'%s' % (bombnum)
        mywin['edit_count'].visible = False
        mywin['load'].visible = False
        mywin['initi'].visible = False
        mywin['cans'].visible = False
        mywin['count'].visible = True
        mywin['made'].visible = True
        mywin['bombs'].visible = True
        mywin['bombpase'].visible = True
        mywin['ryth'].visible = True
        mywin['shiftbombpase'].visible = True
        mywin['shiftryth'].visible = True
        mywin['hour'].visible = True
        mywin['edit_count'].value = ''
    except:
        gui.alert(u'?? ????? ???? ????? ????')
Ejemplo n.º 19
0
 def cargar(self):
     try:
         items = []
         for fn in self.paths:
             if fn.lower().endswith(".csv") or fn.lower().endswith(".xlsx"):
                 filas = formato_csv.leer(fn)
                 items.extend(filas)
             elif fn.lower().endswith(".xml"):
                 regs = formato_xml.leer(fn)
                 items.extend(formato_csv.aplanar(regs))
             elif fn.lower().endswith(".txt"):
                 regs = formato_txt.leer(fn)
                 items.extend(formato_csv.aplanar(regs))
             elif fn.lower().endswith(".dbf"):
                 reg = formato_dbf.leer(conf_dbf,
                                        carpeta=os.path.dirname(fn))
                 items.extend(formato_csv.aplanar(list(reg.values())))
             elif fn.lower().endswith(".json"):
                 regs = formato_json.leer(fn)
                 items.extend(formato_csv.aplanar(regs))
             else:
                 self.error('Formato de archivo desconocido: %s', str(fn))
         if len(items) < 2:
             gui.alert('El archivo no tiene datos válidos', 'Advertencia')
         # extraer los nombres de columnas (ignorar vacios de XLSX)
         cols = items and [str(it).strip() for it in items[0] if it] or []
         if DEBUG:
             print("Cols", cols)
         # armar diccionario por cada linea
         items = [
             dict([(col, item[i]) for i, col in enumerate(cols)])
             for item in items[1:]
         ]
         self.cols = cols
         self.items = items
     except Exception as e:
         self.error('Excepción', str(e))
Ejemplo n.º 20
0
    def on_menu_consultas_lastCBTE_click(self, event):
        ##self.verifica_ws()
        options = [
            v for k, v in sorted([(k, v) for k, v in list(self.tipos.items())])
        ]
        result = gui.single_choice(
            options,
            "Tipo de comprobante",
            "Consulta Último Nro. Comprobante",
        )
        if not result:
            return
        tipocbte = [k for k, v in list(self.tipos.items()) if v == result][0]
        result = gui.prompt("Punto de venta",
                            "Consulta Último Nro. Comprobante", '2')
        if not result:
            return
        ptovta = result

        try:
            if self.webservice == "wsfev1":
                ultcmp = "%s (wsfev1)" % self.ws.CompUltimoAutorizado(
                    tipocbte, ptovta)
            elif self.webservice == "wsfexv1":
                ultcmp = "%s (wsfexv1)" % self.ws.GetLastCMP(tipocbte, ptovta)

            gui.alert(
                "Último comprobante: %s\n"
                "Tipo: %s (%s)\nPunto de Venta: %s" %
                (ultcmp, self.tipos[tipocbte], tipocbte, ptovta),
                'Consulta Último Nro. Comprobante')
        except SoapFault as e:
            self.log(self.client.xml_request)
            self.log(self.client.xml_response)
            self.error(e.faultcode, e.faultstring.encode("ascii", "ignore"))
        except Exception as e:
            self.error('Excepción', str(str(e), "latin1", "ignore"))
Ejemplo n.º 21
0
	def send_message(self, evt):
		to = mywin['notebook']['tab_message']['to'].value
		sender = mywin['notebook']['tab_message']['from'].value
		message = mywin['notebook']['tab_message']['message'].value
		r = self.__get_api__()
		r.set_type(self.mtype)
		if self.mtype == 'mms':
			r.set_image(self.imgfile)
		status = r.send(to, message, sender)
		if status == False:
			mywin['statusbar'].text = r.get_error()
			gui.alert(r.get_error())
			return

		if int(status['error_count']) > 0:
			gui.alert("%u 개의 메시지에 오류가 발생했습니다." % int(status['error_count']))
		else:
			gui.alert("Sent!")

		print status['result_message']
		mywin['statusbar'].text = status['result_message'].encode('utf-8')
Ejemplo n.º 22
0
    def on_btnAutorizar_click(self, event):
        self.verifica_ws()
        try:
            ok = procesadas = rechazadas = 0
            cols = self.cols
            items = []
            self.progreso(0)
            selected = []
            for i, item in self.get_selected_items():
                kargs = item.copy()
                selected.append(item)
                kargs['cbt_desde'] = kargs['cbt_hasta'] = kargs['cbt_numero']
                for key in kargs:
                    if isinstance(kargs[key], str):
                        kargs[key] = kargs[key].replace(",", ".")
                if self.webservice == 'wsfev1':
                    encabezado = {}
                    for k in ('concepto', 'tipo_doc', 'nro_doc', 'tipo_cbte',
                              'punto_vta', 'cbt_desde', 'cbt_hasta',
                              'imp_total', 'imp_tot_conc', 'imp_neto',
                              'imp_iva', 'imp_trib', 'imp_op_ex', 'fecha_cbte',
                              'moneda_id', 'moneda_ctz'):
                        encabezado[k] = kargs[k]

                    for k in ('fecha_venc_pago', 'fecha_serv_desde',
                              'fecha_serv_hasta'):
                        if k in kargs:
                            encabezado[k] = kargs.get(k)

                    self.ws.CrearFactura(**encabezado)

                    for l in range(1, 1000):
                        k = 'tributo_%%s_%s' % l
                        if (k % 'id') in kargs:
                            id = kargs[k % 'id']
                            desc = kargs[k % 'desc']
                            base_imp = kargs[k % 'base_imp']
                            alic = kargs[k % 'alic']
                            importe = kargs[k % 'importe']
                            if id:
                                self.ws.AgregarTributo(id, desc, base_imp,
                                                       alic, importe)
                        else:
                            break

                    for l in range(1, 1000):
                        k = 'iva_%%s_%s' % l
                        if (k % 'id') in kargs:
                            id = kargs[k % 'id']
                            base_imp = kargs[k % 'base_imp']
                            importe = kargs[k % 'importe']
                            if id:
                                self.ws.AgregarIva(id, base_imp, importe)
                        else:
                            break

                    for l in range(1, 1000):
                        k = 'cbte_asoc_%%s_%s' % l
                        if (k % 'tipo') in kargs:
                            tipo = kargs[k % 'tipo']
                            pto_vta = kargs[k % 'pto_vta']
                            nro = kargs[k % 'nro']
                            if id:
                                self.ws.AgregarCmpAsoc(tipo, pto_vta, nro)
                        else:
                            break

                    for l in range(1, 1000):
                        k = 'opcional_%%s_%s' % l
                        if (k % 'id') in kargs:
                            op_id = kargs[k % 'id']
                            valor = kargs[k % 'valor']
                            if op_id:
                                self.ws.AgregarOpcional(op_id, valor)
                        else:
                            break

                    if DEBUG:
                        self.log('\n'.join([
                            "%s='%s'" % (k, v)
                            for k, v in list(self.ws.factura.items())
                        ]))

                    cae = self.ws.CAESolicitar()
                    kargs.update({
                        'cae': self.ws.CAE,
                        'fecha_vto': self.ws.Vencimiento,
                        'resultado': self.ws.Resultado,
                        'motivo': self.ws.Obs,
                        'reproceso': self.ws.Reproceso,
                        'err_code': self.ws.ErrCode.encode("latin1"),
                        'err_msg': self.ws.ErrMsg.encode("latin1"),
                    })
                    if self.ws.ErrMsg:
                        gui.alert(self.ws.ErrMsg, "Error AFIP")
                    if self.ws.Obs and self.ws.Obs != '00':
                        gui.alert(self.ws.Obs, "Observación AFIP")

                elif self.webservice == 'wsfexv1':
                    kargs['cbte_nro'] = kargs['cbt_numero']
                    kargs[
                        'permiso_existente'] = kargs['permiso_existente'] or ""
                    encabezado = {}
                    for k in ('tipo_cbte', 'punto_vta', 'cbte_nro',
                              'fecha_cbte', 'imp_total', 'tipo_expo',
                              'permiso_existente', 'pais_dst_cmp',
                              'nombre_cliente', 'cuit_pais_cliente',
                              'domicilio_cliente', 'id_impositivo',
                              'moneda_id', 'moneda_ctz', 'obs_comerciales',
                              'obs_generales', 'forma_pago', 'incoterms',
                              'idioma_cbte', 'incoterms_ds'):
                        encabezado[k] = kargs.get(k)

                    self.ws.CrearFactura(**encabezado)

                    for l in range(1, 1000):
                        k = 'codigo%s' % l
                        if k in kargs:
                            codigo = kargs['codigo%s' % l]
                            ds = kargs['descripcion%s' % l]
                            qty = kargs['cantidad%s' % l]
                            umed = kargs['umed%s' % l]
                            precio = kargs['precio%s' % l]
                            importe = kargs['importe%s' % l]
                            bonif = kargs.get('bonif%s' % l)
                            self.ws.AgregarItem(codigo, ds, qty, umed, precio,
                                                importe, bonif)
                        else:
                            break

                    for l in range(1, 1000):
                        k = 'cbte_asoc_%%s_%s' % l
                        if (k % 'tipo') in kargs:
                            tipo = kargs[k % 'tipo']
                            pto_vta = kargs[k % 'pto_vta']
                            nro = kargs[k % 'nro']
                            if id:
                                self.ws.AgregarCmpAsoc(tipo, pto_vta, nro)
                        else:
                            break

                    if DEBUG:
                        self.log('\n'.join([
                            "%s='%s'" % (k, v)
                            for k, v in list(self.ws.factura.items())
                        ]))

                    cae = self.ws.Authorize(kargs['id'])
                    kargs.update({
                        'cae': self.ws.CAE,
                        'fecha_vto': self.ws.Vencimiento,
                        'resultado': self.ws.Resultado,
                        'motivo': self.ws.Obs,
                        'reproceso': self.ws.Reproceso,
                        'err_code': self.ws.ErrCode.encode("latin1"),
                        'err_msg': self.ws.ErrMsg.encode("latin1"),
                    })
                    if self.ws.ErrMsg:
                        gui.alert(self.ws.ErrMsg, "Error AFIP")
                    if self.ws.Obs and self.ws.Obs != '00':
                        gui.alert(self.ws.Obs, "Observación AFIP")

                # actualizo la factura
                for k in ('cae', 'fecha_vto', 'resultado', 'motivo',
                          'reproceso', 'err_code', 'err_msg'):
                    if kargs.get(k):
                        item[k] = kargs[k] if kargs[k] is not None else ""
                self.items[i] = item
                self.log("ID: %s CAE: %s Motivo: %s Reproceso: %s" %
                         (kargs['id'], kargs['cae'], kargs['motivo'],
                          kargs['reproceso']))
                procesadas += 1
                if kargs['resultado'] == "R":
                    rechazadas += 1
                elif kargs['resultado'] == "A":
                    ok += 1
                self.progreso(i)
            self.items = self.items
            self.set_selected_items(selected)
            self.progreso(len(self.items) - 1)
            gui.alert(
                'Proceso finalizado, procesadas %d\n\n'
                'Aceptadas: %d\n'
                'Rechazadas: %d' % (procesadas, ok, rechazadas),
                'Autorización')
            self.grabar()
        except SoapFault as e:
            self.error(e.faultcode, e.faultstring.encode("ascii", "ignore"))
        except KeyError as e:
            self.error("Error", 'Campo obligatorio no encontrado: %s' % e)
        except Exception as e:
            self.error('Excepción', str(e))
        finally:
            if DEBUG:
                if self.webservice == 'wsfev1' and DEBUG:
                    print(self.ws.XmlRequest)
                    print(self.ws.XmlResponse)
Ejemplo n.º 23
0
    def on_btnAutenticar_click(self, event):
        try:
            if self.webservice in ('wsfe', ):
                service = "wsfe"
            elif self.webservice in ('wsfev1', ):
                self.log("Conectando WSFEv1... " + wsfev1_url)
                self.ws.Conectar("",
                                 wsfev1_url,
                                 proxy_dict,
                                 timeout=60,
                                 cacert=CACERT,
                                 wrapper=WRAPPER)
                self.ws.Cuit = cuit
                service = "wsfe"
            elif self.webservice in ('wsfex', 'wsfexv1'):
                self.log("Conectando WSFEXv1... " + wsfexv1_url)
                self.ws.Conectar("",
                                 wsfexv1_url,
                                 proxy_dict,
                                 cacert=CACERT,
                                 wrapper=WRAPPER)
                self.ws.Cuit = cuit
                service = "wsfex"
            else:
                gui.alert('Debe seleccionar servicio web!', 'Advertencia')
                return

            self.log("Creando TRA %s ..." % service)
            ws = wsaa.WSAA()
            tra = ws.CreateTRA(service)
            self.log("Frimando TRA (CMS) con %s %s..." %
                     (str(cert), str(privatekey)))
            cms = ws.SignTRA(str(tra), str(cert), str(privatekey))
            self.log("Llamando a WSAA... " + wsaa_url)
            ws.Conectar("",
                        wsdl=wsaa_url,
                        proxy=proxy_dict,
                        cacert=CACERT,
                        wrapper=WRAPPER)
            self.log("Proxy: %s" % proxy_dict)
            xml = ws.LoginCMS(str(cms))
            self.log("Procesando respuesta...")
            if xml:
                self.token = ws.Token
                self.sign = ws.Sign
            if DEBUG:
                self.log("Token: %s" % self.token)
                self.log("Sign: %s" % self.sign)
            elif self.token and self.sign:
                self.log("Token: %s... OK" % self.token[:10])
                self.log("Sign: %s... OK" % self.sign[:10])
            if self.webservice in ("wsfev1", "wsfexv1"):
                self.ws.Token = self.token
                self.ws.Sign = self.sign

            if xml:
                gui.alert('Autenticado OK!', 'Advertencia')
            else:
                gui.alert('Respuesta: %s' % ws.XmlResponse,
                          'No se pudo autenticar: %s' % ws.Excepcion)
        except SoapFault as e:
            self.error(e.faultcode, e.faultstring.encode("ascii", "ignore"))
        except Exception as e:
            self.error('Excepción', str(e))
Ejemplo n.º 24
0
 def on_field1_keypress(self, evt):
     print "Keypress: ", evt.key
     if evt.key == 13:
         gui.alert(self.component['field1'].value, "hello world!")
Ejemplo n.º 25
0
 def on_menu_ayuda_acercade_click(self, event):
     text = ACERCA_DE
     gui.alert(text, 'Acerca de PyRece Versión %s' % __version__)
Ejemplo n.º 26
0
 def on_menu_ayuda_instructivo_click(self, event):
     text = INSTRUCTIVO
     gui.alert(text, 'Instructivo de PyRece')
Ejemplo n.º 27
0
def delete_entropy():
    try:
        os.remove(reckless_fname)
        gui.alert("Success!", "Your key is deleted")
    except:
        gui.error("Failed to delete the key")
Ejemplo n.º 28
0
	def get_balance(self, evt):
		cash, point = self.__get_balance__()
		gui.alert('cash : %u, point : %u' % (cash, point))
Ejemplo n.º 29
0
def on_field1_keypress(evt):
    print "Keypress: ", evt.key
    if evt.key == 13:
        gui.alert(evt.window['field1'].value, "hello world!")
Ejemplo n.º 30
0
def main():
    args = parse_arguments()

    shown_times = []

    logger.debug("Work plan started")

    while True:
        plan_file, error_message = find_plan_file(args.plan_folder)

        if plan_file is None:
            logger.warning(f"No plan file found")
            playsound(no_plan_alarm)
            gui.alert("Error", error_message)

            sleep(20)
        else:
            time_with_activity = get_activities(plan_file)

            now = datetime.datetime.now()
            from_time, to_time = get_current_time_range(
                time_with_activity.keys(), now)

            if from_time is None:
                logger.warning("No defined activity")

                playsound(no_plan_alarm)
                gui.alert("Error", "No activity is planned")
                sleep(20)

            elif to_time is None:
                logger.warning("No defined activity end")

                playsound(no_plan_alarm)
                gui.alert(
                    "Error",
                    f"Activity {time_with_activity[from_time]} starting at {from_time.strftime('%H:%M')}"
                    f" has no defined end")
                sleep(20)

            elif (to_time - from_time).total_seconds() > 60 * 60:
                logger.warning(
                    "Activity is too long (max duration is one hour)")

                playsound(no_plan_alarm)
                gui.alert(
                    "Error",
                    "Activity is too long (maximally one hour is allowed)")
                sleep(20)

            elif from_time not in shown_times:
                logger.info(
                    f"{from_time.strftime('%H:%M')} - {to_time.strftime('%H:%M')}: {time_with_activity[from_time]}"
                )

                shown_times.append(from_time)
                playsound(alarm)
                gui.alert(
                    f"{from_time.strftime('%H:%M')} - {to_time.strftime('%H:%M')}",
                    time_with_activity[from_time],
                    timeout=None)
                sleep(5)

            else:
                sleep(5)
Ejemplo n.º 31
0
 def error(self, code, text):
     ex = traceback.format_exception(sys.exc_info()[0],
                                     sys.exc_info()[1],
                                     sys.exc_info()[2])
     self.log(''.join(ex))
     gui.alert(text, 'Error %s' % code)
Ejemplo n.º 32
0
def on_mypanel_mybutton_click(etv):
    gui.alert("btn clicked!!!!")
Ejemplo n.º 33
0
                    to.append(bcc)
                self.smtp.sendmail(msg['From'], to, msg.as_string())
            except Exception as e:
                self.error('Excepción', str(e))


if __name__ == '__main__':

    if len(sys.argv) > 1 and not sys.argv[1].startswith("-"):
        CONFIG_FILE = sys.argv[1]
    config = SafeConfigParser()
    config.read(CONFIG_FILE)
    if not len(config.sections()):
        if os.path.exists(CONFIG_FILE):
            gui.alert(
                "Error al cargar archivo de configuración: %s" % CONFIG_FILE,
                "PyRece: Imposible Continuar")
        else:
            gui.alert(
                "No se encuentra archivo de configuración: %s" % CONFIG_FILE,
                "PyRece: Imposible Continuar")
        sys.exit(1)
    cert = config.get('WSAA', 'CERT')
    privatekey = config.get('WSAA', 'PRIVATEKEY')
    cuit = config.get('WSFEv1', 'CUIT')
    if config.has_option('WSFEv1', 'ENTRADA'):
        entrada = config.get('WSFEv1', 'ENTRADA')
    else:
        entrada = ""
    if not os.path.exists(entrada):
        entrada = "facturas.csv"
Ejemplo n.º 34
0
        # (this will allow to drop new controls on the window)
        obj = root
        set_drop_target(root, root, designer, inspector)
        # link the designer (context menu) and toolbox (tool click)
        inspector.set_designer(designer)
        tb.set_default_tlw(root, designer, inspector)
        root.show()

    if root:
        designer.onclose = save 
        designer.filename = filename
        
        frame.Show()
        tb.Show()
        
        wellcome_tip(root.wx_obj)

        f1.Move((root.pos[0] + root.size[0] + 50, 25))
        f2.Move((root.pos[0] + root.size[0] + 50, f1.Size[1] + 60))

        f1.Show()
        f2.Show()

        ##import wx.lib.inspection
        ##wx.lib.inspection.InspectionTool().Show()
        
        app.MainLoop()
    else:
        gui.alert("No window to design!")

Ejemplo n.º 35
0
        # (this will allow to drop new controls on the window)
        obj = root
        set_drop_target(root, root, designer, inspector)
        # link the designer (context menu) and toolbox (tool click)
        inspector.set_designer(designer)
        tb.set_default_tlw(root, designer, inspector)
        root.show()

    if root:
        designer.onclose = save 
        designer.filename = filename
        
        frame.Show()
        tb.Show()
        
        wellcome_tip(root.wx_obj)

        f1.Move((root.pos[0] + root.size[0] + 50, 25))
        f2.Move((root.pos[0] + root.size[0] + 50, f1.Size[1] + 60))

        f1.Show()
        f2.Show()

        ##import wx.lib.inspection
        ##wx.lib.inspection.InspectionTool().Show()
        
        app.MainLoop()
    else:
        gui.alert("No window to design!")

Ejemplo n.º 36
0
    def on_btnAutorizarLote_click(self, event):
        self.verifica_ws()
        if not self.items: return
        try:
            #getcontext().prec = 2
            ok = 0
            rechazadas = 0
            cols = self.cols
            items = []
            self.progreso(0)
            cbt_desde = cbt_hasta = None
            datos = {
                'tipo_cbte': None,
                'punto_vta': None,
                'fecha_cbte': None,
                'fecha_venc_pago': None,
                'fecha_cbte': None,
                'fecha_venc_pago': None,
                'fecha_serv_desde': None,
                'fecha_serv_hasta': None,
                'moneda_id': None,
                'moneda_ctz': None,
                'id': None,
            }
            importes = {
                'imp_total': Decimal(0),
                'imp_tot_conc': Decimal(0),
                'imp_neto': Decimal(0),
                'imp_iva': Decimal(0),
                'imp_op_ex': Decimal(0),
                'imp_trib': Decimal(0),
            }
            for l in range(1, 5):
                k = 'iva_%%s_%s' % l
                datos[k % 'id'] = None
                importes[k % 'base_imp'] = Decimal(0)
                importes[k % 'importe'] = Decimal(0)

            for l in range(1, 10):
                k = 'tributo_%%s_%s' % l
                datos[k % 'id'] = None
                datos[k % 'desc'] = None
                importes[k % 'base_imp'] = Decimal(0)
                datos[k % 'alic'] = None
                importes[k % 'importe'] = Decimal(0)

            for i, item in self.get_selected_items():
                if cbt_desde is None or int(item['cbt_numero']) < cbt_desde:
                    cbt_desde = int(item['cbt_numero'])
                if cbt_hasta is None or int(item['cbt_numero']) > cbt_hasta:
                    cbt_hasta = int(item['cbt_numero'])
                for key in item:
                    if key in datos:
                        if datos[key] is None:
                            datos[key] = item[key]
                        elif datos[key] != item[key]:
                            raise RuntimeError(
                                "%s tiene valores distintos en el lote!" % key)
                    if key in importes and item[key]:
                        importes[key] = importes[key] + Decimal(
                            "%.2f" % float(str(item[key].replace(",", "."))))

            kargs = {'cbt_desde': cbt_desde, 'cbt_hasta': cbt_hasta}
            kargs.update({'tipo_doc': 99, 'nro_doc': '0'})
            kargs.update(datos)
            kargs.update(importes)
            if kargs['fecha_serv_desde'] and kargs['fecha_serv_hasta']:
                kargs['presta_serv'] = 1
                kargs['concepto'] = 2
            else:
                kargs['presta_serv'] = 0
                kargs['concepto'] = 1
                del kargs['fecha_serv_desde']
                del kargs['fecha_serv_hasta']

            for key, val in list(importes.items()):
                importes[key] = val.quantize(Decimal('.01'),
                                             rounding=ROUND_DOWN)

            if 'id' not in kargs or kargs['id'] == "":
                id = int(kargs['cbt_desde'])
                id += (int(kargs['tipo_cbte']) * 10**4 +
                       int(kargs['punto_vta'])) * 10**8
                kargs['id'] = id

            if DEBUG:
                self.log('\n'.join(
                    ["%s='%s'" % (k, v) for k, v in list(kargs.items())]))
            if '--test' in sys.argv:
                kargs['cbt_desde'] = 777
                kargs['fecha_cbte'] = '20110802'
                kargs['fecha_venc_pago'] = '20110831'

            if gui.confirm(
                    "Confirma Lote:\n"
                    "Tipo: %(tipo_cbte)s Desde: %(cbt_desde)s Hasta %(cbt_hasta)s\n"
                    "Neto: %(imp_neto)s IVA: %(imp_iva)s Trib.: %(imp_trib)s Total: %(imp_total)s"
                    % kargs, "Autorizar lote:"):

                if self.webservice == 'wsfev1':
                    encabezado = {}
                    for k in ('concepto', 'tipo_doc', 'nro_doc', 'tipo_cbte',
                              'punto_vta', 'cbt_desde', 'cbt_hasta',
                              'imp_total', 'imp_tot_conc', 'imp_neto',
                              'imp_iva', 'imp_trib', 'imp_op_ex', 'fecha_cbte',
                              'moneda_id', 'moneda_ctz'):
                        encabezado[k] = kargs[k]

                    for k in ('fecha_venc_pago', 'fecha_serv_desde',
                              'fecha_serv_hasta'):
                        if k in kargs:
                            encabezado[k] = kargs.get(k)

                    self.ws.CrearFactura(**encabezado)
                    for l in range(1, 1000):
                        k = 'iva_%%s_%s' % l
                        if (k % 'id') in kargs:
                            id = kargs[k % 'id']
                            base_imp = kargs[k % 'base_imp']
                            importe = kargs[k % 'importe']
                            if id:
                                self.ws.AgregarIva(id, base_imp, importe)
                        else:
                            break

                    for l in range(1, 1000):
                        k = 'tributo_%%s_%s' % l
                        if (k % 'id') in kargs:
                            id = kargs[k % 'id']
                            desc = kargs[k % 'desc']
                            base_imp = kargs[k % 'base_imp']
                            alic = kargs[k % 'alic']
                            importe = kargs[k % 'importe']
                            if id:
                                self.ws.AgregarTributo(id, desc, base_imp,
                                                       alic, importe)
                        else:
                            break

                    if DEBUG:
                        self.log('\n'.join([
                            "%s='%s'" % (k, v)
                            for k, v in list(self.ws.factura.items())
                        ]))

                    cae = self.ws.CAESolicitar()
                    kargs.update({
                        'cae': self.ws.CAE,
                        'fecha_vto': self.ws.Vencimiento,
                        'resultado': self.ws.Resultado,
                        'motivo': self.ws.Obs,
                        'reproceso': self.ws.Reproceso,
                        'err_code': self.ws.ErrCode.encode("latin1"),
                        'err_msg': self.ws.ErrMsg.encode("latin1"),
                    })
                    if self.ws.ErrMsg:
                        gui.alert(self.ws.ErrMsg, "Error AFIP")
                    if self.ws.Obs and self.ws.Obs != '00':
                        gui.alert(self.ws.Obs, "Observación AFIP")

                for i, item in self.get_selected_items():
                    for key in ('id', 'cae', 'fecha_vto', 'resultado',
                                'motivo', 'reproceso', 'err_code', 'err_msg'):
                        item[
                            key] = kargs[key] if kargs[key] is not None else ""
                        self.items[i] = item

                self.log("ID: %s CAE: %s Motivo: %s Reproceso: %s" %
                         (kargs['id'], kargs['cae'], kargs['motivo'],
                          kargs['reproceso']))
                if kargs['resultado'] == "R":
                    rechazadas += 1
                elif kargs['resultado'] == "A":
                    ok += 1

                self.items = self.items  # refrescar, ver de corregir
                self.progreso(len(self.items))
                gui.alert(
                    'Proceso finalizado OK!\n\nAceptadas: %d\nRechazadas: %d' %
                    (ok, rechazadas), 'Autorización')
                self.grabar()
        except SoapFault as e:
            self.log(self.client.xml_request)
            self.log(self.client.xml_response)
            self.error(e.faultcode, e.faultstring.encode("ascii", "ignore"))
        except Exception as e:
            self.error('Excepción', str(e))
Ejemplo n.º 37
0
def on_field1_keypress(evt):
    print "Keypress: ", evt.key
    if evt.key == 13:
        gui.alert(evt.window["field1"].value, "hello world!")
Ejemplo n.º 38
0
def qr_animated(indx, callback):
    gui.alert("Animated QR: %s/%s" % (indx[0], indx[1]),
              "Proceed to scanning code No. %s" % str(indx[0] + 1), callback)
Ejemplo n.º 39
0
def sys_mes(mess):
    import wx, sys
    gui.alert(mess)
def doOrderScrape(evt):
    if not mywin['txtFivUsername'].value or not mywin['txtFivPassword'].value:
        gui.alert("Please enter username and password")
        return
    if not os.path.isdir(mywin['txtOutputPath'].value):
        os.makedirs(mywin['txtOutputPath'].value)
    config.outputPath = mywin['txtOutputPath'].value
    config.outputAttachmentsPath = config.outputPath + "Attachments/"
    if not os.path.isdir(config.outputAttachmentsPath):
        os.makedirs(config.outputAttachmentsPath)
    config.FivUsername = mywin['txtFivUsername'].value
    config.FivPassword = mywin['txtFivPassword'].value

    try:
        gui.alert("Starting Order Scrape. \nPlease do not touch your keyboard or mouse.")
        mywin.minimized = True

        ret_value = FiverrOrderScrape.main()
        mywin.minimized = False

        if ret_value == 1:
            gui.alert("Order Scraping Done.")
        elif ret_value == 101:
            gui.alert("There were no orders to scrape.")
        elif ret_value == 102:
            gui.alert("There were no new orders to scrape.")
        else:
            gui.alert("There were some problems with scraping. Please report to developer.")


    except:
        logger.exception(sys.exc_info())
    finally:
        mywin.minimized = False
Ejemplo n.º 41
0
 def on_field1_keypress(self, evt):
     print "Keypress: ", evt.key
     if evt.key == 13:
         gui.alert(self.component['field1'].value, "hello world!")
Ejemplo n.º 42
0
def on_mypanel_mybutton_click(etv):
    gui.alert("btn clicked!!!!")
Ejemplo n.º 43
0
def logicloop(loopy):
    try:
        theDevice = ArduinoUsbDevice(idVendor=0x16c0, idProduct=0x05df)

    except:
        gui.alert(
            u'?? ???? ?? ???? ?????? ????? ??? ????? ????? \n ??? ?? ????? ????? ?? ????? ????'
        )

    try:

        f = open('data.txt', 'r')
        a = pickle.load(f)
        #print a, "Bombs So Far At:", time.ctime()

    except:
        a = 0

    b = 0
    f = open('pase.txt', 'w')
    pickle.dump(b, f)
    f.close()

    startime = time.time()
    f = open('startime.txt', 'w')
    pickle.dump(startime, f)
    f.close()

    c = 0
    f = open('shiftpase.txt', 'w')
    pickle.dump(c, f)
    f.close()

    shifttime = time.time()
    f = open('shifttime.txt', 'w')
    pickle.dump(shifttime, f)
    f.close()

    while True:
        lastChar = chr(theDevice.read())
        sys.stdout.flush()

        while (lastChar == "0"):

            lastChar = chr(theDevice.read())

            if (lastChar == "1"):
                winsound.PlaySound('bomb.wav', winsound.SND_FILENAME)

                f = open('data.txt', 'r')
                a = pickle.load(f)

                a = a + 1
                #print a, "Bombs So Far At:", time.ctime()

                ddelay = 0

                bombnum = a
                mywin['count'].left = '860'
                if (9 < a < 100):
                    mywin['count'].left = '790'
                if (99 < a < 1000):
                    mywin['count'].left = '720'
                if (999 < a):
                    mywin['count'].left = '660'
                mywin['count'].size = (0, 0)
                mywin['count'].text = u'%s' % (bombnum)
                mywin['count'].transparent = False
                mywin['count'].transparent = True
                mywin['count'].bgcolor = 'transparent'

                f = open('data.txt', 'w')
                pickle.dump(a, f)
                f.close()
                lastChar = chr(theDevice.read())

                mywin['statusbar'].text = u"???? ?????? ?????? ????: %s" % (
                    time.ctime())

                f = open('pase.txt', 'r')
                b = pickle.load(f)
                b = b + 1

                f = open('startime.txt', 'r')
                startime = pickle.load(f)

                pase = time.time()
                avg = (pase - startime)

                #print "time passed: ", avg
                avgpase = (b / avg) * 3600
                #print b
                #print "bomb pase: ", avgpase

                avgpase = int(avgpase)
                bombpase = avgpase
                print bombpase
                if (bombpase < 1):
                    mywin['bombpase'].fgcolor = u'#FFFFFF'
                    mywin['bombpase'].left = '800'
                    mywin['bombpase'].top = '500'
                    mywin['bombpase'].size = (0, 0)
                    mywin['bombpase'].text = u'--'
                    mywin['bombpase'].transparent = False
                    mywin['bombpase'].transparent = True
                    mywin['bombpase'].bgcolor = 'transparent'
                if (1 <= bombpase < 10):
                    mywin['bombpase'].fgcolor = u'#FFFFFF'
                    mywin['bombpase'].left = '800'
                    mywin['bombpase'].size = (0, 0)
                    mywin['bombpase'].text = u'%s' % (bombpase)
                    mywin['bombpase'].transparent = False
                    mywin['bombpase'].transparent = True
                    mywin['bombpase'].bgcolor = 'transparent'
                if (10 <= bombpase <= 33):
                    mywin['bombpase'].fgcolor = u'#FFFFFF'
                    mywin['bombpase'].left = '775'
                    mywin['bombpase'].top = '480'
                    mywin['bombpase'].size = (0, 0)
                    mywin['bombpase'].text = u'%s' % (bombpase)
                    mywin['bombpase'].transparent = False
                    mywin['bombpase'].transparent = True
                    mywin['bombpase'].bgcolor = 'transparent'
                if (34 <= bombpase <= 99):
                    mywin['bombpase'].fgcolor = u'#FFFFFF'
                    mywin['bombpase'].left = '775'
                    mywin['bombpase'].top = '480'
                    mywin['bombpase'].size = (0, 0)
                    mywin['bombpase'].text = u'%s' % (bombpase)
                    mywin['bombpase'].transparent = False
                    mywin['bombpase'].transparent = True
                    mywin['bombpase'].bgcolor = 'transparent'
                if (99 < bombpase):
                    mywin['bombpase'].fgcolor = u'#FFFFFF'
                    mywin['bombpase'].left = '780'
                    mywin['bombpase'].top = '500'
                    mywin['bombpase'].size = (0, 0)
                    mywin['bombpase'].text = u'--'
                    mywin['bombpase'].transparent = False
                    mywin['bombpase'].transparent = True
                    mywin['bombpase'].bgcolor = 'transparent'
                f = open('pase.txt', 'w')
                pickle.dump(b, f)
                f.close()

                f = open('shiftpase.txt', 'r')
                c = pickle.load(f)
                c = c + 1

                f = open('shifttime.txt', 'r')
                shifttime = pickle.load(f)

                shiftpase = time.time()
                shiftavg = (shiftpase - shifttime)

                #print "time passed: ", shiftavg
                shiftavgpase = (c / shiftavg) * 3600
                #print c
                #print "bomb pase: ", shiftavgpase

                shiftavgpase = int(shiftavgpase)
                shiftbombpase = shiftavgpase
                print shiftbombpase
                if (shiftbombpase < 1):
                    mywin['shiftbombpase'].fgcolor = u'#FFFFFF'
                    mywin['shiftbombpase'].left = '800'
                    mywin['shiftbombpase'].top = '700'
                    mywin['shiftbombpase'].size = (0, 0)
                    mywin['shiftbombpase'].text = u'--'
                    mywin['shiftbombpase'].transparent = False
                    mywin['shiftbombpase'].transparent = True
                    mywin['shiftbombpase'].bgcolor = 'transparent'
                if (1 <= shiftbombpase < 10):
                    mywin['shiftbombpase'].fgcolor = u'#FFFFFF'
                    mywin['shiftbombpase'].left = '800'
                    mywin['shiftbombpase'].size = (0, 0)
                    mywin['shiftbombpase'].text = u'%s' % (shiftbombpase)
                    mywin['shiftbombpase'].transparent = False
                    mywin['shiftbombpase'].transparent = True
                    mywin['shiftbombpase'].bgcolor = 'transparent'
                if (10 <= shiftbombpase <= 33):
                    mywin['shiftbombpase'].fgcolor = u'#FFFFFF'
                    mywin['shiftbombpase'].left = '775'
                    mywin['shiftbombpase'].top = '680'
                    mywin['shiftbombpase'].size = (0, 0)
                    mywin['shiftbombpase'].text = u'%s' % (shiftbombpase)
                    mywin['shiftbombpase'].transparent = False
                    mywin['shiftbombpase'].transparent = True
                    mywin['shiftbombpase'].bgcolor = 'transparent'
                if (34 <= shiftbombpase <= 99):
                    mywin['shiftbombpase'].fgcolor = u'#FFFFFF'
                    mywin['shiftbombpase'].left = '775'
                    mywin['shiftbombpase'].top = '680'
                    mywin['shiftbombpase'].size = (0, 0)
                    mywin['shiftbombpase'].text = u'%s' % (shiftbombpase)
                    mywin['shiftbombpase'].transparent = False
                    mywin['shiftbombpase'].transparent = True
                    mywin['shiftbombpase'].bgcolor = 'transparent'
                if (99 < shiftbombpase):
                    mywin['shiftbombpase'].fgcolor = u'#FFFFFF'
                    mywin['shiftbombpase'].left = '780'
                    mywin['shiftbombpase'].top = '700'
                    mywin['shiftbombpase'].size = (0, 0)
                    mywin['shiftbombpase'].text = u'--'
                    mywin['shiftbombpase'].transparent = False
                    mywin['shiftbombpase'].transparent = True
                    mywin['shiftbombpase'].bgcolor = 'transparent'
                f = open('shiftpase.txt', 'w')
                pickle.dump(c, f)
                f.close()

                while (ddelay < 50000000):
                    ddelay = ddelay + 1

                break