def _export(self, exportInfo, decorations): size = self.frame.animationPanel.GetSize() if self.temporalMode == TemporalMode.TEMPORAL: timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps() frameCount = len(timeLabels) else: frameCount = self.animationData[ 0].mapCount # should be the same for all animWinSize = [] animWinPos = [] animWinIndex = [] legends = [anim.legendCmd for anim in self.animationData] # determine position and sizes of bitmaps for i, (win, anim) in enumerate(zip(self.mapwindows, self.animations)): if anim.IsActive(): pos = win.GetPosition() animWinPos.append(pos) animWinSize.append(win.GetSize()) animWinIndex.append(i) images = [] busy = wx.BusyInfo( _("Preparing export, please wait..."), parent=self.frame) wx.GetApp().Yield() lastBitmaps = {} fgcolor = UserSettings.Get( group='animation', key='font', subkey='fgcolor') bgcolor = UserSettings.Get( group='animation', key='font', subkey='bgcolor') for frameIndex in range(frameCount): image = EmptyImage(*size) image.Replace(0, 0, 0, 255, 255, 255) # collect bitmaps of all windows and paste them into the one for i in animWinIndex: frameId = self.animations[i].GetFrame(frameIndex) if not UserSettings.Get(group='animation', key='temporal', subkey=['nodata', 'enable']): if frameId is not None: bitmap = self.bitmapProvider.GetBitmap(frameId) lastBitmaps[i] = bitmap else: if i not in lastBitmaps: lastBitmaps[i] = wx.NullBitmap() else: bitmap = self.bitmapProvider.GetBitmap(frameId) lastBitmaps[i] = bitmap im = ImageFromBitmap(lastBitmaps[i]) # add legend if used legend = legends[i] if legend: legendBitmap = self.bitmapProvider.LoadOverlay(legend) x, y = self.mapwindows[i].GetOverlayPos() legImage = ImageFromBitmap(legendBitmap) # not so nice result, can we handle the transparency # otherwise? legImage.ConvertAlphaToMask() im.Paste(legImage, x, y) if im.GetSize() != animWinSize[i]: im.Rescale(*animWinSize[i]) image.Paste(im, *animWinPos[i]) # paste decorations for decoration in decorations: # add image x = decoration['pos'][0] / 100. * size[0] y = decoration['pos'][1] / 100. * size[1] if decoration['name'] == 'image': decImage = wx.Image(decoration['file']) elif decoration['name'] == 'time': timeLabel = timeLabels[frameIndex] if timeLabel[1]: # interval text = _("%(from)s %(dash)s %(to)s") % { 'from': timeLabel[0], 'dash': u"\u2013", 'to': timeLabel[1]} else: if self.temporalManager.GetTemporalType() == TemporalType.ABSOLUTE: text = timeLabel[0] else: text = _("%(start)s %(unit)s") % \ {'start': timeLabel[0], 'unit': timeLabel[2]} decImage = RenderText( text, decoration['font'], bgcolor, fgcolor).ConvertToImage() elif decoration['name'] == 'text': text = decoration['text'] decImage = RenderText( text, decoration['font'], bgcolor, fgcolor).ConvertToImage() image.Paste(decImage, x, y) images.append(image) del busy # export pilImages = [WxImageToPil(image) for image in images] busy = wx.BusyInfo(_("Exporting animation, please wait..."), parent=self.frame) wx.GetApp().Yield() try: if exportInfo['method'] == 'sequence': filename = os.path.join( exportInfo['directory'], exportInfo['prefix'] + '.' + exportInfo['format'].lower()) writeIms(filename=filename, images=pilImages) elif exportInfo['method'] == 'gif': writeGif(filename=exportInfo['file'], images=pilImages, duration=self.timeTick / float(1000), repeat=True) elif exportInfo['method'] == 'swf': writeSwf(filename=exportInfo['file'], images=pilImages, duration=self.timeTick / float(1000), repeat=True) elif exportInfo['method'] == 'avi': writeAvi(filename=exportInfo['file'], images=pilImages, duration=self.timeTick / float(1000), encoding=exportInfo['encoding'], inputOptions=exportInfo['options']) except Exception as e: del busy GError(parent=self.frame, message=str(e)) return del busy
def _do_lm_acquire(self): ### if self._model.slice_offsets_microns is None: print( 'There were no earlier LM acquisitions. POI position prediction is based on slice contours only.' ) # Calculate the physical displacements on the sample required for moving between the points of interest. overview_image_pixelsize_in_microns = 1000.0 / self._model.overview_image_pixels_per_mm self._model.slice_offsets_microns = tools.physical_point_of_interest_offsets_in_microns( self._model.all_points_of_interest, overview_image_pixelsize_in_microns) print('Rough offset from slice polygons (in microns): ' + repr(self._model.slice_offsets_microns)) # Obsolete comment: # For each LM image acquisition we start *new* offset corrections. # This ensures that if we change the POI we also start with a blank slate for offset corrections, # otherwise we would incorrectly combine offset corrections for one POI with those for another # (with possibly a different number of slices) # FIXME: clean up this code + PointOfInterestPanel. When changing the POI, or the number of POIs, the position corrections # should be discarded, but the user needs to be made aware of this in that panel. self._model.all_offsets_microns = [{ 'name': 'Slice mapping', 'parameters': {}, 'offsets': self._model.slice_offsets_microns }] self._model.combined_offsets_microns = copy.deepcopy( self._model.slice_offsets_microns) else: print( 'There were earlier LM acquisitions. Their position corrections will be taken into account for the current acquisition.' ) ### # Move the stage to the first point of interest. # The stage may not currently be positioned there because, # for example, we may have moved the stage while building the focus map. self._move_stage_to_first_point_of_interest() # Remember current stage position so we can return to it after imaging. orig_stage_pos = secom_tools.get_absolute_stage_position() # Print an overview of the position corrections. print( 'The following position corrections will be taken into account during LM image acquisition:' ) tools.show_offsets_table(self._model.all_offsets_microns, self._model.combined_offsets_microns) # Now acquire an LM image at the point of interest location in each slice. wait = wx.BusyInfo("Acquiring LM images...") secom_tools.acquire_lm_microscope_images( self._model.combined_offsets_microns, self._model.lm_stabilization_time_secs, self._model.delay_between_LM_image_acquisition_secs, self._model.odemis_cli, self._model.lm_images_output_folder, self._model.lm_images_prefix, self._model.focus_map if self._model.lm_use_focus_map else None) del wait # Perform image registration on the acquired stack of LM images info_description = 'LM {} Registration'.format( self._model.lm_registration_params['method']) self._do_registration( 'LM', self._model.fiji_path, self._model.registration_script, self._model.lm_registration_params, self._model.lm_images_output_folder, self._model.lm_images_prefix, self._model.lm_registration_output_folder, len(self._model.all_points_of_interest), self._model.lm_image_size, self._model.lm_registration_images_pixels_per_mm, info_description, {} ) # IMPROVEME? perhaps a nice touch would be to store the LM lens that was used. Can we query that via odemis-cli perhaps? # Move stage back to initial position print('Moving stage back to position at start of LM image acquisition') secom_tools.set_absolute_stage_position(orig_stage_pos) # Enable/disable menu entries self._em_image_acquisition_item.Enable(True) self._show_offsets_table_item.Enable(True)
def MAJ(self, mode="saisis", date_debut=None, date_fin=None, listeActivites=[], filtres=[]): self.mode = mode self.date_debut = date_debut self.date_fin = date_fin self.listeActivites = listeActivites self.filtres = filtres # Affiche d'une fenêtre d'attente message = _(u"Calcul des données en cours... Veuillez patienter...") dlgAttente = wx.BusyInfo(message, None) if 'phoenix' not in wx.PlatformInfo: wx.Yield() # Importation des données dictResultats, listeModes = self.Importation() self.dictImpression = { "entete": [], "contenu": [], "total": [], "coloration": [] } # Tri des modes par ordre alphabétique listeModesAlpha = [] for IDmode in listeModes: if IDmode in self.dictModes: label = self.dictModes[IDmode]["nom"] else: label = _(u"Mode inconnu") listeModesAlpha.append((label, IDmode)) listeModesAlpha.sort() # Initialisation du CTRL self.RAZ() dictColonnes = self.CreationColonnes(listeModesAlpha) self.root = self.AddRoot(_(u"Racine")) # Branches Activités listeLabels = [] for IDactivite, dictActivite in dictResultats.items(): if IDactivite in self.dictActivites: nomActivite = self.dictActivites[IDactivite]["nom"] else: if IDactivite == 99999: nomActivite = _(u"Cotisations") elif IDactivite == 88888: nomActivite = _(u"Avoirs") else: nomActivite = _(u"Activité inconnue") listeLabels.append((nomActivite, IDactivite, dictActivite)) listeLabels.sort() for nomActivite, IDactivite, dictActivite in listeLabels: niveauActivite = self.AppendItem(self.root, nomActivite) #self.SetItemBold(niveauActivite) impressionLigne = [ nomActivite, ] # Total par mode dictTotal = {} for labelPrestation, dictPrestation in dictActivite.items(): for IDmode, montant in dictPrestation.items(): if (IDmode in dictTotal) == False: dictTotal[IDmode] = 0.0 dictTotal[IDmode] += montant totalLigne = 0.0 for labelMode, IDmode in listeModesAlpha: if IDmode in dictTotal: montant = dictTotal[IDmode] texte = u"%.2f %s" % (montant, SYMBOLE) self.SetItemText(niveauActivite, texte, dictColonnes[IDmode]) totalLigne += montant impressionLigne.append(texte) else: impressionLigne.append("") # Total Ligne Activité texte = u"%.2f %s" % (totalLigne, SYMBOLE) self.SetItemText(niveauActivite, texte, dictColonnes["total"]) impressionLigne.append(texte) self.dictImpression["contenu"].append(impressionLigne) # Branches Prestations listePrestations = [] for labelPrestation, dictPrestation in dictActivite.items(): listePrestations.append((labelPrestation, dictPrestation)) listePrestations.sort() if self.affichage_details == True: self.dictImpression["coloration"].append( len(self.dictImpression["contenu"]) - 1) for labelPrestation, dictPrestation in listePrestations: niveauPrestation = self.AppendItem(niveauActivite, labelPrestation) self.SetItemFont( niveauPrestation, wx.Font(7, wx.SWISS, wx.NORMAL, wx.NORMAL)) self.SetItemTextColour(niveauPrestation, wx.Colour(160, 160, 160)) impressionLigne = [ labelPrestation, ] # Colonnes Modes totalLigne = 0.0 for labelMode, IDmode in listeModesAlpha: if IDmode in dictPrestation: montant = dictPrestation[IDmode] texte = u"%.2f %s" % (montant, SYMBOLE) self.SetItemText(niveauPrestation, texte, dictColonnes[IDmode]) totalLigne += montant impressionLigne.append(texte) else: impressionLigne.append("") # Total ligne Prestation texte = u"%.2f %s" % (totalLigne, SYMBOLE) self.SetItemText(niveauPrestation, texte, dictColonnes["total"]) impressionLigne.append(texte) self.dictImpression["contenu"].append(impressionLigne) # ------------ Ligne Total -------------- niveauTotal = self.AppendItem(self.root, _(u"Total")) self.SetItemBackgroundColour(niveauTotal, wx.Colour(150, 150, 150)) self.SetItemTextColour(niveauTotal, wx.Colour(255, 255, 255)) impressionLigne = [ _(u"Total"), ] totauxColonnes = {} for IDactivite, dictActivite in dictResultats.items(): for labelPrestation, dictPrestation in dictActivite.items(): for IDmode, montant in dictPrestation.items(): if (IDmode in totauxColonnes) == False: totauxColonnes[IDmode] = 0.0 totauxColonnes[IDmode] += montant totalLigne = 0.0 for labelMode, IDmode in listeModesAlpha: if IDmode in totauxColonnes: montant = totauxColonnes[IDmode] texte = u"%.2f %s" % (montant, SYMBOLE) self.SetItemText(niveauTotal, texte, dictColonnes[IDmode]) totalLigne += montant impressionLigne.append(texte) else: impressionLigne.append("") # Total ligne Prestation texte = u"%.2f %s" % (totalLigne, SYMBOLE) self.SetItemText(niveauTotal, texte, dictColonnes["total"]) impressionLigne.append(texte) self.dictImpression["total"].append(impressionLigne) self.ExpandAllChildren(self.root) del dlgAttente
def GetDonneesImpression(self, listeCotisations=[]): """ Impression des factures """ dlgAttente = wx.BusyInfo(_(u"Recherche des données..."), None) wx.Yield() # Récupère les données de la facture if len(listeCotisations) == 0 : conditions = "()" elif len(listeCotisations) == 1 : conditions = "(%d)" % listeCotisations[0] else : conditions = str(tuple(listeCotisations)) DB = GestionDB.DB() # Récupération des activités req = """SELECT IDactivite, nom, abrege FROM activites ORDER BY date_fin DESC;""" DB.ExecuterReq(req) listeTemp = DB.ResultatReq() dictActivites = {} for IDactivite, nom, abrege in listeTemp : dictTemp = {"IDactivite":IDactivite, "nom":nom, "abrege":abrege} dictActivites[IDactivite] = dictTemp # Récupère les prestations dictFacturation = {} req = """SELECT IDcotisation, SUM(montant) FROM prestations LEFT JOIN cotisations ON cotisations.IDprestation = prestations.IDprestation WHERE cotisations.IDcotisation IN %s GROUP BY cotisations.IDcotisation;""" % conditions DB.ExecuterReq(req) listePrestations = DB.ResultatReq() for IDcotisation, montant in listePrestations : dictFacturation[IDcotisation] = {"montant":montant, "ventilation":0.0, "dateReglement":None,"modeReglement":None} # Récupère la ventilation req = """SELECT IDcotisation, SUM(ventilation.montant), MIN(reglements.date), MIN(modes_reglements.label) FROM ventilation LEFT JOIN prestations ON prestations.IDprestation = ventilation.IDprestation LEFT JOIN cotisations ON cotisations.IDprestation = ventilation.IDprestation LEFT JOIN reglements ON reglements.IDreglement = ventilation.IDreglement LEFT JOIN modes_reglements ON modes_reglements.IDmode = reglements.IDmode WHERE cotisations.IDcotisation IN %s GROUP BY cotisations.IDcotisation;""" % conditions DB.ExecuterReq(req) listeVentilations = DB.ResultatReq() for IDcotisation, ventilation, dateReglement, modeReglement in listeVentilations : if dictFacturation.has_key(IDcotisation) : dictFacturation[IDcotisation]["ventilation"] = ventilation dictFacturation[IDcotisation]["dateReglement"] = dateReglement dictFacturation[IDcotisation]["modeReglement"] = modeReglement # Recherche les cotisations req = """ SELECT cotisations.IDcotisation, cotisations.IDfamille, cotisations.IDindividu, cotisations.IDtype_cotisation, cotisations.IDunite_cotisation, cotisations.date_saisie, cotisations.IDutilisateur, cotisations.date_creation_carte, cotisations.numero, cotisations.IDdepot_cotisation, cotisations.date_debut, cotisations.date_fin, cotisations.IDprestation, types_cotisations.nom, types_cotisations.type, types_cotisations.carte, unites_cotisations.nom, comptes_payeurs.IDcompte_payeur, cotisations.observations, cotisations.activites FROM cotisations LEFT JOIN types_cotisations ON types_cotisations.IDtype_cotisation = cotisations.IDtype_cotisation LEFT JOIN unites_cotisations ON unites_cotisations.IDunite_cotisation = cotisations.IDunite_cotisation LEFT JOIN comptes_payeurs ON comptes_payeurs.IDfamille = cotisations.IDfamille WHERE cotisations.IDcotisation IN %s ORDER BY cotisations.date_saisie ;""" % conditions DB.ExecuterReq(req) listeDonnees = DB.ResultatReq() DB.Close() if len(listeDonnees) == 0 : del dlgAttente return False # Création des dictRappels dictDonnees = {} dictChampsFusion = {} for item in listeDonnees : IDcotisation = item[0] IDfamille = item[1] IDindividu = item[2] IDtype_cotisation = item[3] IDunite_cotisation = item[4] date_saisie = UTILS_Dates.DateEngEnDateDD(item[5]) IDutilisateur = item[6] date_creation_carte = item[7] numero = item[8] IDdepot_cotisation = item[9] date_debut = UTILS_Dates.DateEngEnDateDD(item[10]) date_fin = UTILS_Dates.DateEngEnDateDD(item[11]) IDprestation = item[12] nomTypeCotisation = item[13] typeTypeCotisation = item[14] typeHasCarte = item[15] nomUniteCotisation = item[16] IDcompte_payeur = item[17] observations = item[18] activites = item[19] if activites == None : activites = "" # Activités texte = "" if len(activites) > 0 : listeTemp = [] listeIDactivites = UTILS_Divers.ConvertChaineEnListe(activites) for IDactivite in listeIDactivites : if dictActivites.has_key(IDactivite) : nomActivite = dictActivites[IDactivite]["nom"] listeTemp.append(nomActivite) if len(listeTemp) > 0 : texte = ", ".join(listeTemp) activites = texte nomCotisation = u"%s - %s" % (nomTypeCotisation, nomUniteCotisation) # Type if typeTypeCotisation == "famille" : typeStr = _(u"Cotisation familiale") else: typeStr = _(u"Cotisation individuelle") # Dépôt if IDdepot_cotisation == None : depotStr = _(u"Non déposée") else: depotStr = _(u"Dépôt n°%d") % IDdepot_cotisation # Nom des titulaires de famille beneficiaires = "" rue = "" cp = "" ville = "" if IDfamille != None : beneficiaires = self.dictTitulaires[IDfamille]["titulairesAvecCivilite"] rue = self.dictTitulaires[IDfamille]["adresse"]["rue"] cp = self.dictTitulaires[IDfamille]["adresse"]["cp"] ville = self.dictTitulaires[IDfamille]["adresse"]["ville"] if IDindividu != None and self.dictIndividus.has_key(IDindividu) : beneficiaires = self.dictIndividus[IDindividu]["nom_complet"] rue = self.dictIndividus[IDindividu]["rue"] cp = self.dictIndividus[IDindividu]["cp"] ville = self.dictIndividus[IDindividu]["ville"] # Famille if IDfamille != None : nomTitulaires = self.dictTitulaires[IDfamille]["titulairesAvecCivilite"] famille_rue = self.dictTitulaires[IDfamille]["adresse"]["rue"] famille_cp = self.dictTitulaires[IDfamille]["adresse"]["cp"] famille_ville = self.dictTitulaires[IDfamille]["adresse"]["ville"] else : nomTitulaires = "Famille inconnue" famille_rue = "" famille_cp = "" famille_ville = "" # Facturation montant = 0.0 ventilation = 0.0 dateReglement = None modeReglement = None if dictFacturation.has_key(IDcotisation): montant = dictFacturation[IDcotisation]["montant"] ventilation = dictFacturation[IDcotisation]["ventilation"] dateReglement = dictFacturation[IDcotisation]["dateReglement"] modeReglement = dictFacturation[IDcotisation]["modeReglement"] solde = float(FloatToDecimal(montant) - FloatToDecimal(ventilation)) montantStr = u"%.02f %s" % (montant, SYMBOLE) regleStr = u"%.02f %s" % (ventilation, SYMBOLE) soldeStr = u"%.02f %s" % (solde, SYMBOLE) montantStrLettres = UTILS_Conversion.trad(montant, MONNAIE_SINGULIER, MONNAIE_DIVISION) regleStrLettres = UTILS_Conversion.trad(ventilation, MONNAIE_SINGULIER, MONNAIE_DIVISION) soldeStrLettres = UTILS_Conversion.trad(solde, MONNAIE_SINGULIER, MONNAIE_DIVISION) # Mémorisation des données dictDonnee = { "select" : True, "{IDCOTISATION}" : str(IDcotisation), "{IDTYPE_COTISATION}" : str(IDtype_cotisation), "{IDUNITE_COTISATION}" : str(IDunite_cotisation), "{DATE_SAISIE}" : UTILS_Dates.DateDDEnFr(date_saisie), "{IDUTILISATEUR}" : str(IDutilisateur), "{DATE_CREATION_CARTE}" : UTILS_Dates.DateDDEnFr(date_creation_carte), "{NUMERO_CARTE}" : numero, "{IDDEPOT_COTISATION}" : str(IDdepot_cotisation), "{DATE_DEBUT}" : UTILS_Dates.DateDDEnFr(date_debut), "{DATE_FIN}" : UTILS_Dates.DateDDEnFr(date_fin), "{IDPRESTATION}" : str(IDprestation), "{NOM_TYPE_COTISATION}" : nomTypeCotisation, "{NOM_UNITE_COTISATION}" : nomUniteCotisation, "{COTISATION_FAM_IND}" : typeStr, "{IDCOMPTE_PAYEUR}" : str(IDcompte_payeur), "{NOM_COTISATION}" : nomCotisation, "{NOM_DEPOT}" : depotStr, "{MONTANT_FACTURE}" : montantStr, "{MONTANT_REGLE}" : regleStr, "{SOLDE_ACTUEL}" : soldeStr, "{MONTANT_FACTURE_LETTRES}" : montantStrLettres.capitalize(), "{MONTANT_REGLE_LETTRES}" : regleStrLettres.capitalize(), "{SOLDE_ACTUEL_LETTRES}" : soldeStrLettres.capitalize(), "{DATE_REGLEMENT}" : UTILS_Dates.DateDDEnFr(dateReglement), "{MODE_REGLEMENT}" : modeReglement, "{ACTIVITES}" : activites, "{NOTES}" : observations, "{IDINDIVIDU}" : IDindividu, "{BENEFICIAIRE_NOM}" : beneficiaires, "{BENEFICIAIRE_RUE}" : rue, "{BENEFICIAIRE_CP}" : cp, "{BENEFICIAIRE_VILLE}" : ville, "{IDFAMILLE}" : str(IDfamille), "{FAMILLE_NOM}" : nomTitulaires, "{FAMILLE_RUE}" : famille_rue, "{FAMILLE_CP}" : famille_cp, "{FAMILLE_VILLE}" : famille_ville, "{ORGANISATEUR_NOM}" : self.dictOrganisme["nom"], "{ORGANISATEUR_RUE}" : self.dictOrganisme["rue"], "{ORGANISATEUR_CP}" : self.dictOrganisme["cp"], "{ORGANISATEUR_VILLE}" : self.dictOrganisme["ville"], "{ORGANISATEUR_TEL}" : self.dictOrganisme["tel"], "{ORGANISATEUR_FAX}" : self.dictOrganisme["fax"], "{ORGANISATEUR_MAIL}" : self.dictOrganisme["mail"], "{ORGANISATEUR_SITE}" : self.dictOrganisme["site"], "{ORGANISATEUR_AGREMENT}" : self.dictOrganisme["num_agrement"], "{ORGANISATEUR_SIRET}" : self.dictOrganisme["num_siret"], "{ORGANISATEUR_APE}" : self.dictOrganisme["code_ape"], "{DATE_EDITION_COURT}" : UTILS_Dates.DateDDEnFr(datetime.date.today()), "{DATE_EDITION_LONG}" : UTILS_Dates.DateComplete(datetime.date.today()), } # Ajoute les informations de base individus et familles if IDindividu != None : dictDonnee.update(self.infosIndividus.GetDictValeurs(mode="individu", ID=IDindividu, formatChamp=True)) if IDfamille != None : dictDonnee.update(self.infosIndividus.GetDictValeurs(mode="famille", ID=IDfamille, formatChamp=True)) # Ajoute les réponses des questionnaires for dictReponse in self.Questionnaires.GetDonnees(IDfamille) : dictDonnee[dictReponse["champ"]] = dictReponse["reponse"] if dictReponse["controle"] == "codebarres" : dictDonnee["{CODEBARRES_QUESTION_%d}" % dictReponse["IDquestion"]] = dictReponse["reponse"] dictDonnees[IDcotisation] = dictDonnee # Champs de fusion pour Email dictChampsFusion[IDcotisation] = {} for key, valeur in dictDonnee.iteritems() : if key[0] == "{" : dictChampsFusion[IDcotisation][key] = valeur del dlgAttente return dictDonnees, dictChampsFusion
def Run(self, afficherDlgAttente=False): dictParametres = self.GetParametres() # Ouverture dlg d'attente if afficherDlgAttente == True: dlgAttente = wx.BusyInfo( _(u"Génération du fichier de données..."), None) try: # Génération du nom de fichier self.nomFichier = UTILS_Fichiers.GetRepTemp( fichier=u"data_%s" % dictParametres["IDfichier"]) # Vérifie si le fichier existe déj� nomFichierTemp = self.nomFichier + ".dat" if os.path.isfile(nomFichierTemp): os.remove(nomFichierTemp) # Création des tables dbdest = GestionDB.DB(suffixe=None, nomFichier=nomFichierTemp, modeCreation=True) dbdest.CreationTables(dicoDB=self.dictTables) # Enregistrement des paramètres listeParametres = [ ("IDfichier", dictParametres["IDfichier"]), ("horodatage", dictParametres["horodatage"]), ("type", "donnees"), ] self.Enregistrer(dbdest, nomTable="parametres", listeChamps=["nom", "valeur"], listeDonnees=listeParametres) # Données du dictIndividus from Utils import UTILS_Infos_individus infos = UTILS_Infos_individus.Informations() dictValeurs = infos.GetDictValeurs(mode="individu", formatChamp=False) listeDonnees = [] for ID, dictTemp in dictValeurs.items(): for champ, valeur in dictTemp.items(): if type(valeur) in (str, six.text_type) and valeur not in ( "", None): listeDonnees.append((ID, champ, valeur)) self.Enregistrer(dbdest, nomTable="informations", listeChamps=["IDindividu", "champ", "valeur"], listeDonnees=listeDonnees) # Données individus db = GestionDB.DB(suffixe="PHOTOS") req = """SELECT IDindividu, photo FROM photos;""" db.ExecuterReq(req) listePhotos = db.ResultatReq() db.Close() dictPhotos = {} for IDindividu, photo in listePhotos: dictPhotos[IDindividu] = photo db = GestionDB.DB() req = """SELECT IDindividu, IDcivilite, nom, prenom FROM individus;""" db.ExecuterReq(req) listeIndividus = db.ResultatReq() db.Close() listeDonnees = [] for IDindividu, IDcivilite, nom, prenom in listeIndividus: if IDindividu in dictPhotos: photo = sqlite3.Binary(dictPhotos[IDindividu]) else: photo = None listeDonnees.append( (IDindividu, IDcivilite, nom, prenom, photo)) self.Enregistrer(dbdest, nomTable="individus", listeChamps=[ "IDindividu", "IDcivilite", "nom", "prenom", "photo" ], listeDonnees=listeDonnees) # Données Titulaires de dossier dictTitulaires = UTILS_Titulaires.GetTitulaires() listeDonnees = [] for IDfamille, dictTemp in dictTitulaires.items(): nom = dictTitulaires[IDfamille]["titulairesSansCivilite"] listeDonnees.append((IDfamille, nom)) self.Enregistrer(dbdest, nomTable="titulaires", listeChamps=["IDfamille", "nom"], listeDonnees=listeDonnees) # Données organisateur db = GestionDB.DB() req = """SELECT IDorganisateur, nom, logo FROM organisateur;""" db.ExecuterReq(req) listeTemp = db.ResultatReq() db.Close() listeDonnees = [] for IDorganisateur, nom, logo in listeTemp: if logo != None: logo = sqlite3.Binary(logo) listeDonnees.append((IDorganisateur, nom, logo)) self.Enregistrer(dbdest, nomTable="organisateur", listeChamps=["IDorganisateur", "nom", "logo"], listeDonnees=listeDonnees) # Tables à copier en intégralité listeTables = [ "vacances", "jours_feries", "activites", "groupes", "unites", "unites_groupes", "unites_incompat", "unites_remplissage", "unites_remplissage_unites", "ouvertures", "remplissage", "inscriptions", "consommations", "memo_journee", "comptes_payeurs", "familles", "utilisateurs", "nomade_archivage", "niveaux_scolaires", "ecoles", "classes", "scolarite", ] self.CopieTables(dbdest, listeTables) # Cloture de la base dbdest.connexion.commit() dbdest.Close() # Compression fichierZip = zipfile.ZipFile(self.nomFichier + EXTENSION_DECRYPTE, "w", compression=zipfile.ZIP_DEFLATED) fichierZip.write(self.nomFichier + ".dat", "database.dat") fichierZip.close() os.remove(self.nomFichier + ".dat") # Cryptage cryptage_actif = UTILS_Config.GetParametre( "synchro_cryptage_activer", defaut=False) cryptage_mdp = base64.b64decode( UTILS_Config.GetParametre("synchro_cryptage_mdp", defaut="")) if six.PY3: cryptage_mdp = cryptage_mdp.decode() if cryptage_actif == True and cryptage_mdp != "": UTILS_Cryptage_fichier.CrypterFichier( self.nomFichier + EXTENSION_DECRYPTE, self.nomFichier + EXTENSION_CRYPTE, cryptage_mdp, ancienne_methode=True) os.remove(self.nomFichier + EXTENSION_DECRYPTE) nomFichierFinal = self.nomFichier + EXTENSION_CRYPTE else: nomFichierFinal = self.nomFichier + EXTENSION_DECRYPTE except Exception as err: print("Erreur dans UTILS_Export_nomade.Run :", err) traceback.print_exc(file=sys.stdout) if afficherDlgAttente == True: del dlgAttente dlg = wx.MessageDialog( None, _(u"Désolé, l'erreur suivante a été rencontrée : ") + str(err), "Erreur ", wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return None if afficherDlgAttente == True: del dlgAttente return nomFichierFinal
def on_btn_unpack(self, event): """ Create dialog to choose a file to unpack with download magic. Then run download_magic and create self.contribution. """ def magic_download_dia(warn=""): dia = pw.TextDialog( self, "Download from MagIC\nusing contribution id or DOI", "MagIC id/DOI", warn) res = dia.ShowModal() magic_id = dia.text_ctrl.return_value() if res == wx.ID_CANCEL: return wx.ID_CANCEL if res == wx.ID_OK: return magic_id else: return False dlg = pw.ChooseOne( self, "Download from MagIC", "Unpack previous downloaded file", text= "You can unpack a downloaded file from MagIC, or download a file from MagIC directly using the contribution id or DOI.", title="") dlg.Centre() res = dlg.ShowModal() # try to download directly from MagIC if res == wx.ID_YES: magic_id = True warning = "" while magic_id: magic_id = magic_download_dia(warning) # if magic id was blank if magic_id == "": warning = "You must provide a MagIC contribution id or DOI" magic_id = True continue # if user canceled the download if magic_id == wx.ID_CANCEL: return # if everything looks good, try to download if len(str(magic_id)) < 8: # use contribution id status, stuff = ipmag.download_magic_from_id(magic_id) f = "magic_contribution_{}.txt".format(magic_id) else: # use DOI status, stuff = ipmag.download_magic_from_doi(magic_id) f = "magic_contribution.txt" if not status: warning = stuff if status: break if not os.path.exists(os.path.join(self.WD, f)): os.rename(os.path.join(os.getcwd(), f), os.path.join(self.WD, f)) input_dir = self.WD # try to unpack a previously downloaded file if res == wx.ID_NO: dlg = wx.FileDialog( None, message="choose txt file to unpack", defaultDir=self.WD, defaultFile="", style=wx.FD_OPEN #| wx.FD_CHANGE_DIR ) if dlg.ShowModal() == wx.ID_OK: FILE = dlg.GetPath() input_dir, f = os.path.split(FILE) else: return False outstring = "download_magic.py -f {} -WD {} -ID {}".format( f, self.WD, input_dir) # run as module: print("-I- running python script:\n %s" % (outstring)) wait = wx.BusyInfo("Please wait, working...") wx.SafeYield() ex = None try: if ipmag.download_magic(f, self.WD, input_dir, overwrite=True, data_model=self.data_model): text = "Successfully ran download_magic.py program.\nMagIC files were saved in your working directory.\nSee Terminal/message window for details." else: text = "Something went wrong. Make sure you chose a valid file downloaded from the MagIC database and try again." return except Exception as ex: text = "Something went wrong. Make sure you chose a valid file downloaded from the MagIC database and try again." del wait dlg = wx.MessageDialog(self, caption="Saved", message=text, style=wx.OK) result = dlg.ShowModal() if result == wx.ID_OK: dlg.Destroy() if ex: raise (ex) return self.contribution = cb.Contribution(self.WD) # make a success pop-up dlg = wx.MessageDialog( self, caption="Success", message= "You can now add orientation information or metadata, or open one of the analysis tools", style=wx.OK) dlg.ShowModal()
def MAJ_page(self, page=None): dlgAttente = wx.BusyInfo(_(u"Veuillez patienter..."), self.parent) page.MAJ() del dlgAttente
def __init__(self, parent, uname, upass, dpool, epool): # begin wxGlade: MainPannel.__init__ self.version = 1.0 self.canlock = True self.listall = False self.last_copied_pass = None wx.Frame.__init__(self, parent, size=(1000, 1000), style=wx.TAB_TRAVERSAL | wx.DEFAULT_FRAME_STYLE | wx.WANTS_CHARS) self.DWorkerPool = dpool self.EWrokerPool = epool self.uname = uname self.upass = upass self.icon = wx.Icon( os.path.join(common.cur_file_dir(), "manpassc.ico"), wx.BITMAP_TYPE_ICO) self.SetIcon(self.icon) #self.chkupdate_thread=checkUpdate.ChkUpdateThread("http://192.168.1.1:8090/ver.txt",self.version,self) #username, password must be encoded into utf-8 string before they could be used by crypto functions self.lock_label = wx.HyperlinkCtrl(self, wx.ID_ANY, _("Unlock Me"), style=wx.HL_ALIGN_CENTRE) self.progress_bar = wx.Gauge(self, wx.ID_ANY) self.status_bar = wx.StatusBar(self, wx.ID_ANY) self.SetStatusBar(self.status_bar) defconflist = [ (_("Basic Options"), [ (("addr"), { "desc": _("Listening address"), "value": "127.0.0.1", "type": "string" }), (("port"), { "desc": _("Listening port"), "value": 9000, "type": "int" }), (("idle_timer"), { "desc": _("Idle lock timer(seconds)"), "value": 60, "type": "int" }), (("startup_minimize"), { "desc": _("Minimize the window upon startup"), "value": False, "type": "bool" }), (("close&lock"), { "desc": _("Lock the window upon close(windows only)"), "value": True, "type": "bool" }), ]), ] self.OptionDiag = myoptions.OptionDiag(self, "manpass.conf", defconflist, self.uname) self.confDict = None self.confDict = self.OptionDiag.toDict() if not common.checkTCPPort(self.confDict['addr'], self.confDict['port']): waitbox = wx.BusyInfo(_("Starting Manpass server, please wait...")) cmd = common.getManpassdExeName() exename = cmd cmd += " -username={uname} -pipepass=true -svrip={ip} -svrport={port}".format( uname=self.uname, ip=self.confDict['addr'], port=self.confDict['port']) args = shlex.split(cmd) if platform.system() == "Windows": startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW else: startupinfo = None try: self.svrp = subprocess.Popen(args, executable=exename, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, startupinfo=startupinfo) except Exception as Err: del waitbox wx.MessageBox(unicode(Err), _("Error"), 0 | wx.ICON_ERROR, self) self.ExitMe() return def enqueue_output(out, queue): for line in iter(out.readline, b''): queue.put(line) out.close() errq = Queue.Queue() t2 = newUserDiag.EnQThread(self.svrp.stderr, errq) t2.daemon = True t2.start() self.svrp.stdin.write(self.upass + "\n") self.svrp.stdin.close() ferror = False ferror_msg = "" def check_output(errq): t0 = time.time() ferror = False while True: wx.GetApp().Yield() try: errline = errq.get_nowait() except Queue.Empty: if time.time() - t0 > 30.0: ferror = True ferror_msg = "Time out" break pass else: if errline.find("Server started") != -1: break if errline.find("Fatal Error") != -1: ferror = True ferror_msg = errline break if (time.time() - t0) > 30.0: ferror = True ferror_msg = "Time out" break t2.stop() if ferror: ## wx.MessageBox(_("Server failed to start!\n")+unicode(ferror_msg),_("Error"),0|wx.ICON_ERROR,self) return _("Server failed to start!\n") + unicode(ferror_msg) else: return True startresult = check_output(errq) if startresult != True: del waitbox wx.MessageBox(startresult, _("Error"), 0 | wx.ICON_ERROR, self) self.ExitMe() return del waitbox try: cadata = apiclient.loadCAFile(self.uname, self.upass, self.confDict['confDir']) except Exception as Err: wx.MessageBox( _("Authentication Failed!\n") + unicode(Err), _("Error"), 0 | wx.ICON_ERROR, self) self.ExitMe() return try: self.apiclient = apiclient.APIClient( self.confDict['addr'], self.confDict['port'], cadata, os.path.join(self.confDict["confDir"], "ee.cert"), os.path.join(self.confDict["confDir"], "ee.key"), self.upass, self.DWorkerPool, self.EWrokerPool) except Exception as Err: ## traceback.print_exc(Err) wx.MessageBox(_("Failed to connect to the server!"), _("Error"), 0 | wx.ICON_ERROR, self) self.ExitMe() return self.SetTitle("Manpass - " + self.uname.decode("utf-8")) if platform.system() == "Windows": self.taskicon = MyTaskbarIcon(self) self.taskicon.SetIcon(self.icon) wx.EVT_TASKBAR_LEFT_UP(self.taskicon, self.OnDClickTaskIcon) self.Bind(wx.EVT_CLOSE, self.HideMe) self.timer_lock = wx.Timer(self, wx.NewId()) self.timer_clear = wx.Timer(self, wx.NewId()) self.timer_statustxt = wx.Timer(self, wx.NewId()) self.timer_lock.Start(self.confDict['idle_timer'] * 1000, wx.TIMER_CONTINUOUS) self.text_ctrl_search_input = wx.SearchCtrl(self, wx.NewId(), "") self.list_ctrl_1 = PassListCtrl(self, self.text_ctrl_search_input) self.Bind(wx.EVT_TIMER, self.OnTimerLock, self.timer_lock) self.Bind(wx.EVT_TIMER, self.OnTimerClear, self.timer_clear) self.Bind(wx.EVT_TIMER, self.OnTimerStatusTxt, self.timer_statustxt) self.Bind(wx.EVT_TEXT, self.OnFilter, self.text_ctrl_search_input) self.text_ctrl_search_input.Bind(wx.EVT_SET_FOCUS, self.OnFilterAct) self.text_ctrl_search_input.Bind(wx.EVT_CHAR, self.OnChar) self.Bind(wx.EVT_CHAR, self.OnChar) self.list_ctrl_1.Bind(wx.EVT_CHAR, self.OnChar) self.lock_label.Bind(wx.EVT_CHAR, self.OnChar) ## self.text_ctrl_search_input.Bind(wx.EVT_SET_FOCUS,self.OnFilterAct) self.__set_properties() self.__do_layout() self.CentreOnScreen() self.SetSize((400, 400)) self.list_ctrl_1.reload() self.text_ctrl_search_input.SetFocus() self.text_ctrl_search_input.SetValue("") #self.Bind(wx.EVT_ICONIZE,self.HideMe) self.lock_label.Bind(wx.EVT_HYPERLINK, self.OnUnlock) #self.text_ctrl_search_input.Bind(wx.EVT_CHAR,self.resetTimer) self.list_ctrl_1.Bind(wx.dataview.EVT_DATAVIEW_SELECTION_CHANGED, self.resetTimer) self.list_ctrl_1.Bind(wx.dataview.EVT_DATAVIEW_ITEM_ACTIVATED, self.resetTimer) self.list_ctrl_1.Bind(wx.dataview.EVT_DATAVIEW_COLUMN_HEADER_CLICK, self.resetTimer) self.list_ctrl_1.Bind( wx.dataview.EVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK, self.resetTimer) self.list_ctrl_1.Bind(wx.dataview.EVT_DATAVIEW_ITEM_CONTEXT_MENU, self.resetTimer) self.Bind(wx.EVT_ACTIVATE, self.resetTimer) self.Bind(common.EVT_MANPASS_FATALERR, self.OnFatal) self.Bind(common.EVT_MANPASS_PROGRESS, self.UpdateProgress) self.Bind(common.EVT_MANPASS_LOAD_DONE, self.LoadDone) self.Bind(wx.EVT_SET_FOCUS, self.OnFocus) #self.Bind(checkUpdate.EVT_CHK_UPDATE,self.CheckUpdateDone) if platform.system() == "Windows": import win32con self.RegisterHotKey(52445, win32con.MOD_CONTROL, ord("I")) self.Bind(wx.EVT_HOTKEY, self.OnDClickTaskIcon, id=52445) if self.confDict['startup_minimize']: self.HideMe(None) else: self.Show(True) self.Raise()
def load(self, id): self.DeleteAllItems() mysql = self.top.main_frame.mysql if not mysql: self.top.err("No available connection to MySQL server.") return try: busy = wx.BusyInfo("Loading... please wait.") wx.Yield() except: pass # instantiate a mysql cursor. cursor = mysql.cursor(MySQLdb.cursors.DictCursor) # retrieve the module info. cursor.execute("SELECT * FROM pp_modules WHERE id = '%d'" % id) module = cursor.fetchone() # save the selected module DB entry to the top. self.top.module = module # step through the recon entries for this module id. cursor.execute( "SELECT * FROM pp_recon WHERE module_id = '%d' ORDER BY offset ASC" % id) idx = reviewed = 0 for recon in cursor.fetchall(): address = module["base"] + recon["offset"] # count the number of hits under this recon point. c = mysql.cursor(MySQLdb.cursors.DictCursor) c.execute( "SELECT COUNT(id) AS count FROM pp_hits WHERE recon_id = '%d'" % recon["id"]) num_hits = c.fetchone()["count"] c.close() self.InsertStringItem(idx, "") self.SetStringItem(idx, 0, "%04x" % recon["id"]) self.SetStringItem(idx, 1, "%08x" % address) self.SetStringItem(idx, 2, "%d" % recon["stack_depth"]) self.SetStringItem(idx, 3, recon["status"]) self.SetStringItem(idx, 4, recon["username"]) self.SetStringItem(idx, 5, "%d" % num_hits) self.SetStringItem(idx, 6, recon["boron_tag"]) self.SetStringItem(idx, 7, recon["reason"]) # create an entry for the column sort map. self.SetItemData(idx, idx) self.items_sort_map[idx] = (recon["id"], address, recon["stack_depth"], recon["status"], recon["username"], num_hits, recon["boron_tag"], recon["reason"]) if recon["status"] in ["uncontrollable", "clear", "vulnerable"]: reviewed += 1 idx += 1 # update % coverage gauge. self.top.percent_analyzed_static.SetLabel( "%d of %d RECON Points Reviewed:" % (reviewed, idx)) percent = int((float(reviewed) / float(idx)) * 100) self.top.percent_analyzed.SetValue(percent) cursor.close()
def __init__(self, parent, id=wx.ID_ANY, title=None, vectorName=None, item=None, log=None, selection=None, **kwargs): """GRASS Attribute Table Manager window :param parent: parent window :param id: window id :param title: window title or None for default title :param vectorName: name of vector map :param item: item from Layer Tree :param log: log window :param selection: name of page to be selected :param kwagrs: other wx.Frame's arguments """ self.parent = parent try: mapdisplay = self.parent.GetMapDisplay() except: mapdisplay = None DbMgrBase.__init__(self, id=id, mapdisplay=mapdisplay, vectorName=vectorName, item=item, log=log, statusbar=self, **kwargs) wx.Frame.__init__(self, parent, id, *kwargs) # title if not title: title = "%s" % _("GRASS GIS Attribute Table Manager - ") if not self.dbMgrData['editable']: title += _("READONLY - ") title += "<%s>" % (self.dbMgrData['vectName']) self.SetTitle(title) # icon self.SetIcon( wx.Icon( os.path.join( globalvar.ICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(parent=self, id=wx.ID_ANY) if len(self.dbMgrData['mapDBInfo'].layers.keys()) == 0: GMessage( parent=self.parent, message=_( "Database connection for vector map <%s> " "is not defined in DB file. " "You can define new connection in " "'Manage layers' tab.") % self.dbMgrData['vectName']) busy = wx.BusyInfo(_("Please wait, loading attribute data..."), parent=self.parent) wx.SafeYield() self.CreateStatusBar(number=1) self.notebook = GNotebook(self.panel, style=globalvar.FNPageDStyle) self.CreateDbMgrPage(parent=self, pageName='browse') self.notebook.AddPage(page=self.pages['browse'], text=_("Browse data"), name='browse') self.pages['browse'].SetTabAreaColour(globalvar.FNPageColor) self.CreateDbMgrPage(parent=self, pageName='manageTable') self.notebook.AddPage( page=self.pages['manageTable'], text=_("Manage tables"), name='table') self.pages['manageTable'].SetTabAreaColour(globalvar.FNPageColor) self.CreateDbMgrPage(parent=self, pageName='manageLayer') self.notebook.AddPage( page=self.pages['manageLayer'], text=_("Manage layers"), name='layers') del busy if selection: wx.CallAfter(self.notebook.SetSelectionByName, selection) else: wx.CallAfter(self.notebook.SetSelection, 0) # select browse tab # buttons self.btnClose = Button(parent=self.panel, id=wx.ID_CLOSE) self.btnClose.SetToolTip(_("Close Attribute Table Manager")) self.btnReload = Button(parent=self.panel, id=wx.ID_REFRESH) self.btnReload.SetToolTip( _("Reload currently selected attribute data")) self.btnReset = Button(parent=self.panel, id=wx.ID_CLEAR) self.btnReset.SetToolTip( _("Reload all attribute data (drop current selection)")) # events self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow) self.btnReload.Bind(wx.EVT_BUTTON, self.OnReloadData) self.btnReset.Bind(wx.EVT_BUTTON, self.OnReloadDataAll) self.notebook.Bind( FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) # do layout self._layout() # self.SetMinSize(self.GetBestSize()) self.SetSize((700, 550)) # FIXME hard-coded size self.SetMinSize(self.GetSize())
def on_right_click_popup_expand_tag (self, event): ''' Right click event handler for popup expand tag menu selection. ''' if not self.selected: return selected = self.GetPyData(self.selected) mysql = self.top.main_frame.mysql if not mysql: self.top.err("No available connection to MySQL server.") return dlg = wx.MessageDialog(self, "Expand out the basic blocks under: %s?\n" % selected["tag"], "Confirm", wx.YES_NO | wx.ICON_QUESTION | wx.NO_DEFAULT) if dlg.ShowModal() == wx.ID_NO: return dlg.Destroy() busy = wx.BusyInfo("Expanding tag ... please wait.") wx.Yield() cc = utils.code_coverage.code_coverage(mysql=mysql) cc.import_mysql(selected["target_id"], selected["id"]) no_modules = [] new_hits = [] for ea in cc.hits.keys(): hit = cc.hits[ea][0] # we are expanding out all the basic blocks of the hit functions. if not hit.is_function: continue # if we don't have the module for this hit, continue to the next one. if not self.top.pida_modules.has_key(hit.module): if not no_modules.count(hit.module): no_modules.append(hit.module) self.top.err("Necessary module '%s' for part of tag expansion missing, ignoring." % hit.module) continue # rebase the module if necessary. self.top.pida_modules[hit.module].rebase(hit.base) # grab the appropriate PIDA function. function = self.top.pida_modules[hit.module].functions[hit.eip] for bb_ea in function.basic_blocks.keys(): if not cc.hits.has_key(bb_ea): ccs = utils.code_coverage.__code_coverage_struct__() ccs.eip = bb_ea ccs.tid = 0 ccs.num = cc.num ccs.timestamp = 0 ccs.module = hit.module ccs.base = hit.base ccs.is_function = 0 new_hits.append(ccs) # increment the internal counter. cc.num += 1 # manually propagate the new hits into the code coverage data structure. for ccs in new_hits: if not cc.hits.has_key(ccs.eip): cc.hits[ccs.eip] = [] cc.hits[ccs.eip].append(ccs) # clear the current database entries and upload the new ones. cc.clear_mysql(selected["target_id"], selected["id"]) cc.export_mysql(selected["target_id"], selected["id"]) self.top.msg("Tag expansion complete, added %d new entries." % len(new_hits))
def importModules(wxpython=False): # This is a function for finding and importing modules # Sometimes the extra Python packages get installed in weird places, most especially on OSX # For Windows, everything is packaged into that Python install so we shouldn't have problems on Windows # First let's find out if PYROSETTA_DATABASE is set, and figure out what it should be if not if (not(wxpython)): try: # Is PYROSETTA_DATABASE defined? # If not, then we don't know where PyRosetta is and have to look for it s = os.environ["PYROSETTA_DATABASE"] if (len(s) == 0): raise Exception except: # Let's find it # Did we find it already and save it? if (platform.system() == "Windows"): cfgfile = os.path.expanduser("~") + "/InteractiveROSETTA/seqwindow.cfg" else: cfgfile = os.path.expanduser("~") + "/.InteractiveROSETTA/seqwindow.cfg" try: f = open(cfgfile.strip(), "r") rosettadir = "Not Found" rosettadb = "Not Found" for aline in f: if ("[ROSETTAPATH]" in aline): rosettapath = aline.split("\t")[1].strip() if ("[ROSETTADB]" in aline): rosettadb = aline.split("\t")[1].strip() f.close() if (rosettapath == "Not Found"): # It wasn't saved there raise Exception else: # Let's try this saved path # On Windows you have to cd to where the folder is to import, because appending to the # path does not appear to work sys.path.append(rosettapath) if (platform.system() == "Windows"): olddir = os.getcwd() os.chdir(rosettapath) os.environ["PYROSETTA_DATABASE"] = rosettadb if (platform.system() == "Windows"): olddir = os.getcwd() os.chdir(olddir) except: # We didn't save it or the saved location was bad # The error may have been the Rosetta import, which means the file needs to be closed try: f.close() except: pass # Tell the user we're busy looking for PyRosetta import wx busyDlg = wx.BusyInfo("Searching for PyRosetta installation, please be patient...") # Okay, we still didn't get it, so let's traverse the filesystem looking for it... foundIt = False if (platform.system() == "Windows"): roots = ["C:\\"] elif (platform.system() == "Darwin"): # To avoid long searches on Mac roots = ["/Users", "/Applications", "/"] else: roots = ["/"] for root in roots: for dpath, dnames, fnames in os.walk(root): try: if (platform.system() == "Windows"): # On Windows, we expect the PyRosetta folder to have either rosetta.pyd # or rosetta.dll in the folder try: indx = fnames.index("rosetta.pyd") # 64bit except: indx = fnames.index("rosetta.dll") # 32bit else: # On Mac/Linux, there should be a libmini file in the folder # On Mac, it's libmini.dylib, on Linux it's libmini.so indx = dnames.index("rosetta") files = glob.glob(dpath + "/rosetta/*libmini*") if (len(files) == 0): raise Exception except: continue # If we got this far, then we found a candidate PyRosetta folder # Is the database in this folder also? # It is either called "database" or "rosetta_database" foundIt = True rosettapath = dpath for dname in dnames: if ("database" in dname): rosettadb = dpath + "/" + dname break break if (foundIt): break busyDlg = None if (foundIt): # Let's try to import what we found # Remember on Windows we have to cd sys.path.append(rosettapath) if (platform.system() == "Windows"): olddir = os.getcwd() os.chdir(rosettapath) os.environ["PYROSETTA_DATABASE"] = rosettadb try: # Now let's save these paths so the next time this gets started we don't have to traverse the filesystem again data = [] f = open(cfgfile, "r") for aline in f: if (not("[ROSETTAPATH]" in aline) and not("[ROSETTADB]") in aline): data.append(aline.strip()) f.close() f = open(cfgfile, "w") for aline in data: f.write(aline + "\n") f.write("[ROSETTAPATH]\t" + rosettapath.strip() + "\n") f.write("[ROSETTADB]\t" + rosettadb.strip() + "\n") f.close() if (platform.system() == "Windows"): olddir = os.getcwd() os.chdir(olddir) except: # Can't find it, it's probably not installed or it's in a hidden location print "PyRosetta cannot be found on your system!" print "Until you install PyRosetta, you may only use InteractiveROSETTA to visualize structures in PyMOL" exit() # Attempt to locate other packages that may not be on the PYTHONPATH if (platform.system() == "Windows"): # We want to import wxPython a bit earlier than the others, to display graphics for the license agreement # On Windows, everything should already be in the Python package, so don't try to find anything # If there are issues, the user should reinstall InteractiveROSETTA if (wxpython): import wx else: import numpy import pymol import psutil import requests import poster import Bio import openbabel else: if (platform.system() == "Darwin"): # These are the standard locations for some of these things, hopefully we'll get these right away # These are the paths that are used in the bash installer sys.path.append("/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages") sys.path.append("/usr/local/Cellar/open-babel/HEAD/lib/python2.7/site-packages") # Again, here's the option for either importing wx only, or all the modules if (wxpython): modules = ["wx"] else: modules = ["numpy", "pymol", "psutil", "requests", "poster", "Bio", "openbabel"] notfound = [] # Try to import each of the modules and keep track of which ones throw an error for module in modules: try: mod = __import__(module) except: notfound.append(module) # For everything that is not found, let's first see if we've saved a location and try to import from there cwd = os.getcwd() goToSandbox() for module in notfound: keyword = "[" + module.upper() + "PATH]" f = open("seqwindow.cfg", "r") path = "N/A" for aline in f: if (keyword in aline): path = aline.split("\t")[1].strip() break f.close() # Add the saved location to the path sys.path.append(path) # Try to import again try: if (path == "N/A"): raise Exception mod = __import__(module) except: # This still didn't work, so now we have to search for it print "Could not import " + module + "... Searching for it..." root = "/usr/local" foundIt = False for dpath, dnames, fnames in os.walk(root): # We're looking for a directory that is the name of the module, on some path that # includes python for dname in dnames: if ((module in dname and os.path.isfile(dpath + "/" + dname + "/__init__.py")) or module + ".py" in fnames): if ("python3" in dpath): # Sometimes there are duplicates for python3, and trying to import them ruins everything break sys.path.append(dpath) print "Trying " + dpath.strip() + "..." try: # Try to import it again mod = __import__(str(module)) # Now let's save these paths so the next time this gets started we don't have to traverse the filesystem again data = [] f = open("seqwindow.cfg", "r") for aline in f: if (not(keyword in aline)): data.append(aline.strip()) f.close() f = open("seqwindow.cfg", "w") for aline in data: f.write(aline + "\n") f.write(keyword + "\t" + dpath.strip() + "\n") f.close() print "Found " + module + " at " + dpath.strip() + "!" foundIt = True except: pass break if (foundIt): break if (not(foundIt)): # Explain how to install the packages that are missing print module + " cannot be found on your system!" if (module == "Bio"): print "Install it by executing \"sudo easy_install biopython\" in a terminal." elif (module == "openbabel" and platform.system() == "Darwin"): print "Install it by executing \"brew install mcs07/cheminformatics/open-babel --HEAD --with-python\" in a terminal." elif (module == "openbabel" and platform.system() == "Linux"): print "Install it by executing either \"sudo apt-get install python-openbabel\" or \"sudo yum install openbabel python-openbabel\" in a terminal." elif (module == "wx" and platform.system() == "Darwin"): print "Download and install wxPython from here: http://www.wxpython.org/download.php, wxPython3.0-osx-cocoa-py2.7" elif (module == "wx" and platform.system() == "Linux"): print "Install it by executing either \"sudo apt-get install python-wxgtk2.8\" or \"sudo yum install wxPython\" in a terminal." else: print "Install it by executing \"sudo easy_install " + module + "\" in a terminal." exit() if (wxpython): import wx else: import numpy import pymol import psutil import requests import poster import Bio import openbabel os.chdir(cwd)
def OnExplorerButton(self, event): busy = wx.BusyInfo("Please wait! Loading Explorer...") wx.Yield() self.ShowFileListView() #print 'cliked' event.Skip()
def _do_registration(self, modality, fiji_path, registration_script, registration_params, input_folder, input_filenames_prefix, output_folder, num_images, orig_image_size, pixels_per_mm, info_description, info_parameters): # modality is 'EM' or 'LM' # Ensure that folder exists, if not create it and its parent folders. tools.make_dir(output_folder) # Tell Fiji to execute a macro that (i) reads the LM/EM images, (ii) merges them into a stack, # (iii) saves the stack to TIFF, (iv) aligns the slices in this stack # and (v) saves the aligned stack to TIFF. # Registration happens either with Fiji's Plugins > Registration > Linear Stack Alignment with SIFT, or with Plugins > StackReg. busy_string = "Registering {} images...".format(modality) print(busy_string) print( 'Starting a headless Fiji and calling the image registration plugin. Please be patient...' ) script_args = "srcdir='{}',dstdir='{}',prefix='{}',method='{}',numimages='{}',do_invert='{}',do_enhance_contrast='{}',do_crop='{}',roi_x='{}',roi_y='{}',roi_width='{}',roi_height='{}'".format( input_folder, output_folder, input_filenames_prefix, registration_params['method'], num_images, registration_params["invert"], registration_params["enhance_contrast"], registration_params["crop"], registration_params["roi"][0], registration_params["roi"][1], registration_params["roi"][2], registration_params["roi"][3]) # Note: info about headless ImageJ: https://imagej.net/Headless#Running_macros_in_headless_mode wait = wx.BusyInfo(busy_string) retcode, out, err = tools.commandline_exec([ fiji_path, "-Dpython.console.encoding=UTF-8", "--ij2", "--headless", "--console", "--run", registration_script, script_args ]) print('Headless Fiji retcode={}\nstdout=\n{}\nstderr={}\n'.format( retcode, out, err)) del wait # # # # # # # # # # BEGIN EXPERIMENTAL CODE update_offsets = True output_filename = '{}_aligned_stack.tif'.format( registration_params['method']) registration_correct = wx.MessageBox( 'Please check the registration result {}.\n' 'Are all images aligned correctly?'.format( os.path.join(output_folder, output_filename)), 'Registration successful?', wx.YES_NO | wx.ICON_QUESTION, self) # "Yes" is selected by default if registration_correct == wx.NO: print('User feedback: registration is not correct.') with RegistrationImportDialog(output_folder, None, wx.ID_ANY, "Import Registration Output") as dlg: if dlg.ShowModal() == wx.ID_OK: print('Using manual registration output') out = dlg.get_registration_output() info_description = info_description + ' (Manual)' else: print('User feedback: do not use manual registration') update_offsets = False else: print('User feedback: registration is correct.') # # # # # # # # # # END EXPERIMENTAL CODE if update_offsets: # Parse the output of the registration plugin and extract # the transformation matrices to register each slice onto the next. print( 'Extracting transformation matrices from registration plugin output' ) registration_matrices = tools.extract_registration_matrices( registration_params['method'], out) print(registration_matrices) registration_offsets_microns = self.calculate_registration_offsets( registration_matrices, orig_image_size, pixels_per_mm, registration_params) print( 'Registration corrected point-of-interest offsets [micrometer]: ' + repr(registration_offsets_microns)) # Combine (=sum) existing offsets with this new one assert self._model.combined_offsets_microns is not None assert len(self._model.combined_offsets_microns) == len( registration_offsets_microns) self._model.combined_offsets_microns = map( operator.add, self._model.combined_offsets_microns, registration_offsets_microns) print('Combined offsets [micrometer]: ' + repr(self._model.combined_offsets_microns)) # Append offset correction to "history" of existing offsets. self._model.all_offsets_microns.append({ 'name': info_description, 'parameters': info_parameters, 'offsets': registration_offsets_microns }) else: print('Registration plugin output NOT used.') print('Slice offsets NOT updated with corrections.') # self._do_save_poi_info(output_folder) # For debugging / validation: display the offsets table. tools.show_offsets_table(self._model.all_offsets_microns, self._model.combined_offsets_microns)
def SauvegardeRappels(self): """ Sauvegarde des rappels """ dlgAttente = wx.BusyInfo(_(u"Génération des rappels en cours..."), None) wx.Yield() # Recherche numéro de facture suivant DB = GestionDB.DB() req = """SELECT MAX(numero) FROM rappels;""" DB.ExecuterReq(req) listeDonnees = DB.ResultatReq() DB.Close() if listeDonnees[0][0] == None: numero = 1 else: numero = listeDonnees[0][0] + 1 # Récupère Utilisateur en cours IDutilisateur = UTILS_Identification.GetIDutilisateur() # Génération des rappels listeRappelsGenerees = [] # Fusion des mots-clés facturation = UTILS_Rappels.Facturation() # Tri par ordre alphabétique de la liste listeComptes = [] listeAnomalies = [] dictCoches = self.ctrl_rappels.GetCoches() for IDcompte_payeur, dictCompte in self.ctrl_rappels.dictComptes.iteritems( ): if dictCompte["select"] == True and dictCoches.has_key( IDcompte_payeur): # Insertion du document dans le dictCompte dictDocument = self.ctrl_rappels.GetDictDocument( IDcompte_payeur) if dictDocument["IDtexte"] == 0: listeAnomalies.append(IDcompte_payeur) else: dictCompte["IDtexte"] = dictDocument["IDtexte"] dictCompte["titre"] = dictDocument["titre"] dictCompte["texte"] = facturation.Fusion( dictCompte["IDtexte"], dictCompte) listeComptes.append((dictCompte["nomSansCivilite"], IDcompte_payeur, dictCompte)) listeComptes.sort() # Il reste des textes non attribués : if len(listeAnomalies) > 0: del dlgAttente dlg = wx.MessageDialog( self, _(u"Il reste %d lettre(s) pour lesquelles vous n'avez pas attribué de texte !" ) % len(listeAnomalies), _(u"Erreur de saisie"), wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() return False # Sauvegarde DB = GestionDB.DB() try: index = 0 for nomTitulaires, IDcompte_payeur, dictCompte in listeComptes: self.EcritStatusbar( _(u"Génération de la lettre de rappel %d sur %d...") % (index + 1, len(listeComptes))) # Liste des activités texteActivites = "" for IDactivite in self.parent.dictParametres["listeActivites"]: texteActivites += "%d;" % IDactivite if len(texteActivites) > 0: texteActivites = texteActivites[:-1] # Sauvegarde de la facture listeDonnees = [ ("numero", numero), ("IDcompte_payeur", IDcompte_payeur), ("date_edition", str(datetime.date.today())), ("date_reference", self.parent.dictParametres["date_reference"]), ("IDtexte", dictCompte["IDtexte"]), ("activites", texteActivites), ("date_min", str(dictCompte["date_min"])), ("date_max", str(dictCompte["date_max"])), ("solde", float(dictCompte["solde_num"])), ("IDlot", self.parent.dictParametres["IDlot"]), ("prestations", ";".join(self.parent.dictParametres["prestations"])), ] IDrappel = DB.ReqInsert("rappels", listeDonnees) listeRappelsGenerees.append(IDrappel) numero += 1 index += 1 DB.Close() self.EcritStatusbar(u"") del dlgAttente except Exception, err: DB.Close() del dlgAttente traceback.print_exc(file=sys.stdout) dlg = wx.MessageDialog( self, _(u"Désolé, le problème suivant a été rencontré : \n\n%s" ) % err, _(u"Erreur"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() self.EcritStatusbar(u"") return False
def Load(self, filename): """Load layer tree definition stored in GRASS Workspace XML file (gxw) .. todo:: Validate against DTD :return: True on success :return: False on error """ # parse workspace file try: gxwXml = ProcessWorkspaceFile(etree.parse(filename)) except Exception as e: GError( parent=self.lmgr, message=_("Reading workspace file <%s> failed.\n" "Invalid file, unable to parse XML document.") % filename, ) return False if gxwXml.database and gxwXml.location and gxwXml.mapset: if not self._tryToSwitchMapsetFromWorkspaceFile(gxwXml): return False # the really busy part starts here (mapset change is fast) busy = wx.BusyInfo(_("Please wait, loading workspace..."), parent=self.lmgr) wx.GetApp().Yield() # # load layer manager window properties # if (UserSettings.Get(group="general", key="workspace", subkey=["posManager", "enabled"]) is False): if gxwXml.layerManager["pos"]: self.lmgr.SetPosition(gxwXml.layerManager["pos"]) if gxwXml.layerManager["size"]: self.lmgr.SetSize(gxwXml.layerManager["size"]) if gxwXml.layerManager["cwd"]: self.lmgr.cwdPath = gxwXml.layerManager["cwd"] if os.path.isdir(self.lmgr.cwdPath): os.chdir(self.lmgr.cwdPath) # # start map displays first (list of layers can be empty) # displayId = 0 mapdisplay = list() for display in gxwXml.displays: mapdisp = self.lmgr.NewDisplay(name=display["name"], show=False) mapdisplay.append(mapdisp) maptree = self.lmgr.notebookLayers.GetPage(displayId).maptree # set windows properties mapdisp.SetProperties( render=display["render"], mode=display["mode"], showCompExtent=display["showCompExtent"], alignExtent=display["alignExtent"], constrainRes=display["constrainRes"], projection=display["projection"]["enabled"], ) if display["projection"]["enabled"]: if display["projection"]["epsg"]: UserSettings.Set( group="display", key="projection", subkey="epsg", value=display["projection"]["epsg"], ) if display["projection"]["proj"]: UserSettings.Set( group="display", key="projection", subkey="proj4", value=display["projection"]["proj"], ) # set position and size of map display if not UserSettings.Get(group="general", key="workspace", subkey=["posDisplay", "enabled"]): if display["pos"]: mapdisp.SetPosition(display["pos"]) if display["size"]: mapdisp.SetSize(display["size"]) # set extent if defined if display["extent"]: w, s, e, n, b, t = display["extent"] region = maptree.Map.region = maptree.Map.GetRegion(w=w, s=s, e=e, n=n) mapdisp.GetWindow().ResetZoomHistory() mapdisp.GetWindow().ZoomHistory(region["n"], region["s"], region["e"], region["w"]) if "showStatusbar" in display and not display["showStatusbar"]: mapdisp.ShowStatusbar(False) if "showToolbars" in display and not display["showToolbars"]: for toolbar in mapdisp.GetToolbarNames(): mapdisp.RemoveToolbar(toolbar) displayId += 1 mapdisp.Show() # show mapdisplay # set render property to False to speed up loading layers mapdisp.mapWindowProperties.autoRender = False maptree = None selectList = [] # list of selected layers # # load list of map layers # for layer in gxwXml.layers: display = layer["display"] maptree = self.lmgr.notebookLayers.GetPage(display).maptree newItem = maptree.AddLayer( ltype=layer["type"], lname=layer["name"], lchecked=layer["checked"], lopacity=layer["opacity"], lcmd=layer["cmd"], lgroup=layer["group"], lnviz=layer["nviz"], lvdigit=layer["vdigit"], loadWorkspace=True, ) if "selected" in layer: selectList.append((maptree, newItem, layer["selected"])) for maptree, layer, selected in selectList: if selected: if not layer.IsSelected(): maptree.SelectItem(layer, select=True) else: maptree.SelectItem(layer, select=False) del busy # set render property again when all layers are loaded for i, display in enumerate(gxwXml.displays): mapdisplay[i].mapWindowProperties.autoRender = display["render"] for overlay in gxwXml.overlays: # overlay["cmd"][0] name of command e.g. d.barscale, d.legend # overlay["cmd"][1:] parameters and flags if overlay["display"] == i: if overlay["cmd"][0] == "d.legend.vect": mapdisplay[i].AddLegendVect(overlay["cmd"]) if overlay["cmd"][0] == "d.legend": mapdisplay[i].AddLegendRast(overlay["cmd"]) if overlay["cmd"][0] == "d.barscale": mapdisplay[i].AddBarscale(overlay["cmd"]) if overlay["cmd"][0] == "d.northarrow": mapdisplay[i].AddArrow(overlay["cmd"]) if overlay["cmd"][0] == "d.text": mapdisplay[i].AddDtext(overlay["cmd"]) # avoid double-rendering when loading workspace # mdisp.MapWindow2D.UpdateMap() # nviz if gxwXml.displays[i]["viewMode"] == "3d": mapdisplay[i].AddNviz() self.lmgr.nvizUpdateState( view=gxwXml.nviz_state["view"], iview=gxwXml.nviz_state["iview"], light=gxwXml.nviz_state["light"], ) mapdisplay[i].MapWindow3D.constants = gxwXml.nviz_state[ "constants"] for idx, constant in enumerate( mapdisplay[i].MapWindow3D.constants): mapdisplay[i].MapWindow3D.AddConstant(constant, i + 1) for page in ("view", "light", "fringe", "constant", "cplane"): self.lmgr.nvizUpdatePage(page) self.lmgr.nvizUpdateSettings() mapdisplay[i].toolbars["map"].combo.SetSelection(1) self.workspaceFile = filename return True
def on_upload_file(self, event): """ Write all data to appropriate er_* and pmag_* files. Then use those files to create a MagIC upload format file. Validate the upload file. """ # coherence validations wait = wx.BusyInfo('Validating data, please wait...') wx.Yield() spec_warnings, samp_warnings, site_warnings, loc_warnings = self.er_magic.validate_data() result_warnings = self.er_magic.validate_results(self.er_magic.results) meas_warnings = self.er_magic.validate_measurements(self.er_magic.measurements) self.warn_dict = {'specimen': spec_warnings, 'sample': samp_warnings, 'site': site_warnings, 'location': loc_warnings, 'result': result_warnings, 'age': {}, 'measurement': meas_warnings} # done coherence validations del wait # write upload file and perform data validations wait = wx.BusyInfo('Making upload file, please wait...') wx.Yield() self.er_magic.write_files() upfile, error_message, errors = ipmag.upload_magic(dir_path=self.WD, data_model=self.data_model) del wait if upfile: text = "You are ready to upload.\nYour file:\n{}\nwas generated in directory: \n{}\nDrag and drop this file in the MagIC database.".format(os.path.split(upfile)[1], self.WD) dlg = wx.MessageDialog(self, caption="Saved", message=text, style=wx.OK) else: text = "There were some problems with the creation of your upload file.\nError message: {}\nSee Terminal/Command Prompt for details".format(error_message) dlg = wx.MessageDialog(self, caption="Error", message=text, style=wx.OK) result = dlg.ShowModal() if result == wx.ID_OK: dlg.Destroy() self.edited = False ## add together data & coherence errors into one dictionary if errors: for item_type in errors: for item_name in errors[item_type]: if item_name in self.warn_dict[item_type]: self.warn_dict[item_type][item_name].update(errors[item_type][item_name]) else: self.warn_dict[item_type][item_name] = errors[item_type][item_name] has_problems = [] for item_type, warnings in list(self.warn_dict.items()): if warnings: has_problems.append(item_type) # for any dtypes with validation problems (data or coherence), # highlight the button to the corresponding grid # skip this step for Windows if sys.platform in ['win32', 'win62']: pass else: for dtype in self.warn_dict: wind = self.FindWindowByName(dtype + '_btn') if wind: if dtype in has_problems: wind.Bind(wx.EVT_PAINT, self.highlight_button) else: wind.Unbind(wx.EVT_PAINT, handler=self.highlight_button) self.Refresh() if has_problems: self.validation_mode = set(has_problems) if sys.platform in ['win32', 'win62']: self.message.SetLabel('The following grid(s) have incorrect or incomplete data:\n{}'.format(', '.join(self.validation_mode))) else: self.message.SetLabel('Highlighted grids have incorrect or incomplete data') self.bSizer_msg.ShowItems(True) self.hbox.Fit(self) if not has_problems: self.validation_mode = set() self.message.SetLabel('') self.bSizer_msg.ShowItems(False) self.hbox.Fit(self)
def on_back_elimination(self, *evt): wait = wx.BusyInfo('Please Wait\nPerforming Backward Elimination') self.plot.backward_elimination() del wait self.radiobox_include_back_elim.Enable()
_(u"La connexion FTP n'a pas pu être établie !\n\nVérifiez les paramètres de connexion FTP dans les paramètres de synchronisation." ), "Erreur ", wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return False del dlgAttente # Analyse du fichier ftp = ftplib.FTP(hote, identifiant, mdp) ftp.cwd(repertoire) for nomFichier, tailleFichier in listeFichiersRecus: # Analyse du fichier dlgAttente = wx.BusyInfo( _(u"Analyse du fichier synchronisation..."), self) resultat = AnalyserFichier(nomFichier=nomFichier, tailleFichier=tailleFichier, typeTransfert="ftp") del dlgAttente # Suppression du fichier dans le répertoire FTP ftp.delete(nomFichier) ftp.quit() # MAJ de la liste des fichiers self.ctrl_fichiers.MAJ() def OnBoutonActualiser(self, event): self.ctrl_fichiers.MAJ()
def OnFindWidget(self, evt): self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.OnCaptureLost) self.CaptureMouse() self.finding = wx.BusyInfo("Click on any widget in the app...")
def make_grid_frame(self, event): """ Create a GridFrame for data type of the button that was clicked """ if self.grid_frame: print('-I- You already have a grid frame open') pw.simple_warning("You already have a grid open") return try: grid_type = event.GetButtonObj().Name[:-4] # remove '_btn' except AttributeError: grid_type = self.FindWindowById(event.Id).Name[:-4] # remove ('_btn') wait = wx.BusyInfo('Making {} grid, please wait...'.format(grid_type)) wx.SafeYield() # propagate site lat/lon info into locations if necessary if grid_type == 'locations' and 'sites' in self.contribution.tables: self.contribution.get_min_max_lat_lon() self.contribution.propagate_cols_up(['lithologies', 'geologic_classes'], 'locations', 'sites') # propagate lithologies/type/class information from sites to samples/specimens if grid_type in ['specimens', 'samples']: self.contribution.propagate_lithology_cols() # propagate average lat/lon info from samples table if # available in samples and missing in sites if grid_type == 'sites': self.contribution.propagate_average_up(cols=['lat', 'lon', 'height'], target_df_name='sites', source_df_name='samples') self.contribution.propagate_lithology_cols() # hide mainframe self.on_open_grid_frame() # choose appropriate size for grid if grid_type == 'measurements': huge = True else: huge = False # make grid frame self.grid_frame = grid_frame.GridFrame(self.contribution, self.WD, grid_type, grid_type, self.panel, huge=huge) row_string = "" # paint validations if appropriate if self.validation_mode: if grid_type in self.validation_mode: if grid_type == 'measurements': skip_cell_render = True else: skip_cell_render = False self.grid_frame.toggle_help(None, "open") row_problems = self.failing_items[grid_type]["rows"] missing_columns = self.failing_items[grid_type]["missing_columns"] missing_groups = self.failing_items[grid_type]["missing_groups"] #all_cols = row_problems.columns #col_nums = range(len(all_cols)) #col_pos = dict(zip(all_cols, col_nums)) if len(row_problems): row_string = "Columns and rows with problem data have been highlighted in blue.\n" if not skip_cell_render: row_string += "Cells with problem data are highlighted according to the type of problem.\nRed: incorrect data\n" row_string += "For full error messages, see {}.".format(grid_type + "_errors.txt") # reset codes button to show error file instead self.grid_frame.toggle_codes_btn.SetLabel("Show errors") self.grid_frame.Bind(wx.EVT_BUTTON, self.grid_frame.show_errors, self.grid_frame.toggle_codes_btn) # paint cells for row in row_problems['num']: self.grid_frame.grid.paint_invalid_row(row) mask = row_problems["num"] == row items = row_problems[mask] cols = items.dropna(how="all", axis=1).drop(["num", "issues"], axis=1) for col in cols: pre, col_name = val_up3.extract_col_name(col) col_ind = self.grid_frame.grid.col_labels.index(col_name) self.grid_frame.grid.paint_invalid_cell(row, col_ind, skip_cell=skip_cell_render) current_label = self.grid_frame.msg_text.GetLabel() if len(missing_columns): col_string = "You are missing the following required columns: {}\n\n".format(", ".join(missing_columns)) else: col_string = "" if len(missing_groups): group_string = "You must have at least one column from each of the following groups: {}\n\n".format(", ".join(missing_groups)) else: group_string = "" # add_text = """{}{}{}""".format(col_string, group_string, row_string) self.grid_frame.msg_text.SetLabel(add_text) #self.on_finish_change_dir(self.change_dir_dialog) self.grid_frame.do_fit(None) del wait
def on_btn_upload(self, event): """ Try to run upload_magic. Open validation mode if the upload file has problems. """ if not self.check_for_uncombined_files(): return outstring = "upload_magic.py" print("-I- running python script:\n %s" % (outstring)) wait = wx.BusyInfo("Please wait, working...") wx.SafeYield() success_responses = ['200', 200, '201', 201, True] if 'measurements' in self.contribution.tables: self.contribution.tables['measurements'].add_measurement_names() upload_file, val_response, dummy1, dummy2 = ipmag.upload_magic( concat=False, input_dir_path=self.WD, dir_path=self.WD) del wait if val_response == "no 3.0 files found, upload file not created": pw.simple_warning( "No 3.0 files were found in your directory, so no upload could be created!" ) return status = val_response['status'] if not status: pw.simple_warning( "Oops, something went wrong with validating on the server.\n{}\nTry again later or submit a bug report." .format(val_response['warnings'])) return validation_errors = val_response['validation'] if (not validation_errors['warnings']) and ( not validation_errors['errors']): text = "You are ready to upload!\n{} was generated in {}".format( os.path.split(upload_file)[1], self.WD) dlg = pw.ChooseOne(self, "Go to MagIC for uploading", "Not ready yet", text, "Saved") dlg.Centre() result = dlg.ShowModal() if result == wx.ID_OK: dlg.Destroy() if result == wx.ID_YES: pw.on_database_upload(None) return # there were problems, so display validation text = "There were some problems with the creation of your upload file.\nSee Terminal/message window for details" dlg = wx.MessageDialog(self, caption="Error", message=text, style=wx.OK) dlg.Centre() result = dlg.ShowModal() # TODO: get the error-y business formatted into a dict of lists of dicts from programs import magic_gui self.Disable() self.Hide() self.magic_gui_frame = magic_gui.MainFrame( self.WD, dmodel=self.data_model, title="Validations", contribution=self.contribution, errors=validation_errors['errors']) self.magic_gui_frame.Centre() self.magic_gui_frame.Show() self.magic_gui_frame.highlight_problems() # bind that button to quitting magic gui and re-enabling Pmag GUI self.magic_gui_frame.Bind(wx.EVT_BUTTON, self.on_end_validation, self.magic_gui_frame.return_btn) # do binding so that closing/quitting re-opens the main frame self.magic_gui_frame.Bind(wx.EVT_CLOSE, self.on_end_validation) # this makes it work with only the validation window open self.magic_gui_frame.Bind( wx.EVT_MENU, lambda event: self.menubar.on_quit(event, self.magic_gui_frame), self.magic_gui_frame.menubar.file_quit) # this makes it work if an additional grid is open self.Bind( wx.EVT_MENU, lambda event: self.menubar.on_quit(event, self.magic_gui_frame), self.magic_gui_frame.menubar.file_quit)
def test_busyinfo1(self): busy = wx.BusyInfo('This is a busy info message') self.waitFor(250) del busy
def Sauvegarder(self): """ Sauvegarde des attestations """ # Demande la confirmation de sauvegarde dlg = wx.MessageDialog(self, _(u"Souhaitez-vous mémoriser les attestations ?\n\n(Cliquez NON si c'était juste un test sinon cliquez OUI)"), _(u"Sauvegarde"), wx.YES_NO|wx.YES_DEFAULT|wx.CANCEL|wx.ICON_INFORMATION) reponse = dlg.ShowModal() dlg.Destroy() if reponse != wx.ID_YES : return dlgAttente = wx.BusyInfo(_(u"Sauvegarde des attestations en cours..."), None) if 'phoenix' not in wx.PlatformInfo: wx.Yield() DB = GestionDB.DB() try : for IDcompte_payeur, dictCompte in self.donnees.items() : if dictCompte["select"] == True : numero = dictCompte["num_attestation"] IDfamille = dictCompte["IDfamille"] listePrestations = dictCompte["listePrestations"] total = dictCompte["total"] regle = dictCompte["ventilation"] solde = total - regle # Liste des activités texteActivites = "" for IDactivite in self.listeActivites : texteActivites += "%d;" % IDactivite if len(self.listeActivites) > 0 : texteActivites = texteActivites[:-1] # Liste des individus texteIndividus = "" for IDindividu in list(dictCompte["individus"].keys()) : texteIndividus += "%d;" % IDindividu if len(list(dictCompte["individus"].keys())) > 0 : texteIndividus = texteIndividus[:-1] IDutilisateur = UTILS_Identification.GetIDutilisateur() # Sauvegarde de la facture listeDonnees = [ ("numero", numero), ("IDfamille", IDfamille), ("date_edition", str(datetime.date.today())), ("activites", texteActivites), ("individus", texteIndividus), ("IDutilisateur", IDutilisateur), ("date_debut", str(self.date_debut)), ("date_fin", str(self.date_fin)), ("total", float(total)), ("regle", float(regle)), ("solde", float(solde)), ] IDattestation = DB.ReqInsert("attestations", listeDonnees) # Mémorisation de l'action dans l'historique UTILS_Historique.InsertActions([{ "IDfamille" : IDfamille, "IDcategorie" : 27, "action" : _(u"Edition d'une attestation de présence pour la période du %s au %s pour un total de %.02f ¤ et un solde de %.02f ¤") % (DateEngFr(str(self.date_debut)), DateEngFr(str(self.date_fin)), total, solde), },]) DB.Close() del dlgAttente except Exception as err: DB.Close() del dlgAttente traceback.print_exc(file=sys.stdout) dlg = wx.MessageDialog(self, _(u"Désolé, le problème suivant a été rencontré dans la sauvegarde des attestations : \n\n%s") % err, _(u"Erreur"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return False
class Cotisation(): def __init__(self): """ Récupération de toutes les données de base """ DB = GestionDB.DB() # Récupération des infos sur l'organisme req = """SELECT nom, rue, cp, ville, tel, fax, mail, site, num_agrement, num_siret, code_ape FROM organisateur WHERE IDorganisateur=1;""" DB.ExecuterReq(req) listeDonnees = DB.ResultatReq() self.dictOrganisme = {} for nom, rue, cp, ville, tel, fax, mail, site, num_agrement, num_siret, code_ape in listeDonnees : self.dictOrganisme["nom"] = nom self.dictOrganisme["rue"] = rue self.dictOrganisme["cp"] = cp if ville != None : ville = ville.capitalize() self.dictOrganisme["ville"] = ville self.dictOrganisme["tel"] = tel self.dictOrganisme["fax"] = fax self.dictOrganisme["mail"] = mail self.dictOrganisme["site"] = site self.dictOrganisme["num_agrement"] = num_agrement self.dictOrganisme["num_siret"] = num_siret self.dictOrganisme["code_ape"] = code_ape DB.Close() # Get noms Titulaires et individus self.dictTitulaires = UTILS_Titulaires.GetTitulaires() self.dictIndividus = UTILS_Titulaires.GetIndividus() # Récupération des infos de base individus et familles self.infosIndividus = UTILS_Infos_individus.Informations() # Récupération des questionnaires self.Questionnaires = UTILS_Questionnaires.ChampsEtReponses(type="famille") def Supprime_accent(self, texte): liste = [ (u"é", u"e"), (u"è", u"e"), (u"ê", u"e"), (u"ë", u"e"), (u"à", u"a"), (u"û", u"u"), (u"ô", u"o"), (u"ç", u"c"), (u"î", u"i"), (u"ï", u"i"),] for a, b in liste : texte = texte.replace(a, b) texte = texte.replace(a.upper(), b.upper()) return texte def EcritStatusbar(self, texte=u""): try : topWindow = wx.GetApp().GetTopWindow() topWindow.SetStatusText(texte) except : pass def GetDonneesImpression(self, listeCotisations=[]): """ Impression des factures """ dlgAttente = wx.BusyInfo(_(u"Recherche des données..."), None) wx.Yield() # Récupère les données de la facture if len(listeCotisations) == 0 : conditions = "()" elif len(listeCotisations) == 1 : conditions = "(%d)" % listeCotisations[0] else : conditions = str(tuple(listeCotisations)) DB = GestionDB.DB() # Récupération des activités req = """SELECT IDactivite, nom, abrege FROM activites ORDER BY date_fin DESC;""" DB.ExecuterReq(req) listeTemp = DB.ResultatReq() dictActivites = {} for IDactivite, nom, abrege in listeTemp : dictTemp = {"IDactivite":IDactivite, "nom":nom, "abrege":abrege} dictActivites[IDactivite] = dictTemp # Récupère les prestations dictFacturation = {} req = """SELECT IDcotisation, SUM(montant) FROM prestations LEFT JOIN cotisations ON cotisations.IDprestation = prestations.IDprestation WHERE cotisations.IDcotisation IN %s GROUP BY cotisations.IDcotisation;""" % conditions DB.ExecuterReq(req) listePrestations = DB.ResultatReq() for IDcotisation, montant in listePrestations : dictFacturation[IDcotisation] = {"montant":montant, "ventilation":0.0, "dateReglement":None,"modeReglement":None} # Récupère la ventilation req = """SELECT IDcotisation, SUM(ventilation.montant), MIN(reglements.date), MIN(modes_reglements.label) FROM ventilation LEFT JOIN prestations ON prestations.IDprestation = ventilation.IDprestation LEFT JOIN cotisations ON cotisations.IDprestation = ventilation.IDprestation LEFT JOIN reglements ON reglements.IDreglement = ventilation.IDreglement LEFT JOIN modes_reglements ON modes_reglements.IDmode = reglements.IDmode WHERE cotisations.IDcotisation IN %s GROUP BY cotisations.IDcotisation;""" % conditions DB.ExecuterReq(req) listeVentilations = DB.ResultatReq() for IDcotisation, ventilation, dateReglement, modeReglement in listeVentilations : if dictFacturation.has_key(IDcotisation) : dictFacturation[IDcotisation]["ventilation"] = ventilation dictFacturation[IDcotisation]["dateReglement"] = dateReglement dictFacturation[IDcotisation]["modeReglement"] = modeReglement # Recherche les cotisations req = """ SELECT cotisations.IDcotisation, cotisations.IDfamille, cotisations.IDindividu, cotisations.IDtype_cotisation, cotisations.IDunite_cotisation, cotisations.date_saisie, cotisations.IDutilisateur, cotisations.date_creation_carte, cotisations.numero, cotisations.IDdepot_cotisation, cotisations.date_debut, cotisations.date_fin, cotisations.IDprestation, types_cotisations.nom, types_cotisations.type, types_cotisations.carte, unites_cotisations.nom, comptes_payeurs.IDcompte_payeur, cotisations.observations, cotisations.activites FROM cotisations LEFT JOIN types_cotisations ON types_cotisations.IDtype_cotisation = cotisations.IDtype_cotisation LEFT JOIN unites_cotisations ON unites_cotisations.IDunite_cotisation = cotisations.IDunite_cotisation LEFT JOIN comptes_payeurs ON comptes_payeurs.IDfamille = cotisations.IDfamille WHERE cotisations.IDcotisation IN %s ORDER BY cotisations.date_saisie ;""" % conditions DB.ExecuterReq(req) listeDonnees = DB.ResultatReq() DB.Close() if len(listeDonnees) == 0 : del dlgAttente return False # Création des dictRappels dictDonnees = {} dictChampsFusion = {} for item in listeDonnees : IDcotisation = item[0] IDfamille = item[1] IDindividu = item[2] IDtype_cotisation = item[3] IDunite_cotisation = item[4] date_saisie = UTILS_Dates.DateEngEnDateDD(item[5]) IDutilisateur = item[6] date_creation_carte = item[7] numero = item[8] IDdepot_cotisation = item[9] date_debut = UTILS_Dates.DateEngEnDateDD(item[10]) date_fin = UTILS_Dates.DateEngEnDateDD(item[11]) IDprestation = item[12] nomTypeCotisation = item[13] typeTypeCotisation = item[14] typeHasCarte = item[15] nomUniteCotisation = item[16] IDcompte_payeur = item[17] observations = item[18] activites = item[19] if activites == None : activites = "" # Activités texte = "" if len(activites) > 0 : listeTemp = [] listeIDactivites = UTILS_Divers.ConvertChaineEnListe(activites) for IDactivite in listeIDactivites : if dictActivites.has_key(IDactivite) : nomActivite = dictActivites[IDactivite]["nom"] listeTemp.append(nomActivite) if len(listeTemp) > 0 : texte = ", ".join(listeTemp) activites = texte nomCotisation = u"%s - %s" % (nomTypeCotisation, nomUniteCotisation) # Type if typeTypeCotisation == "famille" : typeStr = _(u"Cotisation familiale") else: typeStr = _(u"Cotisation individuelle") # Dépôt if IDdepot_cotisation == None : depotStr = _(u"Non déposée") else: depotStr = _(u"Dépôt n°%d") % IDdepot_cotisation # Nom des titulaires de famille beneficiaires = "" rue = "" cp = "" ville = "" if IDfamille != None : beneficiaires = self.dictTitulaires[IDfamille]["titulairesAvecCivilite"] rue = self.dictTitulaires[IDfamille]["adresse"]["rue"] cp = self.dictTitulaires[IDfamille]["adresse"]["cp"] ville = self.dictTitulaires[IDfamille]["adresse"]["ville"] if IDindividu != None and self.dictIndividus.has_key(IDindividu) : beneficiaires = self.dictIndividus[IDindividu]["nom_complet"] rue = self.dictIndividus[IDindividu]["rue"] cp = self.dictIndividus[IDindividu]["cp"] ville = self.dictIndividus[IDindividu]["ville"] # Famille if IDfamille != None : nomTitulaires = self.dictTitulaires[IDfamille]["titulairesAvecCivilite"] famille_rue = self.dictTitulaires[IDfamille]["adresse"]["rue"] famille_cp = self.dictTitulaires[IDfamille]["adresse"]["cp"] famille_ville = self.dictTitulaires[IDfamille]["adresse"]["ville"] else : nomTitulaires = "Famille inconnue" famille_rue = "" famille_cp = "" famille_ville = "" # Facturation montant = 0.0 ventilation = 0.0 dateReglement = None modeReglement = None if dictFacturation.has_key(IDcotisation): montant = dictFacturation[IDcotisation]["montant"] ventilation = dictFacturation[IDcotisation]["ventilation"] dateReglement = dictFacturation[IDcotisation]["dateReglement"] modeReglement = dictFacturation[IDcotisation]["modeReglement"] solde = float(FloatToDecimal(montant) - FloatToDecimal(ventilation)) montantStr = u"%.02f %s" % (montant, SYMBOLE) regleStr = u"%.02f %s" % (ventilation, SYMBOLE) soldeStr = u"%.02f %s" % (solde, SYMBOLE) montantStrLettres = UTILS_Conversion.trad(montant, MONNAIE_SINGULIER, MONNAIE_DIVISION) regleStrLettres = UTILS_Conversion.trad(ventilation, MONNAIE_SINGULIER, MONNAIE_DIVISION) soldeStrLettres = UTILS_Conversion.trad(solde, MONNAIE_SINGULIER, MONNAIE_DIVISION) # Mémorisation des données dictDonnee = { "select" : True, "{IDCOTISATION}" : str(IDcotisation), "{IDTYPE_COTISATION}" : str(IDtype_cotisation), "{IDUNITE_COTISATION}" : str(IDunite_cotisation), "{DATE_SAISIE}" : UTILS_Dates.DateDDEnFr(date_saisie), "{IDUTILISATEUR}" : str(IDutilisateur), "{DATE_CREATION_CARTE}" : UTILS_Dates.DateDDEnFr(date_creation_carte), "{NUMERO_CARTE}" : numero, "{IDDEPOT_COTISATION}" : str(IDdepot_cotisation), "{DATE_DEBUT}" : UTILS_Dates.DateDDEnFr(date_debut), "{DATE_FIN}" : UTILS_Dates.DateDDEnFr(date_fin), "{IDPRESTATION}" : str(IDprestation), "{NOM_TYPE_COTISATION}" : nomTypeCotisation, "{NOM_UNITE_COTISATION}" : nomUniteCotisation, "{COTISATION_FAM_IND}" : typeStr, "{IDCOMPTE_PAYEUR}" : str(IDcompte_payeur), "{NOM_COTISATION}" : nomCotisation, "{NOM_DEPOT}" : depotStr, "{MONTANT_FACTURE}" : montantStr, "{MONTANT_REGLE}" : regleStr, "{SOLDE_ACTUEL}" : soldeStr, "{MONTANT_FACTURE_LETTRES}" : montantStrLettres.capitalize(), "{MONTANT_REGLE_LETTRES}" : regleStrLettres.capitalize(), "{SOLDE_ACTUEL_LETTRES}" : soldeStrLettres.capitalize(), "{DATE_REGLEMENT}" : UTILS_Dates.DateDDEnFr(dateReglement), "{MODE_REGLEMENT}" : modeReglement, "{ACTIVITES}" : activites, "{NOTES}" : observations, "{IDINDIVIDU}" : IDindividu, "{BENEFICIAIRE_NOM}" : beneficiaires, "{BENEFICIAIRE_RUE}" : rue, "{BENEFICIAIRE_CP}" : cp, "{BENEFICIAIRE_VILLE}" : ville, "{IDFAMILLE}" : str(IDfamille), "{FAMILLE_NOM}" : nomTitulaires, "{FAMILLE_RUE}" : famille_rue, "{FAMILLE_CP}" : famille_cp, "{FAMILLE_VILLE}" : famille_ville, "{ORGANISATEUR_NOM}" : self.dictOrganisme["nom"], "{ORGANISATEUR_RUE}" : self.dictOrganisme["rue"], "{ORGANISATEUR_CP}" : self.dictOrganisme["cp"], "{ORGANISATEUR_VILLE}" : self.dictOrganisme["ville"], "{ORGANISATEUR_TEL}" : self.dictOrganisme["tel"], "{ORGANISATEUR_FAX}" : self.dictOrganisme["fax"], "{ORGANISATEUR_MAIL}" : self.dictOrganisme["mail"], "{ORGANISATEUR_SITE}" : self.dictOrganisme["site"], "{ORGANISATEUR_AGREMENT}" : self.dictOrganisme["num_agrement"], "{ORGANISATEUR_SIRET}" : self.dictOrganisme["num_siret"], "{ORGANISATEUR_APE}" : self.dictOrganisme["code_ape"], "{DATE_EDITION_COURT}" : UTILS_Dates.DateDDEnFr(datetime.date.today()), "{DATE_EDITION_LONG}" : UTILS_Dates.DateComplete(datetime.date.today()), } # Ajoute les informations de base individus et familles if IDindividu != None : dictDonnee.update(self.infosIndividus.GetDictValeurs(mode="individu", ID=IDindividu, formatChamp=True)) if IDfamille != None : dictDonnee.update(self.infosIndividus.GetDictValeurs(mode="famille", ID=IDfamille, formatChamp=True)) # Ajoute les réponses des questionnaires for dictReponse in self.Questionnaires.GetDonnees(IDfamille) : dictDonnee[dictReponse["champ"]] = dictReponse["reponse"] if dictReponse["controle"] == "codebarres" : dictDonnee["{CODEBARRES_QUESTION_%d}" % dictReponse["IDquestion"]] = dictReponse["reponse"] dictDonnees[IDcotisation] = dictDonnee # Champs de fusion pour Email dictChampsFusion[IDcotisation] = {} for key, valeur in dictDonnee.iteritems() : if key[0] == "{" : dictChampsFusion[IDcotisation][key] = valeur del dlgAttente return dictDonnees, dictChampsFusion def Impression(self, listeCotisations=[], nomDoc=None, afficherDoc=True, dictOptions=None, repertoire=None, repertoireTemp=False): """ Impression des factures """ # Récupération des données à partir des IDrappel resultat = self.GetDonneesImpression(listeCotisations) if resultat == False : return False dictCotisations, dictChampsFusion = resultat # Récupération des paramètres d'affichage if dictOptions == None : if afficherDoc == False : dlg = DLG_Apercu_cotisation.Dialog(None, titre=_(u"Sélection des paramètres de la cotisation"), intro=_(u"Sélectionnez ici les paramètres d'affichage de la cotisation.")) dlg.bouton_ok.SetImageEtTexte("Images/32x32/Valider.png", _("Ok")) else : dlg = DLG_Apercu_cotisation.Dialog(None) if dlg.ShowModal() == wx.ID_OK: dictOptions = dlg.GetParametres() dlg.Destroy() else : dlg.Destroy() return False # Création des PDF à l'unité def CreationPDFunique(repertoireCible=""): dictPieces = {} dlgAttente = wx.BusyInfo(_(u"Génération des cotisations à l'unité au format PDF..."), None) wx.Yield() try : index = 0 for IDcotisation, dictCotisation in dictCotisations.iteritems() : if dictCotisation["select"] == True : numero_cotisation = str(dictCotisation["{NUMERO_CARTE}"]) nomTitulaires = self.Supprime_accent(dictCotisation["{FAMILLE_NOM}"]) nomFichier = _(u"Cotisation %s - %s") % (numero_cotisation, nomTitulaires) cheminFichier = u"%s/%s.pdf" % (repertoireCible, nomFichier) dictComptesTemp = {IDcotisation : dictCotisation} self.EcritStatusbar(_(u"Edition de la cotisation %d/%d : %s") % (index, len(dictCotisation), nomFichier)) UTILS_Impression_cotisation.Impression(dictComptesTemp, dictOptions, IDmodele=dictOptions["IDmodele"], ouverture=False, nomFichier=cheminFichier) dictPieces[IDcotisation] = cheminFichier index += 1 self.EcritStatusbar("") del dlgAttente return dictPieces except Exception, err: del dlgAttente traceback.print_exc(file=sys.stdout) dlg = wx.MessageDialog(None, _(u"Désolé, le problème suivant a été rencontré dans l'édition des cotisations : \n\n%s") % err, _(u"Erreur"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return False # Répertoire souhaité par l'utilisateur if repertoire != None : resultat = CreationPDFunique(repertoire) if resultat == False : return False # Répertoire TEMP (pour Emails) dictPieces = {} if repertoireTemp == True : dictPieces = CreationPDFunique(UTILS_Fichiers.GetRepTemp()) if dictPieces == False : return False # Fabrication du PDF global if repertoireTemp == False : dlgAttente = wx.BusyInfo(_(u"Création du PDF des cotisations..."), None) wx.Yield() self.EcritStatusbar(_(u"Création du PDF des cotisations en cours... veuillez patienter...")) try : UTILS_Impression_cotisation.Impression(dictCotisations, dictOptions, IDmodele=dictOptions["IDmodele"], ouverture=afficherDoc, nomFichier=nomDoc) self.EcritStatusbar("") del dlgAttente except Exception, err: del dlgAttente traceback.print_exc(file=sys.stdout) dlg = wx.MessageDialog(None, u"Désolé, le problème suivant a été rencontré dans l'édition des cotisations : \n\n%s" % err, _(u"Erreur"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return False