def test_comtypes(self):
        from comtypes.client import CreateObject
        d = CreateObject("TestDispServerLib.TestDispServer")

        self.assertEqual(d.eval("3.14"), 3.14)
        self.assertEqual(d.eval("1 + 2"), 3)
        self.assertEqual(d.eval("[1 + 2, 'foo', None]"), (3, 'foo', None))

        self.assertEqual(d.eval2("3.14"), 3.14)
        self.assertEqual(d.eval2("1 + 2"), 3)
        self.assertEqual(d.eval2("[1 + 2, 'foo', None]"), (3, 'foo', None))

        d.eval("__import__('comtypes.client').client.CreateObject('MSScriptControl.ScriptControl')")

        self.assertEqual(d.EVAL("3.14"), 3.14)
        self.assertEqual(d.EVAL("1 + 2"), 3)
        self.assertEqual(d.EVAL("[1 + 2, 'foo', None]"), (3, 'foo', None))

        self.assertEqual(d.EVAL2("3.14"), 3.14)
        self.assertEqual(d.EVAL2("1 + 2"), 3)
        self.assertEqual(d.EVAL2("[1 + 2, 'foo', None]"), (3, 'foo', None))

        server_id = d.eval("id(self)")
        self.assertEqual(d.id, server_id)
        self.assertEqual(d.ID, server_id)

        self.assertEqual(d.Name, "spam, spam, spam")
        self.assertEqual(d.nAME, "spam, spam, spam")

        d.SetName("foo bar")
        self.assertEqual(d.Name, "foo bar")

        d.name = "blah"
        self.assertEqual(d.Name, "blah")
def test_microsoft_excel():
    xl = CreateObject("Excel.Application")
    xl.Visible = True
    wb = xl.Workbooks.Add()
    sheet = wb.ActiveSheet
    sheet.Range["A1"].Value2 = "Test passed"
    wb.Close(SaveChanges = False)
    xl.Quit()
Beispiel #3
0
 def test(self):
     d = CreateObject("MSScriptControl.ScriptControl")
     d.Language = "jscript"
     d.AddCode('function x() { return [3, "spam foo", 3.14]; };')
     result = d.Run("x", [])
     self.failUnless(isinstance(result,
                                comtypes.client.lazybind.Dispatch))
     self.failUnlessEqual(result[0], 3)
     self.failUnlessEqual(result[1], "spam foo")
     self.failUnlessEqual(result[2], 3.14)
     self.assertRaises(IndexError, lambda: result[3])
        def test_jscript(self):
            engine = CreateObject("MSScriptControl.ScriptControl")
            engine.Language = "JScript"
            # strange.
            #
            # engine.Eval returns a VARIANT containing a dispatch pointer.
            #
            # The dispatch pointer exposes this typeinfo (the number of
            # dispproperties varies, depending on the length of the list we pass
            # to Eval):
            #
            #class JScriptTypeInfo(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDispatch):
            #    'JScript Type Info'
            #    _iid_ = GUID('{C59C6B12-F6C1-11CF-8835-00A0C911E8B2}')
            #    _idlflags_ = []
            #    _methods_ = []
            #JScriptTypeInfo._disp_methods_ = [
            #    DISPPROPERTY([dispid(9522932)], VARIANT, '0'),
            #    DISPPROPERTY([dispid(9522976)], VARIANT, '1'),
            #]
            #
            # Although the exact interface members vary, the guid stays
            # the same. Don't think that's allowed by COM standards - is
            # this a bug in the MSScriptControl?
            #
            # What's even more strange is that the returned dispatch
            # pointer can't be QI'd for this interface!  So it seems the
            # typeinfo is really a temporary thing.

            res = engine.Eval("[1, 2, 3, 4]")._comobj

            # comtypes.client works around this bug, by not trying to
            # high-level wrap the dispatch pointer because QI for the real
            # interface fails.
            self.failUnlessEqual(type(res), POINTER(IDispatch))

            tinfo_1 = engine.Eval("[1, 2, 3]")._comobj.GetTypeInfo(0)
            tinfo_2 = engine.Eval("[1, 2, 3, 4]")._comobj.GetTypeInfo(0)
            tinfo_3 = engine.Eval("[1, 2, 3, 4, 5]")._comobj.GetTypeInfo(0)


            self.failUnlessEqual(tinfo_1.GetTypeAttr().cVars, 3)
            self.failUnlessEqual(tinfo_2.GetTypeAttr().cVars, 4)
            self.failUnlessEqual(tinfo_3.GetTypeAttr().cVars, 5)

            # These tests simply describe the current behaviour ;-)
            self.failUnlessEqual(tinfo_1.GetTypeAttr().guid,
                                 tinfo_1.GetTypeAttr().guid)

            ## print (res[0], res[1], res[2])
            ## print len(res)

            engine.Reset()
Beispiel #5
0
    def test_nondefault_eventinterface(self):
        sink = EventSink()
        ie = CreateObject("InternetExplorer.Application")
        import comtypes.gen.SHDocVw as mod
        conn = GetEvents(ie, sink, interface=mod.DWebBrowserEvents)

        ie.Visible = True
        ie.Navigate2(Flags=0, URL="http://docs.python.org/")
        import time
        for i in range(50):
            PumpWaitingMessages()
            time.sleep(0.1)
        ie.Visible = False
        ie.Quit()

        self.failUnlessEqual(sink._events, ['BeforeNavigate', 'NavigateComplete'])
        del ie
    def test(self, dynamic=False):
        engine = CreateObject("SAPI.SpVoice", dynamic=dynamic)
        stream = CreateObject("SAPI.SpFileStream", dynamic=dynamic)
        from comtypes.gen import SpeechLib

        fd, fname = tempfile.mkstemp(suffix=".wav")
        os.close(fd)

        stream.Open(fname, SpeechLib.SSFMCreateForWrite)

        # engine.AudioStream is a propputref property
        engine.AudioOutputStream = stream
        self.failUnlessEqual(engine.AudioOutputStream, stream)
        engine.speak("Hello, World", 0)
        stream.Close()
        filesize = os.stat(fname).st_size
        self.failUnless(filesize > 100, "filesize only %d bytes" % filesize)
        os.unlink(fname)
Beispiel #7
0
    def test_default_eventinterface(self):
        sink = EventSink()
        ie = CreateObject("InternetExplorer.Application")
        conn = GetEvents(ie, sink=sink)
        ie.Visible = True
        ie.Navigate2(URL="http://docs.python.org/", Flags=0)
        import time
        for i in range(50):
            PumpWaitingMessages()
            time.sleep(0.1)
        ie.Visible = False
        ie.Quit()

        self.failUnlessEqual(sink._events, ['OnVisible', 'BeforeNavigate2',
                                            'NavigateComplete2', 'DocumentComplete',
                                            'OnVisible'])

        del ie
        del conn
Beispiel #8
0
 def __init__(self, fileName):
     self.msdia = GetModule("msdia140.dll")
     self.dataSource = CreateObject(self.msdia.DiaSource, interface=self.msdia.IDiaDataSource)
     ext = fileName.split(os.path.extsep)[-1]
     if 'pdb' == ext.lower():
         self.dataSource.loadDataFromPdb(fileName)
     else:
         symPath = os.environ.get('_NT_SYMBOL_PATH', 'SRV**\\\\symbols\\symbols')
         self.dataSource.loadDataForExe(fileName, symPath, None)
     self.session = self.dataSource.openSession()
     self.globalScope = self.session.globalScope
def getLength(text,wavfn):
    '''Get the length, in seconds, of a wav file produced by applying a
    text-to-speech engine to the given text.'''
    with tempfile.NamedTemporaryFile() as f:
        wavfn = f.name

    engine = CreateObject("SAPI.SpVoice")
    stream = CreateObject("SAPI.SpFileStream")
    stream.Open(wavfn, comtypes.gen.SpeechLib.SSFMCreateForWrite)
    engine.AudioOutputStream = stream
    engine.speak(text)
    stream.Close()

    with contextlib.closing(wave.open(wavfn,'r')) as f:
        frames = f.getnframes()
        rate = f.getframerate()
        duration = frames / float(rate)

    os.remove(wavfn)
    return duration
Beispiel #10
0
 def _add_required_sessions(self):
     for soft_mod_name, soft_mod in self.software_modules.iteritems():
         required_name = 'pyivi_' + soft_mod_name
         if required_name not in self._logical_names.keys():
             new_log_name = CreateObject("IviConfigServer.IviLogicalName",
                  interface=gen.IVICONFIGSERVERLib.IIviLogicalName)
             new_log_name.Name = required_name
             if required_name not in self._sessions.keys():
                 new_session = CreateObject("IviConfigServer.IviDriverSession")
                 new_session.QueryInterface(gen.IVICONFIGSERVERLib.IIviDriverSession)
                 new_session.Name = required_name
                 new_session.SoftwareModule = soft_mod._soft_mod
                 self._add_session(new_session)
             else:
                 new_session = self._sessions[required_name]._session
             new_log_name.Session = new_session
             self._add_logical_name(new_log_name)
     self._config_store.Serialize(self._config_store.MasterLocation)
    def test(self, dynamic=False):
        d = CreateObject("Scripting.Dictionary", dynamic=dynamic)
        s = CreateObject("TestComServerLib.TestComServer", dynamic=dynamic)
        s.name = "the value"

        # This calls propputref, since we assign an Object
        d.Item["object"] = s
        # This calls propput, since we assing a Value
        d.Item["value"] = s.name

        self.failUnlessEqual(d.Item["object"], s)
        self.failUnlessEqual(d.Item["object"].name, "the value")
        self.failUnlessEqual(d.Item["value"], "the value")

        # Changing the default property of the object
        s.name = "foo bar"
        self.failUnlessEqual(d.Item["object"], s)
        self.failUnlessEqual(d.Item["object"].name, "foo bar")
        self.failUnlessEqual(d.Item["value"], "the value")

        # This also calls propputref since we assign an Object
        d.Item["var"] = VARIANT(s)
        self.failUnlessEqual(d.Item["var"], s)
Beispiel #12
0
    def deisotope_scan(self,
                       scan,
                       tolerance_da=0.0025,
                       tolerance_ppm=7,
                       max_charge=None,
                       require_peptide_profile=False):
        """
        The Agilent MassHunter DAC has the neat feature of including its own
        deisotoping algorithm!  This function uses that to return the specified
        scan in deisotoped form.
        
        tolerance_da (Daltons) and tolerance_ppm (Parts-per-million) are
        ADDED TOGETHER to obtain the total tolerance value for each peak.
        
        max_charge can be set to an integer to only consider isotopic envelopes of
        charge equal to or less; 'None' performs no charge filtering.
        
        require_peptide_profile filters based on isotopic sequences having
        the relative intensity profile caused by standard relative isotopic
        abundances.
        """
        scanObj = self.source.GetSpectrum_6(scan)

        deisoFilter = CreateObject(
            r'Agilent.MassSpectrometry.DataAnalysis.MsdrChargeStateAssignmentFilter'
        )
        if not (tolerance_da == 0.0025 and tolerance_ppm == 7
                and not (max_charge or require_peptide_profile)):

            deisoFilter.AbsoluteTolerance = tolerance_da
            if max_charge:
                deisoFilter.LimitMaxChargeState = max_charge
            deisoFilter.RelativeTolerance = tolerance_ppm
            deisoFilter.RequirePeptideLikeAbundanceProfile = require_peptide_profile

        self.source.Deisotope(
            scanObj,
            deisoFilter)  # Void type, not even a success return value.

        return list(zip(scanObj.XArray, scanObj.YArray))
class RoboRealmInterface:
    def __init__(self, rr_x=1000, rr_y=1000):
        self.rr = CreateObject("RoboRealm.API.1")
        self.rr_x = rr_x
        self.rr_y = rr_y

    def connect(self):
        self.rr.Startup()

    def get_robot_positions(self):

        robots_id = [
            str(name.strip()[1:5])
            for name in self.rr.GetArrayVariable("FIDUCIAL_NAME_ARRAY")[0]
        ]
        robots_x = self.rr.GetFloatArrayVariable("FIDUCIAL_X_COORD_ARRAY")[0]
        robots_y = self.rr.GetFloatArrayVariable("FIDUCIAL_Y_COORD_ARRAY")[0]
        robots_orient = self.rr.GetFloatArrayVariable(
            "FIDUCIAL_ORIENTATION_ARRAY")[0]
        if (len(robots_id) is not len(robots_x)) or (len(robots_id) is not len(
                robots_y)) or (len(robots_y) is not len(robots_orient)):
            print("ERROR: API data length mismatch: ({0},{1},{2},{3})".format(
                len(robots_id), len(robots_x), len(robots_y),
                len(robots_orient)))
            return {}
        res = {}
        for i in range(len(robots_id)):
            res[robots_id[i]] = (robots_x[i], robots_y[i], robots_orient[i])
#        print ("RoboRealm Data")
#        print res
#        print ('')
        return res

    def wait_image(self):
        self.rr.WaitImage()

    def disconnect(self):
        self.rr.Disconnect()
def process(PA):
	global ActiveWindow, Shapes, Word, TRs_all, xl, Visio
	global RESULTS
	# Bien gérer les erreurs
	try:

		# ouvrir le fichier excel et faire les initialisations de coutume
		xl = CreateObject("Excel.application")
		xl.Visible = False
		xl.DisplayAlerts = False
		PA_wb = xl.Workbooks.Open(PA)
		PA_wb.Sheets("synoptique-bilan µmodules").Select()

		# dans la sheet visée, détecter tout les objets OLE (qui seront 
		# normalement tous des déssins visio)
		OLEObjects = PA_wb.Sheets("synoptique-bilan µmodules").OLEObjects()

		# pour chaque déssin ...
		for OLEObject in OLEObjects:
			# l'ouvrir dans Visio
			OLEObject.Verb(2)
			# prendre la main sur la fenêtre visio ouverte
			Visio = GetActiveObject("Visio.Application")
			# Visio.Visible = False
			Visio.DisplayAlerts = False
			ActiveWindow =  Visio.ActiveWindow
			Page = ActiveWindow.Page
			Shapes = Page.Shapes
			# Ceci est pour les déssins plutôt compliqués, après chaque sélection des PB, le script
			# les affichera et demandra de confirmer si c'est bon ou non
			msg = "Voulez confirmer le nombre de PBs après chaque sélection?\n" \
						+ "(si c'est plan assez complexe mieux vaut répondre par oui)"
			yn = ynbox(msg)
			# allons-y!
			# On extrait d'abord les infos d'entête
			for shape in Shapes:
				text = shape.Text
				if text.startswith('NRO'):
					bloc_NRO = text
				elif text.startswith('PT'):
					# certaines shapes buguent je ne sais pas pourquoi, elles n'ont pas d'utilité
					try:
						blocs_PT.append(shape)
					except:
						blocs_PT = [shape]
				elif text.startswith('PA'):
					bloc_PA = text
					# On extrait la position x du PA pour prendre toutes les TR qui sont à droite
					PA_posx = get_XY(shape)[0]
			# Les deux blocs FI et PA tout deux commencent par PT, celui de PA est plus à gauche
			# on les différenciera par leur position
			if get_XY(blocs_PT[0])[0] < get_XY(blocs_PT[1])[0]:
				FI_bloc = blocs_PT[0]
				PA_bloc = blocs_PT[1]
			else:
				FI_bloc = blocs_PT[1]
				PA_bloc = blocs_PT[0]

			PA_PT = PA_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			PMZ_PT = FI_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			CH = PA_bloc.Text.rsplit('\n')[2].replace('CH: ', '')
			NRO = extract('NRO/PMZ/PA', bloc_NRO, 'NRO')
			ADRESSE1 = ' '.join(PA_bloc.Text.rsplit('\n')[3:5])\
									.replace('Adresse: ', '')
			ADRESSE2 = ADRESSE1.rsplit('-')[0]

			# Les TRs du déssin courant
			TRs = {}

			# là ça va barder!
			for shape in Shapes:
				if shape.Text.startswith('TR'):
					# Seulement ceux qui sont plus à droite de PA
					if get_XY(shape)[0] > PA_posx:
						# Le text est un peu bizarre, il est vraiment en texte mais paraît être un
						# bytes! On doit le nettoyer
						TR_TXT = str(shape.Text.encode()).replace("b'", '').replace("'", '')
						# Extraire ne TR
						TR = TR_TXT.rsplit('FO')[0] \
							.replace('\\n', ' ') + 'FO'
						# Si ce n'est pas un TR valide, passer
						if not re.match(r'TR\s+\d{2}\s+\d{4}\s+\d+FO', TR):
							continue
						# Si ce TR n'a pas encore été enregistré dans la liste TRs, l'enregistrer
						## Initialiser la longueur à 0
						## Mettre le shape courant dans la liste "shapes"
						## Initialiser une liste vide pour les CH ou IMB ou AP qui vont avec
						## Initialiser une liste vide pour les PTs qui vont avec (pour le nommage)
						## Et initialiser une variable "0" pour le PT qui est maximum (pour le nommage)
						if TR not in TRs:
							TRs[TR] = {
								'LONG': 0,
								'SHAPES': [shape.ID],
								'CH/IMB/AP': [],
								'PTs': [],
								'maxPT': 0
								}
						# Sinon si le TR est déjà dans TRs, ajouter le shape courant à "SHAPES"
						else:
							TRs[TR]['SHAPES'].append(shape.ID)
						# Essayer d'extraire la longueur du TR courant
						try:
							TR_LONG = int(TR_TXT.rsplit('\\xe2\\x80\\x93 ')[1] \
															.replace('m', ''))
						except:
							TR_LONG = 0
						# Et incrémenter la longueur du TR global corréspondant à cette ligne
						TRs[TR]['LONG'] = TRs[TR]['LONG'] + TR_LONG
			
			# Message pour que l'utilisateur sélectionner les blocs PB pour chaque TR
			title1 = 'Sélectionnez les bloc'
			title2 = 'Confirmez la sélection'
			# Pour chaque TR dans TRs
			for TR in TRs:
				# Python n'a pas de "REDO", on hack avec un "WHILE"
				while True:
					# Sélectionner toutes les shapes de cette ligne de TR
					SelectShapes(TRs[TR]['SHAPES'])
					# Demander lui de sélectionner, quand il confirme continuer...
					if ccbox(TR, title1):
						# Une liste vide pour tout les PB dans ce TR
						CH_OR_IMB_OR_AP_all = []
						# Une liste vide pour tout les PTs dans ce TR
						PTs = []
						# Une liste vide pour tout les PBs dans ce TR
						PBs = []
						# Un message au cas où l'utilisateur aurait choisit une confirmation
						msg = "Pour " + TR + "\nVous avez sélectionné:\n"
						# Le nombre de PBs sélectionnées (pour affichage dans la confirmation)
						selected_PBs = 0
						# Au cas où il n'y aurait pas de PB valide, pas la peine de mettre une 
						# fenêtre de confirmation, supposer tout de même qu'il y'en a ...
						yn_yes = True
						# Pour chaque fenêtre sélectionnée
						for selected in ActiveWindow.Selection:
							# (certains shapes n'aiment pas qu'on appelle leur .Text!!!!)
							try:
								TEXT = str(selected.Text)
								# Prendre seulement les blocs qui commencent par "PB"
								if not TEXT.startswith('PB'):
									continue
								# Incrémenter le nombre de PBs trouvés par +1
								selected_PBs = selected_PBs + 1
								# Enregister le PB, PT, l'adresse, et le text qui peut être un:
								## Ch.XXXXX
								## IMB/XXXXX/XXXX
								## AP XXXX
								PB = TEXT.rsplit('\n')[0].rstrip()
								PT = TEXT.rsplit('\n')[2]
								ADR = TEXT.rsplit('\n')[3]
								CH_OR_IMB_OR_AP = TEXT.rsplit('\n')[4]
								# Si l'un de ces lignes ne se trouve pas à la bonne place
								if (not CH_OR_IMB_OR_AP.startswith('AP ')
									and not CH_OR_IMB_OR_AP.startswith('Ch.')
									and not CH_OR_IMB_OR_AP.startswith('IMB')):
									# Resélectionner les sélectionnés (pfff sert à rien ça!)
									SelectShapes([selected.ID])
									# Et dire qu'il y a un truc qui cloche!
									msgbox("T'as surement encore fais une connerie dans tes"
												+ "déssins, regarde ce bloc dans la ligne PT!\n"
												+ "Je devrais trouver Ch.XXXX ou AP XXXX"
												+ "ou IMB/XXXX/XXX mais j'ai trouvé\n"
												+ CH_OR_IMB_OR_AP + "\n"
												+ "Quand t'auras détécté l'erreur click sur OK")
									# Continuer ou quitter!
									cont = boolbox("Dois-je continuer ou fermer?",
																"Que faire?",
																['Continuer?', 'Fermer?'])
									if not cont:
										exit(0)
									else:
										pass
								else:
									# Sinon, préparer le message de confirmation
									msg = msg + "- " + CH_OR_IMB_OR_AP + "\n"
									# Et ajouter le CH/IMB/AP à la liste
									CH_OR_IMB_OR_AP_all.append([ADR, CH_OR_IMB_OR_AP])
									# Ajouter le PT de ce bloc à la liste PTs
									PTs.append(int(PT.replace('PT', '')))
									# Ajouter le PB de ce bloc à la liste PBs
									PBs.append(PB)
							except:
								# Si quelque chose cloche, trouver une porte de sortie!!:
								SelectShapes([selected.ID])
								msgbox("T'as surement encore fais une connerie dans tes"
										+ "déssins, regarde ce bloc dans la ligne PT!\n"
										+ "Quand t'auras détécté l'erreur click sur OK")
								cont = boolbox("Dois-je continuer ou fermer?",
												"Que faire?",
												['Continuer?', 'Fermer?'])
								# Vraiment je ne sais pas à quoi sert ce que j'ai écrit dans les 
								# 8 prochaines lignes!!!!
								if not cont:
									exit(0)
								else:
									msg = msg + "(RIEN!)"
									CH_OR_IMB_OR_AP_all = []
									PTs = []
									PBs = []
									yn_yes = False
						# S'il n'a rien sélectionné
						if not selected_PBs:
							cont = boolbox("Tu n'as rien sélectionné! Tu confirmes"
											+ " que ce n'est pas une connerie?",
											"Sélection vide!",
											['Oui vas-y', 'Comme d\'hab! Une connerie'])
							# Soit on quitte!
							if cont:
								break
							# Soit c'est délibéré et on continue
							else:
								continue

						# Si l'utilisateur avait demandé une confirmation, la montrer
						# (S'il y a eu une erreur, yn_yes est False, et pas la peine de montrer la
						# confirmation)
						if yn and yn_yes:
							msg = msg + "(" + str(selected_PBs) + " sélectionnés)"
							conf = boolbox(msg, title2, ['Confirmer?', 'Refaire?'])
							if conf:
								# Si c'est confirmé, stocher ces données pour le shape
								TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
								TRs[TR]['PTs'] = PTs
								TRs[TR]['PBs'] = PBs
								break
							else:
								pass
						# Sinon s'il n'avait pas demandé de confirmation, stocker ces données
						# directement pour le shape
						else:
							TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
							TRs[TR]['PTs'] = PTs
							TRs[TR]['PBs'] = PBs
							break
					# En cas d'erreur sortir :-(
					else:
						exit(0)
				# Il doit y avoir au moins un PT pour créer un fichier doc et xls avec le max des TRs
				if len(TRs[TR]['PTs']):
					TRs[TR]['DE_filename'] = 'DE_PT%06d' % max(TRs[TR]['PTs']) + '.doc'
					TRs[TR]['AR_filename'] = 'AR_PT%06d' % max(TRs[TR]['PTs']) + '.xls'
				# Les fichiers avec ce nom ne devront jamais voir le jour!
				else:
					TRs[TR]['DE_filename'] = 'je_ne_suis_pas_cense_exister.doc'
					TRs[TR]['AR_filename'] = 'je_ne_suis_pas_cense_exister.xls'
					# Un cas très particulier m'a forcé à ajourer la ligne suivant!
					TRs[TR]['PBs'] = []

			# Si je n'ai trouvé aucun TR, montrer un message
			if TRs == {}:
				msgbox("il n'y pas de TR valide sur ce déssin")
			# Ajouter ces TRs à TR_all
			TRs_all.append(TRs)
			# Cacher le déssin Visio
			Visio.Visible = False

		# Demander qui est le client
		xl.Visible = True
		msg = "Quel est le client pour cette fiche PA?"
		choices = ["Circet","Engie"]
		client = buttonbox(msg, choices=choices)

		# Résultat globaux pour cette fiche PA
		RESULTS[PA] = {
			'PA_REF':		bloc_PA,
			'client':		client,
			'TRs_all': 		TRs_all,
			'NRO':			NRO,
			'PMZ_PT':		PMZ_PT,
			'PA_PT':		PA_PT,
			'CH':			CH,
			'ADRESSE1':		ADRESSE1,
			'ADRESSE2':		ADRESSE2,
			'DATE':			DATE
		}

		# Quitter excel et passer à la prochaine fiche PA
		xl.Quit()
		return

	except:
		# En cas d'erreur innatendue!
		print(format_exc())
		codebox("t'as encore fais une connerie! Fais moi un screen de malheur!",
				"Erreur",
				format_exc())
		going()
Beispiel #15
0
if not os.path.exists("images"):
    os.mkdir("images")
else:
    import shutil

    shutil.rmtree("images")
    os.mkdir("images")

image_directory = pathlib.Path("images")

import comtypes.client
#comtypes.client.gen_dir = None
from comtypes.client import CreateObject

word = CreateObject("Word.Application")
word.Visible = False

from comtypes.gen import Word as constants

imagemagick = "magick.exe"

# [(file name, word image, html image)]
results = []

if __name__ == "__main__":
    if len(sys.argv) != 1:
        file_names = [pathlib.Path(p) for p in sys.argv[1:]]
    else:
        file_names = list(pathlib.Path("docs").iterdir())
Beispiel #16
0
    def test_dict(self):
        d = CreateObject("Scripting.Dictionary", dynamic=True)
        self.failUnlessEqual(type(d), Dispatch)

        # Count is a normal propget, no propput
        self.failUnlessEqual(d.Count, 0)
        self.assertRaises(AttributeError, lambda: setattr(d, "Count", -1))

        # HashVal is a 'named' propget, no propput
        ##d.HashVal

        # Add(Key, Item) -> None
        self.failUnlessEqual(d.Add("one", 1), None)
        self.failUnlessEqual(d.Count, 1)

        # RemoveAll() -> None
        self.failUnlessEqual(d.RemoveAll(), None)
        self.failUnlessEqual(d.Count, 0)

        # CompareMode: propget, propput
        # (Can only be set when dict is empty!)
        self.failUnlessEqual(d.CompareMode, 0)
        d.CompareMode = 1
        self.failUnlessEqual(d.CompareMode, 1)
        d.CompareMode = 0

        # Exists(key) -> bool
        self.failUnlessEqual(d.Exists(42), False)
        d.Add(42, "foo")
        self.failUnlessEqual(d.Exists(42), True)

        # Keys() -> array
        # Items() -> array
        self.failUnlessEqual(d.Keys(), (42,))
        self.failUnlessEqual(d.Items(), ("foo",))
        d.Remove(42)
        self.failUnlessEqual(d.Exists(42), False)
        self.failUnlessEqual(d.Keys(), ())
        self.failUnlessEqual(d.Items(), ())

        # Item[key] : propget
        d.Add(42, "foo")
        self.failUnlessEqual(d.Item[42], "foo")

        d.Add("spam", "bar")
        self.failUnlessEqual(d.Item["spam"], "bar")

        # Item[key] = value: propput, propputref
        d.Item["key"] = "value"
        self.failUnlessEqual(d.Item["key"], "value")
        d.Item[42] = 73, 48
        self.failUnlessEqual(d.Item[42], (73, 48))

        ################################################################
        # part 2, testing propput and propputref

        s = CreateObject("Scripting.Dictionary", dynamic=True)
        s.CompareMode = 42

        # This calls propputref, since we assign an Object
        d.Item["object"] = s
        # This calls propput, since we assing a Value
        d.Item["value"] = s.CompareMode

        a = d.Item["object"]
 
        self.failUnlessEqual(d.Item["object"], s)
        self.failUnlessEqual(d.Item["object"].CompareMode, 42)
        self.failUnlessEqual(d.Item["value"], 42)

        # Changing a property of the object
        s.CompareMode = 5
        self.failUnlessEqual(d.Item["object"], s)
        self.failUnlessEqual(d.Item["object"].CompareMode, 5)
        self.failUnlessEqual(d.Item["value"], 42)

        # This also calls propputref since we assign an Object
        d.Item["var"] = VARIANT(s)
        self.failUnlessEqual(d.Item["var"], s)

        # iter(d)
        keys = [x for x in d]
        self.failUnlessEqual(d.Keys(),
                             tuple([x for x in d]))

        # d[key] = value
        # d[key] -> value
        d["blah"] = "blarg"
        self.failUnlessEqual(d["blah"], "blarg")
        # d(key) -> value
        self.failUnlessEqual(d("blah"), "blarg")
def process(PA):
	global current_row, DATE
	# ouvrir le fichier excel et faire les initialisations de coutume
	xl = CreateObject("Excel.application")
	xl.Visible = False
	xl.DisplayAlerts = False
	PA_wb = xl.Workbooks.Open(PA)
	DEMANDE_wb = xl.Workbooks.Open(__DEMANDE_FILE__)
	POINTAGE_sh = PA_wb.Sheets("pointage-etude")
	CREATION_sh = DEMANDE_wb.WorkSheets.Item(1)

	all_rows = []
	demandeurs = ('INEO/', 'CIRCET/', 'CONSTRUCTEL/')
	try:
		imb_a_creer_ou_supp = POINTAGE_sh.Range("P5:P1000").SpecialCells(2)
	except:
		imb_a_creer_ou_supp = ()
	try:
		imb_a_modifier = POINTAGE_sh.Range("T5:T1000").SpecialCells(2)
	except:
		imb_a_modifier = ()

	for i, cell in list(enumerate(imb_a_creer_ou_supp)) + list(enumerate(imb_a_modifier)):
		current_row = cell.EntireRow
		if cell.Value() == "immeuble à créer" or cell.Value() == "immeuble à supprimer" or cell_value(20):
			IMB = cell_value(1)
			n_PA = cell_value(3)
			DATE = DATE
			NRO = cell_value(4)
			RIVOLI = cell_value(5)
			TYPE_LIB = cell_value(6)
			if cell_value(7) != '':
				cell_value_7 = int(cell_value(7))
			else:
				cell_value_7 = cell_value(7)
			N_VOIE = cell_value_7
			COMP_VOIE = cell_value(8)
			BATIMENT = cell_value(9)
			ADR_A_NORM = str(cell_value_7) + ' ' + str(cell_value(8)) + ' ' + str(cell_value(6))
			ADR_A_NORM = ADR_A_NORM.lstrip()
			CoordX = cell_value(17)
			CoordY = cell_value(18)
			commentaire = cell_value(20)
			if cell.Value() == "immeuble à supprimer":
				nb_el = ''
				TYPE_SITE = cell_value(11)
				NbLogementsR = ''
				NbLogementsP = ''
				ACTION = "SUPPRIMER"
			else:
				nb_el = int(cell_value(13)) + int(cell_value(14))
				TYPE_SITE = ['maison' if nb_el < 4 else 'immeuble'][0]
				NbLogementsR = int(cell_value(13))
				NbLogementsP = int(cell_value(14))
				if cell.Value() == "immeuble à créer":
					ACTION = "CREER"
				elif cell_value(20):
					ACTION = "MODIFIER"
			msg = "Quel est le demandeur pour IMB: " + IMB + "? (" + str(i+1) + "/" + str(len(list(imb_a_creer_ou_supp))) + ")"
			demandeur = buttonbox(msg, choices=demandeurs)
			all_rows.append({
					'IMB': IMB,
					'n_PA': n_PA,
					'ACTION': ACTION,
					'DATE': DATE,
					'NRO': NRO,
					'RIVOLI': RIVOLI,
					'TYPE_LIB': TYPE_LIB,
					'N_VOIE': N_VOIE,
					'COMP_VOIE': COMP_VOIE,
					'BATIMENT': BATIMENT,
					'nb_el': nb_el,
					'TYPE_SITE': TYPE_SITE,
					'ADR_A_NORM': ADR_A_NORM,
					'NbLogementsR': NbLogementsR,
					'NbLogementsP': NbLogementsP,
					'CoordX': CoordX,
					'CoordY': CoordY,
					'DEMANDEUR': demandeur
				})
			
	pp(all_rows)
	first_row = 2

	for row in all_rows:
		CREATION_sh.Range('B' + str(first_row)).Value[()] = str(row['IMB'])
		CREATION_sh.Range('A' + str(first_row)).Value[()] = str(row['n_PA'])
		CREATION_sh.Range('C' + str(first_row)).Value[()] = str(row['ACTION'])
		CREATION_sh.Range('E' + str(first_row)).Value[()] = str(row['DEMANDEUR'])
		CREATION_sh.Range('F' + str(first_row)).Value[()] = str(row['DATE'])
		CREATION_sh.Range('H' + str(first_row)).Value[()] = str(row['NRO'])
		CREATION_sh.Range('I' + str(first_row)).Value[()] = str(row['RIVOLI'])
		CREATION_sh.Range('J' + str(first_row)).Value[()] = str(row['TYPE_LIB'])
		CREATION_sh.Range('K' + str(first_row)).Value[()] = str(row['N_VOIE'])
		CREATION_sh.Range('L' + str(first_row)).Value[()] = str(row['COMP_VOIE'])
		CREATION_sh.Range('P' + str(first_row)).Value[()] = str(row['TYPE_SITE'])
		CREATION_sh.Range('Q' + str(first_row)).Value[()] = str(row['ADR_A_NORM'])
		CREATION_sh.Range('S' + str(first_row)).Value[()] = str(row['BATIMENT'])
		CREATION_sh.Range('U' + str(first_row)).Value[()] = str(row['NbLogementsR'])
		CREATION_sh.Range('V' + str(first_row)).Value[()] = str(row['NbLogementsP'])
		CREATION_sh.Range('W' + str(first_row)).Value[()] = str(row['CoordX'])
		CREATION_sh.Range('X' + str(first_row)).Value[()] = str(row['CoordY'])
		first_row = first_row + 1

	DEMANDE_wb.Save()
	# Quitter excel et passer à la prochaine fiche PA
	xl.Quit()
Beispiel #18
0
from comtypes.client import CreateObject, GetModule

#### Using the IviScope interface ####
GetModule('IviScopeTypeLib.dll')
from comtypes.gen import IviScopeLib

ivi_scope = CreateObject('Tkdpo2k3k4k.Tkdpo2k3k4k',
                         interface=IviScopeLib.IIviScope)
ivi_scope.Initialize('USB0::0x0699::0x0411::C012048::INSTR', False, False, '')

ivi_scope.Acquisition.ConfigureRecord(TimePerRecord=.1,
                                      MinNumPts=1000,
                                      AcquisitionStartTime=0)
ch1 = ivi_scope.Channels.Item('CH1')
ch1.Configure(Range=.1,
              Offset=0.1,
              Coupling=IviScopeLib.IviScopeVerticalCouplingDC,
              ProbeAttenuation=1,
              Enabled=True)

ch1.Offset = 0.05  # Channel parameters can be configured using properties

waveform = ivi_scope.Measurements.Item('CH1').ReadWaveform(
    MaxTimeMilliseconds=100)

print "Waveform :", waveform[0]
print "Time Origin :", waveform[1]
print "Time Step :", waveform[2]

#### Using the Tkdpo2k3k4k interface ####
from comtypes.gen import Tkdpo2k3k4kLib
Beispiel #19
0
import sys
from comtypes.client import CreateObject
from comtypes.safearray import safearray_as_ndarray
import numpy as np

camID = 'ASCOM.ASICamera2.Camera'
print("camID = ", camID)

#cam = Dispatch(camID)
cam = CreateObject(camID)
print(dir(cam))
print("cam = ", cam)
print("cam.Connected = ", cam.Connected)

if not cam.Connected:
    cam.Connected = True

print("Camera Properties")

print("Binning (X x Y)      : ", cam.BinX, cam.BinY)
print("Camera State         : ", cam.CameraState)
print("Camera Size          : ", cam.CameraXSize, cam.CameraYSize)
print("CanGetCoolerPower    : ", cam.CanGetCoolerPower)
print("CanSetCCDTemperature : ", cam.CanSetCCDTemperature)
print("CCDTemperature       : ", cam.CCDTemperature)
print("Connected            : ", cam.Connected)
print("CoolerOn             : ", cam.CoolerOn)
print("CoolerPower          : ", cam.CoolerPower)
print("Description          : ", cam.Description)
print("DriverVersion        : ", cam.DriverVersion)
print("MaxBinX x MaxBinY    : ", cam.MaxBinX, cam.MaxBinY)
Beispiel #20
0
from comtypes.client import CreateObject, Constants
try:
    from comtypes.gen import TEMScripting
except:
    CreateObject("TEMScripting.Instrument")
    from comtypes.gen import TEMScripting

from comtypes.client import GetModule

from .acquisition import Acquisition
from .autoloader import AutoLoader
from .illumination import Illumination
from .temperatureControl import TemperatureControl
from .vacuum import Vacuum
from .camera import Camera
from .projection import Projection
from .gun import Gun
from .stage import Stage


class Instrument():

    try:
        instrument = CreateObject("TEMScripting.Instrument")
    except:
        print('Could not create instrument')

    acquisition = Acquisition(instrument)
    autoloader = AutoLoader(instrument)
    camera = Camera(instrument)
    gun = Gun(instrument)
Beispiel #21
0
__models_folder__ = abtronics.__models_folder__
__model_name__ = 'fiche_pa_3.2d.xls'
__model_path__ = __models_folder__ + sep + __model_name__
__jobs_folder__ = abtronics.__jobs_folder__
__JOB_ID__ = abtronics.__JOB_ID__
__JOB_PATH__ = __jobs_folder__ + sep + __JOB_ID__ + sep
mkdir(__JOB_PATH__)

def GetCellValue(cell):
	return excel.ActiveWorkbook.Sheets('positionnement-etude').Range(cell).Value()

file = fileopenbox("Séléctionnez la fiche PMR source", "Abtronics", filetypes= "*.xls*", multiple=False)
filename = basename(file)

excel = CreateObject('Excel.Application')
excel.DisplayAlerts = False
excel.Visible = True
excel.Workbooks.Open(file)
data = excel.ActiveWorkbook.Sheets('positionnement-etude').Range('A5:O1000').Value()
data = [line for line in data if not all(x is None for x in line)]
data = [[x for x in line] for line in data if not all(x is None for x in line)]
for i, line in enumerate(data):
	data[i][1] = ' '.join(line[1:3])
	del(data[i][2])
	if data[i][8]: data[i][8] = data[i][8].lower()
	if data[i][9]: data[i][9] = data[i][9].lower()
	if data[i][11]: data[i][11] = data[i][11].lower()
excel.Workbooks.Close()
excel.Workbooks.Open(__model_path__)
for i, line in enumerate(data):
class MainApplication(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        """application configuration"""
        menu = tk.Menu()
        Font = "helevetica 10" 
        root.grid_rowconfigure(2, weight=2)
        style = ttk.Style()
        style.configure("TLabel", relief="flat", foreground="black", background="lightgreen")
        style.configure("TButton", relief="grooved", foreground="#800", background="lightgreen", width=30)
        root.config(menu=menu)
        root.resizable(0, 0)
        root.title("Text To Audio Converter")
        root.geometry("500x200")
        menu.add_command(label="Exit", command=root.quit)
        menu.add_command(label="Help", command=self.showhelp)
        menu.add_command(label="About", command=self.about)
        root.configure(background="lightgreen")
        menu.configure(background="white")
        self.basic = ttk.Label(text="Please click the help button on the menu to learn how to use program \n", font=Font)
        self.basic.pack()
        self.Linput = ttk.Label(root, text="Input file", width=30) 
        self.Linput.pack()
        self.inputentry = ttk.Entry(root, width=30)
        self.inputentry.pack()
        self.Loutput = ttk.Label(text="Output file", width=30)
        self.Loutput.grid_rowconfigure(4, weight=2)
        self.Loutput.pack()
        self.OutputEntry = ttk.Entry(width=30)
        self.OutputEntry.pack()
        self.Lspeed = ttk.Label(text="Set voice rate", width=30)
        self.Lspeed.pack() 
        self.Setrate = ttk.Entry(width=30)
        self.Setrate.pack()
        self.Convert = ttk.Button(text="Convert Text", command=self.ConverterToAudio)
        self.Convert.pack(side="top")
        """sets up main root nction"""
    def ConverterToAudio(self):
        try: 
            self.engine = CreateObject("SAPI.SpVoice")
            self.stream = CreateObject("SAPI.SpFileStream")
            self.infile = self.inputentry.get()
            self.outfile = self.OutputEntry.get()
            self.stream.Open(self.outfile, SpeechLib.SSFMCreateForWrite)
            self.engine.AudioOutputStream = self.stream
            with open(self.infile, "r") as text:
                self.content = text.read()
                self.engine.rate = int(self.Setrate.get())
                self.engine.pitch =int(self.Setrate.get())
                self.engine.GetVoices("microsoft zira")
                self.engine.speak(self.content)
                self.stream.Close()
                mbx.showinfo("output", f" conversion of  source file {self.infile} to  destination{self.outfile}")
                with open("converter-conversions-log.txt","a") as C:
                    C.write(f"output: conversion of {self.infile} {self.outfile} completed")

                #mbx.showinfo("Output", "Conversion of {} to {}".format(self.infile, self.outfile))#
        except Exception as e:
            mbx.showwarning("error", e)
            with open("converter-error-log.txt", "a") as E:
                E.write(f"\n error: {e}")

      
    def showhelp(self):mbx.showinfo("Help", "To use this application make sure you type in the file or directory you need converted in the input entry and output\n entru for example text.txt and\n then in the output entry do text.mp3 you can also tab to the next entry\nthe new feature you can is set the rate of the scale from -10 to 10 in the rate entry box but there must be a number, i will add voices as I go. if you have a problem email [email protected] or notify me at my github. amke sure to send the logs you ahve when you find a error pelse send converter-error-log and converter-conversions-log as well ")

    def about(self):
        mbx.showinfo("About", "\n\n created by austin heisley-cook\ndate 2/1/2018 original year is 2013 this program the idea is credited to past boss because I am making the idea becomes a reality.\n I have spent years creating this.")
def generateMAL_AON_cs(out_excel, county, rate=10.0, year=2015, where_clause='', sort_by=DEFAULT_SORT):
    """Generates the Maintenance Assessment List for a county as an excel file using ALL_OR_NOTHING
    style of admin fees.

    Required:
        out_excel -- output .xls file
        county -- name of county
        rate -- tax rate for county as a float
        year -- year for assessment

    Optional:
        where_clause -- optional where clause to filter records
        sort_by -- optional fields to sort by, if none specified will sort by
            owner code and legal description (records are already sorted by
            section-township-range)
    """
    rate = float(rate)
    if os.path.exists(out_excel):
        os.remove(out_excel)

    # **************************************************************************************
    # styles
    #
    # set up style dict
    styleDict = {DATE_PAID: styleDate,
                 LANDOWNER: styleHeadersLeft,
                 ACRES: styleCurrency,
                 BENEFIT: styleCurrency,
                 ASSESSMENT: styleCurrency,
                 ADMIN_FEE: styleCurrency,
                 DEFAULT_STYLE: defaultStyle
        }

    # style dict for breaking out of years
    yearBreakDict = {ACRES: yearBreak,
                     BENEFIT: yearBreak,
                     ASSESSMENT: yearBreak,
                     ADMIN_FEE: yearBreak
        }

    # section overwrite style dict
    sectionBreakDict = {PID: styleHeadersRight}

    # column widths
    widths = (8, 35, 8, 9, 30, 20, 8, 8, 10, 10, 3, 8)

    # **************************************************************************************

    # validate table name and set up workbook and sheets
    if not os.path.splitext(out_excel)[-1] == '.xls':
        out_excel = os.path.splitext(out_excel)[0] + '.xls'

    headers = [CODE, LANDOWNER, SECTION, SEQUENCE, DESCRIPTION,
               PID, ACRES, BENEFIT, ASSESSMENT, ADMIN_FEE, EXEMPT, DATE_PAID]

    col_widths = dict(zip(range(len(headers)), widths))

    # new workbook
    wb = ExcelWorkbook()
    ws = wb.add_sheet('Assessments', headers, header_line_no=3, use_borders=False, styleHeaders=styleHeadersWithBorder,
                      styleDict=styleDict, widths=col_widths)

    # write merged and special header cells
    ws.ws.write(0, 0, Formula('TODAY()'), styleDate)
    ws.ws.write_merge(0, 0, 1, 7, 'THE LITTLE RIVER DRAINAGE DISTRICT', style=styleHeaders)
    ws.ws.write_merge(1, 1, 1, 7, 'MAINTENANCE ASSESSMENT LIST', style=styleHeaders)
    ws.ws.write_merge(0, 0, 9, 11, '{} {}'.format(year, ' '.join(county.upper().split()[:-1])), style=styleHeaders)
    ws.ws.write_merge(1, 1, 9, 11, 'RATE    %.1f' %float(rate) + '%', style=styleHeaders)

    # form sql clause, make sure it is sorted by year at minimum
    sql = (None, None)
    if sort_by in(None, '', '#'):
        sort_by = DEFAULT_SORT

    # make sure it is sorted by Section-Township-Range at minimum
    sql2 = (None, 'ORDER BY {}'.format(', '.join(sort_by.split(';') if isinstance(sort_by, basestring) else sort_by)))
    sort_fields = sort_by.split(';') if isinstance(sort_by, basestring) else sort_by
    if sort_by:
        sql = (None, 'ORDER BY {}'.format(', '.join(sort_fields)))
    print sql


    # default value for DATE PAID
    default_date_paid = datetime.datetime(int(year), 12, 31)

    # reference Geodatabase and fields
    county_where = "{} = '{}'".format(COUNTY_GIS, county.upper())
    gdb = utils.Geodatabase()
    fields = [CODE_GIS, LANDOWNER_GIS, SEC_TWN_RNG_GIS, SEQUENCE_GIS, DESCRIPTION_GIS,
             PID_GIS, ACRES_GIS, BENEFIT_GIS, ASSESSMENT_GIS, EXEMPT_GIS, DATE_PAID_GIS]

    # field indices
    sec_ind = fields.index(SEC_TWN_RNG_GIS)
    acre_ind = fields.index(ACRES_GIS)
    benefit_ind = fields.index(BENEFIT_GIS)
    assessment_ind = fields.index(ASSESSMENT_GIS)
    exempt_ind = fields.index(EXEMPT_GIS)
    date_ind = fields.index(DATE_PAID_GIS)
    desc_ind = fields.index(DESCRIPTION_GIS)
    seq_ind = fields.index(SEQUENCE_GIS)
    admin_ind = headers.index(ADMIN_FEE)
    ben_col = ascii_uppercase[headers.index(BENEFIT)]
    assess_col = ascii_uppercase[headers.index(ASSESSMENT)]

    # alter initial where clause to include county
    hide_admin = " AND {} <> '{}'".format(DESCRIPTION_GIS, ADMINISTRATIVE_FEE)
    null_secs = " AND {} NOT LIKE '%99%'".format(SEC_TWN_RNG_GIS)
    where_clause = ' AND '.join(filter(None, [county_where, where_clause, no_flag]))

    # admin fees
    #
    # recalculate admin fees if necessary
    #
    if float(rate) != float(utils.getRate()):
        gdb.calculate_admin_fee(rate)

    # now add rows to spreadsheet
    all_pins = {}
    grand_tots = {ACRES: [], BENEFIT: [], ASSESSMENT: [], ADMIN_FEE: []}

    start_index_row = ws._currentRowIndex + 1

    with arcpy.da.SearchCursor(gdb.breakdown_table, fields + [PIN], where_clause=where_clause, sql_clause=sql) as rows:
        cnt = 0
        for r in rows:

            vals = list(r)[:len(fields)]
            vals[headers.index(ASSESSMENT)] = Formula(ASSESSMENT_FORMULA.format(b='%s%s' %(ben_col, ws._currentRowIndex+1), r=(float(rate) * 0.01)))
            vals.insert(admin_ind, Formula(ADMIN_FEE_FORMULA.format(a='%s%s' %(assess_col, ws._currentRowIndex+1))))

            ws.addRow(*vals)
            all_pins[r[-1]] = vals
            cnt += 1

    # add blank row with dashed style
    ws.addRow(styleDict=yearBreakDict)

    # now add totals
    totals = {h:Formula('SUM({col}{st}:{col}{en})'.format(col=ascii_uppercase[i],
            st=start_index_row, en=ws._currentRowIndex-1))
            for i,h in enumerate(headers) if i in range(acre_ind, admin_ind+1)}

    totals[PID] = 'TOTAL'
    totals['styleDict'] = sectionBreakDict
    ws.addRow(**totals)
    for k in [ACRES, BENEFIT, ASSESSMENT, ADMIN_FEE]:
        grand_tots[k].append(totals[k])

    # add another blank row
    ws._currentRowIndex += 1

##    # now add grand totals
##    totals = {k: Formula(' + '.join([f.text() for f in v])) for k,v in grand_tots.iteritems()}
##
##    totals[PID] = 'GRAND TOTAL'
##    totals['styleDict'] = sectionBreakDict
##    ws.addRow(**totals)


    # set print properties
    ws.ws.set_fit_width_to_pages(1)
    ws.ws.set_fit_height_to_pages(0)
    ws.ws.set_portrait(0)
    ws.ws.set_fit_num_pages(1)

    # set page headers
    ws.ws.set_header_str('&R Page &P of &N')
    ws.ws.set_footer_str('')

    # save it
    wb.save(out_excel)
    del wb

    # add title rows
    xl = CreateObject('Excel.application')
    wb = xl.Workbooks.Open(out_excel)
    ws = wb.ActiveSheet
    ws.PageSetup.PrintTitleRows = '$1:$4'
    try:
        # silence compatibility message going from xls to xlsx
        wb.DoNotPromptForConvert = True
        wb.CheckCompatibility = False
        xl.DisplayAlerts = False
    except:
        pass
    wb.Save()
    wb.SaveAs(out_excel)
    wb.Close()
    xl.Application.Quit()
    del xl, wb

    os.startfile(out_excel)
    return out_excel
Beispiel #24
0
from comtypes.client import CreateObject
from comtypes.gen import SpeechLib

engine = CreateObject("SAPI.SpVoice")
engine.Rate = 1
stream = CreateObject("SAPI.SpFileStream")

import sys
inf = open(sys.argv[1])
for i,line in enumerate(inf):
	outfile = "output_%03d.wav"%i
	stream.Open(outfile, SpeechLib.SSFMCreateForWrite)
	engine.AudioOutputStream = stream
	sel=None
	engine.Volume = 100
	line = line.strip()
	if line == "--":
		s,t = "Sam","Silence"
		engine.Volume = 0
	else:
		s,t = line.split(":", 1)
	for v in engine.GetVoices():
		d=v.GetDescription()
		if s.lower() in d.lower():
			sel=v
			break
	if sel:
		engine.Voice = sel
	else:
		print("cant find voice")
		exit(1)
def GetRawHandle(RawFile):
    hRaw = CreateObject('MSFileReader.XRawfile')
    hRaw.open(RawFile)
    return hRaw
Beispiel #26
0
def run():
    arguments = docopt(__doc__, version='0.1')

    if arguments['<path>'] == '-':
        text = sys.stdin.read()
    else:
        text = get_file_contents(arguments['<path>'])

    css = []

    if arguments['--css']:
        css.append(get_file_contents(arguments['--css']))

    if arguments['--style']:
        css.append(arguments['--style'])

    save_as = None
    if arguments['--save']:
        save_as = pathlib.Path(arguments['--save'])
        if save_as.suffix not in SAVE_FORMATS:
            print('Error: Cannot save in {0} format. Supported formats: {1}'.format(
                save_as.suffix,
                ', '.join(SAVE_FORMATS.keys())
            ), file=sys.stderr)
            exit(1)

        if save_as.exists():
            print('Error: Path {0} already exists. Not overwriting'.format(save_as), file=sys.stderr)
            exit(1)

    with Timer(factor=1000) as t:
        parsed = parse(text, stylesheets=css)

    print('Parsed in {0:f} ms'.format(t.elapsed))

    with Timer(factor=1000) as t:
        try:
            word = CreateObject("Word.Application")
        except AttributeError as e:
            gen_dir = inspect.getsourcefile(gen)

            print('****** There was an error opening word ******')
            print('This is a transient error that sometimes happens.')
            print('Remove all files (except __init__.py) from here:')
            print(os.path.dirname(gen_dir))
            print('Then retry the program')
            print('*********************************************')
            raise e
        doc = word.Documents.Add()

    print('Opened word in {0:f} ms'.format(t.elapsed))

    word.Visible = not arguments['--hidden']

    from comtypes.gen import Word as constants

    with Timer(factor=1000) as t:
        insert(parsed, document=doc, constants=constants, debug=arguments['--debug'])

    print('Inserted in {0:f} ms'.format(t.elapsed))

    if save_as:
        file_format_attr = SAVE_FORMATS[save_as.suffix]

        if callable(file_format_attr):
            file_format_attr(doc, save_as, constants)
        else:
            # https://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.saveas2.aspx
            doc.SaveAs2(
                FileName=str(save_as.absolute()),
                FileFormat=getattr(constants, file_format_attr),
            )
        print('Saved to {0}'.format(save_as))

    if arguments['--close']:
        word.Quit(SaveChanges=constants.wdDoNotSaveChanges)
Beispiel #27
0
class PDBSymbols(object):
    def __init__(self, fileName):
        self.msdia = GetModule("msdia140.dll")
        self.dataSource = CreateObject(self.msdia.DiaSource, interface=self.msdia.IDiaDataSource)
        ext = fileName.split(os.path.extsep)[-1]
        if 'pdb' == ext.lower():
            self.dataSource.loadDataFromPdb(fileName)
        else:
            symPath = os.environ.get('_NT_SYMBOL_PATH', 'SRV**\\\\symbols\\symbols')
            self.dataSource.loadDataForExe(fileName, symPath, None)
        self.session = self.dataSource.openSession()
        self.globalScope = self.session.globalScope

    def _getSingleSymbolObject(self, name, caseSensetive, symType):
        searchType = 1
        if not caseSensetive:
            searchType = 2
        children = self.globalScope.findChildren(symType, name, searchType)
        if (not children) or (0 == children.count):
            raise Exception("No children for type")
        if 1 != children.count:
            raise Exception("Ambiguous struct name. %d match" % children.count)
        return children.Item(0)

    def findGlobalSymbolRVA(self, name, caseSensetive=True):
        sym = self._getSingleSymbolObject(name, caseSensetive, SymTagEnum['SymTagData'])
        return sym.relativeVirtualAddress

    def getStruct(self, name, caseSensetive=True, maxDepth=20):
        child = self._getSingleSymbolObject(name, caseSensetive, SymTagEnum['SymTagUDT'])
        structName = child.name
        structElements = child.findChildren(0, None, 0)
        if not structElements:
            raise Exception("No struct elements")
        return self._getAllMembers(structElements, maxDepth=maxDepth)

    def _getAllMembers(self, structElements, base=0, maxDepth=20):
        members = []
        if 0 == maxDepth:
            return members
        for memberIndex in range(structElements.count):
            member = structElements.Item(memberIndex)
            members.extend(self._fetchSymData(member, base=base, maxDepth=maxDepth))
        return members

    def _fetchSymData(self, symData, base=0, maxDepth=20):
        if 0 == maxDepth:
            return []
        symTag = SymTagEnumTag[symData.symTag]
        if symTag == 'SymTagVTable':
            if None == symData.type.name:
                name = 'VFN_table'
            else:
                name = symData.type.name + '__VFN_table'
            return [SHAPE(name, (base+symData.offset, None), POINTER(isNullValid=True), fromStart=True)]
        elif symTag == 'SymTagBaseClass':
            return self._getAllMembers(symData.type.findChildren(0, None, 0), base=base+symData.offset, maxDepth=maxDepth)
        elif symTag == 'SymTagData':
            name = symData.name
            while name.startswith('_'):
                name = name[1:]
            dataKind = SymDataKindTag[symData.dataKind]
            if dataKind != 'Member':
                return []
            return self._getSymTagDataTypeAsShape(symData.Type, name, base+symData.offset, maxDepth=maxDepth)
        return []

    def _getAllChildren(self, dataType, symTypeFilter=None):
        if None == symTypeFilter:
            symTypeFilter = 0
        members = dataType.findChildren(symTypeFilter, None, 0)
        return [members.Item(x) for x in range(members.count)]

    def _getSymTagDataTypeAsShape(self, dataType, name, base, maxDepth):
        if 0 == maxDepth:
            return []
        name, base, dataType, dataTypeArgs, dataTypeKw = self._getSymTagDataType(dataType, name, base, maxDepth)
        if -1 == base:
            place = 0
        else:
            place = (base, None)
        return [SHAPE(name, place, dataType(*dataTypeArgs, **dataTypeKw), fromStart=True)]

    def _getSymTagDataType(self, dataType, name, base, maxDepth):
        dataTypeName = dataType.name
        if not dataTypeName:
            dataTypeName = 'void'
        memberTypeSymTag = SymTagEnumTag[dataType.symTag]
        if 'SymTagUDT' == memberTypeSymTag:
            if dataTypeName.startswith('std::basic_string<'):
                if 'wchar_t' in dataType.name:
                    isWide = True
                    def chooser(ctx):
                        return (ctx.maxStringLength * 2) < 0x10
                else:
                    isWide = False
                    def chooser(ctx):
                        return ctx.maxStringLength < 0x10
                return (
                        name,
                        base,
                        STRUCT,
                        [[
                            SHAPE('stringLength', (0x10, None), SIZE_T()),
                            SHAPE('maxStringLength', 0, SIZE_T()),
                            SHAPE('data', (0, None),
                                SWITCH(
                                chooser,
                                {
                                    True: [
                                        SHAPE('string', 0, STRUCT([
                                            SHAPE('string', 0, STRING(isUnicode=isWide, maxSize=0x10, isPrintable=False, size='_parent._parent.stringLength'))])) ],
                                    False: [
                                        SHAPE('string', 0, POINTER_TO_STRUCT([
                                                SHAPE('string', 0, STRING(isUnicode=isWide, isPrintable=False, size='_parent._parent.stringLength'))])),
                                        SHAPE('dummy', 0, ANYTHING(size=8))]}), fromStart=True)
                        ]], {'desc':dataTypeName})
            elif dataTypeName.startswith('std::unique_ptr'):
                struct = self._getUniquePtr(dataType, maxDepth-1)
                if 'std::default_delete' in dataTypeName:
                    return (
                            name,
                            base,
                            POINTER_TO_STRUCT,
                            [struct],
                            {   'isNullValid':True,
                                'desc':dataTypeName })
                else:
                    return (
                            name,
                            base,
                            STRUCT,
                            [[
                                SHAPE('deleter' + name, 0, POINTER(isNullValid=True)),
                                SHAPE(name, 0, POINTER_TO_STRUCT(struct, isNullValid=True))]],
                            { 'desc':dataTypeName })

            elif dataTypeName.startswith('std::shared_ptr'):
                baseType = self._getAllChildren(dataType, SymTagEnum['SymTagBaseClass'])
                if 1 != len(baseType):
                    raise Exception("Failed to parse shared_ptr")
                baseType = baseType[0]
                struct = self._getUniquePtr(baseType, maxDepth-1)
                return (
                        name,
                        base,
                        STRUCT,
                        [[
                            SHAPE('ptr', 0, POINTER_TO_STRUCT(struct, isNullValid=True)),
                            SHAPE('rep', 0, POINTER(isNullValid=True))]],
                        { 'desc':dataTypeName })
            elif dataTypeName.startswith('std::function'):
                return (name, base, ARRAY, [10, SIZE_T, [], {}], {'desc':dataTypeName})
            elif    dataTypeName.startswith('std::map') or \
                    dataTypeName.startswith('std::multimap') or \
                    dataTypeName.startswith('std::set') or \
                    dataTypeName.startswith('std::multiset'):

                baseType = self._getAllChildren(dataType, SymTagEnum['SymTagBaseClass'])
                if 1 != len(baseType):
                    raise Exception("Failed to parse shared_ptr")
                baseType = baseType[0]
                struct = self._getMapType(baseType, maxDepth-1)

                def parseNode(patFinder, startAddress, context):
                    isNil = patFinder.readByte(startAddress + (patFinder.getPointerSize() * 3) + 1)
                    if isNil:
                        return [SHAPE('duummy', 0, ANYTHING())]
                    return [
                        SHAPE('left', 0, POINTER_TO_STRUCT(parseNode)),
                        SHAPE('parent', 0, POINTER()),
                        SHAPE('right', 0, POINTER_TO_STRUCT(parseNode)),
                        SHAPE('dummy', 0, SIZE_T()),
                        SHAPE('data', 0, STRUCT(struct))]

                return (
                        name,
                        base,
                        STRUCT,
                        [[
                            SHAPE('tree', 0, POINTER_TO_STRUCT([
                                SHAPE('left', 0, POINTER()),
                                SHAPE('anchor', 0, POINTER_TO_STRUCT(parseNode)),
                                SHAPE('right', 0, POINTER()),
                                SHAPE('color', 0, BYTE()),
                                SHAPE('isNil', 0, BYTE(1))])),
                            SHAPE('treeSize', 0, SIZE_T())]],
                        { 'desc':dataTypeName })

            elif dataTypeName.startswith('std::vector') and 'bool' not in dataTypeName:
                structSize, struct = self._getVectorTypeAndSize(dataType, maxDepth-1)
                def arraySizeProc(ctx):
                    return (ctx._parent.last - ctx._parent.first) // structSize
                return (
                        name,
                        base,
                        STRUCT,
                        [[
                            SHAPE('first', 0, POINTER(isNullValid=True)),
                            SHAPE('last', 0, POINTER(isNullValid=True)),
                            SHAPE('end', 0, POINTER(isNullValid=True)),
                            SHAPE('data', 0, POINTER_TO_STRUCT([SHAPE('items', 0, ARRAY(
                                arraySizeProc, STRUCT, [struct]))], isNullValid=True), fromStart=True)]],
                        { 'desc':dataTypeName } )
            elif dataTypeName.startswith('nonstd::optional'):
                structSize, struct = self._getOptionalTypeAndSize(dataType, maxDepth-1)
                if 1 == structSize:
                    alignment = 0
                elif structSize in [1,2,4,8]:
                    alignment = structSize
                else:
                    alignment = None
                def chooser(ctx):
                    return 0 != (ctx.has_value_ & 0xff)
                if alignment:
                    return (
                            name,
                            base,
                            STRUCT,
                            [[
                                SHAPE('has_value_', 0, BYTE()),
                                SHAPE('contained', (0, 0, alignment),
                                    SWITCH(
                                        chooser,
                                        {
                                            True: struct,
                                            False: [] }))]],
                            { 'desc':dataTypeName })
                else:
                    return (
                            name,
                            base,
                            STRUCT,
                            [[
                                SHAPE('has_value_', 0, SIZE_T()),
                                SHAPE('contained', 0,
                                    SWITCH(
                                        chooser,
                                        {
                                            True: struct,
                                            False: [] }))]],
                            { 'desc':dataTypeName })

            else:
                content = self._getAllMembers(dataType.findChildren(0, None, 0), base=0, maxDepth=maxDepth)
                if not content:
                    return ( name, base, ANYTHING, [], {'desc':dataTypeName})
                return ( name, base, STRUCT, [content], {'desc':dataTypeName})
        elif 'SymTagPointerType' == memberTypeSymTag:
            content = self._getAllMembers(dataType.findChildren(0, None, 0), base=0, maxDepth=maxDepth-1)
            if not content:
                return ( name, base, POINTER, [], {'isNullValid':True, 'desc':dataTypeName} )
            return (
                        name,
                        base,
                        POINTER_TO_STRUCT,
                        [content],
                        {'isNullValid':True, 'desc':dataTypeName} )
        elif memberTypeSymTag in ['SymTagBaseType', 'SymTagEnum']:
            if dataType.baseType in [7, 1, 5, 10, 12, 14, 20, 21, 22, 23, 24, 31]:
                dataInfo = {'isSigned':False}
            elif dataType.baseType in [6, 2, 3, 4, 11, 13, 15, 16, 17, 18, 19]:
                dataInfo = {'isSigned':True, 'desc':dataTypeName}
            elif 8 == dataType.baseType:
                if 8 == dataType.length:
                    return (name, base, DOUBLE, [], {'desc':dataTypeName})
                elif 4 == dataType.length:
                    return (name, base, FLOAT, [], {'desc':dataTypeName})
                else:
                    raise Exception("Invlaid size for float %d" % dataType.length)
            else:
                raise Exception("Unknown data type %d" % dataType.baseType)
            if 'SymTagEnum' == memberTypeSymTag:
                enumChildrenItems = self._getAllChildren(dataType)
                values = {x.value : x.name for x in enumChildrenItems}
                dataInfo['value'] = values
            dataInfo['size'] = dataType.length
            dataInfo['desc'] = dataTypeName
            return (name, base, NUMBER, [], dataInfo)
        elif 'SymTagArrayType' == memberTypeSymTag:
            arrayCount = dataType.count
            arrayName, _, arrayType, arrayTypeArgs, arrayTypeKw = self._getSymTagDataType(dataType.type, 'A', 0, maxDepth)
            return (name, base, ARRAY, [arrayCount, arrayType, arrayTypeArgs, arrayTypeKw], {'desc':arrayName})
        else:
            raise Exception("Unknown ember type %s" % memberTypeSymTag)

    def _getUniquePtr(self, dataType, maxDepth):
        return self._getSubType(dataType, 'element_type', maxDepth)[1]

    def _getMapType(self, dataType, maxDepth):
        return self._getSubType(dataType, 'value_type', maxDepth)[1]

    def _getVectorTypeAndSize(self, dataType, maxDepth):
        return self._getSubType(dataType, 'value_type', maxDepth)

    def _getOptionalTypeAndSize(self, dataType, maxDepth):
        return self._getSubType(dataType, 'value_type', maxDepth)

    def _getSubType(self, dataType, itemName, maxDepth):
        baseType = dataType.findChildren(SymTagEnum['SymTagTypedef'], itemName, 1)
        if baseType.count != 1:
            raise Exception("Failed to parse %s" % itemName)
        baseType = baseType.Item(0)
        typeSize = baseType.length
        return (typeSize, self._getSymTagDataTypeAsShape(baseType.type, 'val', base=0, maxDepth=maxDepth-1))
Beispiel #28
0
 def create_com_object_filter():
     if not DLL_IS_LOADED:
         raise WindowsError("Could not locate Agilent DLLs")
     no_filter = CreateObject(
         'Agilent.MassSpectrometry.DataAnalysis.MsdrPeakFilter')
     return no_filter
Beispiel #29
0
 def setUp(self):
     self.d = CreateObject("Scripting.Dictionary", dynamic=False)
Beispiel #30
0
class EditableText (NVDAObjects.behaviors.EditableText):
	"""
	Provides latex-access support, but makes sure this is only in edit controls.  The normal editableText.EditableText class is not used any more in this plugin because we need to take advantage of selection changes for the matrix processor.
	
	This NVDAObject overlay class is used when NVDA enters accessible Editable text, and provides the user with all the events, scripts and gestures needed to use this plugin.
	
	See the l{__gestures} dict for all the key bindings that this plugin uses.  Some may also be found in the l{GlobalPlugin} class, in the same dict.
	
	Any method beginning with event_* is an NVDA event which gets fired on other system events.
	
	Any method that begins with script_* will get executed when the required l{InputGesture} is pressed, E.G. if a key is pressed, button on the mouse is clicked, etc.
	"""

	processMaths = False
	latex_access = CreateObject ("latex_access")

	# For the matrix:
	matrix = None
	row = None
	column = None

	def _caretScriptPostMovedHelper(self, speakUnit, gesture, info = None):
		"""
This method ensures that LaTeX translation occurs when the system caret moves, and also makes sure that normal behaviour occurs when l{processMaths} is off.
		"""

		if isScriptWaiting ():
			return

		if not info:
			try:
				info = self.makeTextInfo (textInfos.POSITION_CARET)
			except:
				return
		review.handleCaretMove(info)
		if speakUnit == textInfos.UNIT_LINE and EditableText.processMaths and not willSayAllResume(gesture):
			spokenLine = GetLine ()
			brailledLine = GetLine ()
			if not spokenLine and not brailledLine:# Is it a blank line?
				spokenLine = _("blank")
				brailledLine = _("")
			else:
				spokenLine = EditableText.latex_access.speech (spokenLine)
				brailledLine = EditableText.latex_access.nemeth (brailledLine)
			speech.speakMessage (spokenLine)
			braille.handler.message (brailledLine)
		else:
			if speakUnit and not willSayAllResume(gesture):
				info.expand(speakUnit)
				speech.speakTextInfo(info, unit=speakUnit, reason=controlTypes.REASON_CARET)
		braille.handler.handleCaretMove(self)

	def script_reportCurrentLine (self, gesture):
		"""
		This script reports the line that the current navigator object is focused on, and speaks/brailles it appropriately depending on the state of l{processMaths}.  If pressed twice quickly, the current line is spelt out.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}.
		"""

		obj=api.getFocusObject()
		treeInterceptor=obj.treeInterceptor
		if hasattr(treeInterceptor,'TextInfo') and not treeInterceptor.passThrough:
			obj=treeInterceptor
		try:
			info=obj.makeTextInfo(textInfos.POSITION_CARET)
		except (NotImplementedError, RuntimeError):
			info=obj.makeTextInfo(textInfos.POSITION_FIRST)
		info.expand(textInfos.UNIT_LINE)
		if getLastScriptRepeatCount()==0:
			if EditableText.processMaths:
				spokenLine = GetLine ()
				brailledLine = GetLine ()
				if not spokenLine and not brailledLine:# Is it a blank line?
					spokenLine = _("blank")
					brailledLine = _("")
				else:
					spokenLine = EditableText.latex_access.speech (spokenLine)
					brailledLine = EditableText.latex_access.nemeth (brailledLine)
				speech.speakMessage (spokenLine)
				braille.handler.message (brailledLine)
			else:
				speech.speakTextInfo(info,unit=textInfos.UNIT_LINE,reason=controlTypes.REASON_CARET)
		else:
			speech.speakSpelling(info.text)
	script_reportCurrentLine.__doc__ = _("If latex-access translation is on, Translates the current line into nemeth braille and speech.  If translation is turned off, the current line is spoken as normal.  If this keystroke is pressed twice, the current line is spellt out.")

	def script_toggleDollars_nemeth (self, gesture):
		"""
		Toggles the state of whether dollar signs should be brailled in nemeth LaTeX translation.
		@param gesture: the gesture to be passed through to nvda (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		dollars = EditableText.latex_access.toggle_dollars_nemeth ()
		if dollars == True:
			ui.message (_("nemeth dollars off"))
		else:
			ui.message (_("nemeth dollars on"))
	script_toggleDollars_nemeth.__doc__ = _("Toggles the state of whether dollar signs should be brailled in nemeth LaTeX translation.")

	def script_toggleDollars_speech (self, gesture):
		"""
		Toggles the state of whether dollar signs should be spoken in speech for LaTeX translation.
		@param gesture: the gesture to be passed through to nvda (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		dollars = EditableText.latex_access.toggle_dollars_speech ()
		if dollars == True:
			ui.message (_("speech dollars off"))
		else:
			ui.message (_("speech dollars on"))
	script_toggleDollars_speech.__doc__ = _("Toggles the state of whether dollar signs should be spoken in speech for LaTeX translation.")

	def script_toggleMaths (self, Gesture):
		"""A script to toggle the latex-access translation on or off.
		@param gesture: the gesture to be past through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}.
		"""
		if EditableText.processMaths:# is translation on?
			EditableText.processMaths = False
			ui.message (_("Maths to be read as plain latex"))
		else:
			EditableText.processMaths = True# translation was off.
			ui.message (_("Maths to be processed to a more verbal form"))
	script_toggleMaths.__doc__ = _("Toggles the speaking of mathematical expressions as either straight latex or a more verbal rendering.")

	def script_inputMatrix (self, gesture):
		"""
		This script creates the matrix COM Object, and initialises a matrix based on the text that is currently selected.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		EditableText.matrix = CreateObject ("latex_access_matrix")
		EditableText.row = 1
		EditableText.column = 1
		EditableText.matrix.tex_init(getSelectedText ())
		# The msg variable is here to say how many rows and columns have been initialised.
		msg = "Initialised"
		msg = msg + str (EditableText.matrix.rows)
		msg = msg + " by "
		msg = msg + str(EditableText.matrix.columns)
		msg = msg + " matrix"
		ui.message (_(msg))
	script_inputMatrix.__doc__ = _ ("Initialises a matrix.  First highlight it and then run this script to have it as an object.")

	def script_matrixRight (self, gesture):
		"""
		Moves the matrix one cell to the right.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		if EditableText.column < EditableText.matrix.columns:
			EditableText.column = EditableText.column + 1
			ui.message (_(EditableText.matrix.get_cell(EditableText.row, EditableText.column)))
		else:
			ui.message (_("End of row"))
	script_matrixRight.__doc__ = _ ("moves the matrix cursor right and then speaks and brailles the cell.")

	def script_matrixLeft (self, gesture):
		"""
		Moves the matrix one cell to the left.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		if EditableText.column > 1:
			EditableText.column = EditableText.column - 1
			ui.message (_ (EditableText.matrix.get_cell (EditableText.row, EditableText.column)))
		else:
			ui.message (_ ("Start of row"))
	script_matrixLeft.__doc__ = _ ("Moves the matrix cursor to the left one cell, then speaks and brailles it")

	def script_matrixDown (self, gesture):
		"""
		Moves the matrix one cell down.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		if EditableText.row < EditableText.matrix.rows:
			EditableText.row = EditableText.row + 1
			ui.message (_ (EditableText.matrix.get_cell (EditableText.row, EditableText.column)))
		else:
			ui.message (_ ("End of column"))
	script_matrixDown.__doc__ = _ ("Moves the matrix cursor down one cell, then speaks and brailles it.")

	def script_matrixUp (self, gesture):
		"""
		Moves the matrix one cell up.
		@param gesture: the gesture to be passed through to NVDA (in this case, a keypress).
		@type gesture: l{inputCore.InputGesture}
		"""

		if EditableText.row > 1:
			EditableText.row = EditableText.row - 1
			ui.message (_ (EditableText.matrix.get_cell (EditableText.row, EditableText.column)))
		else:
			ui.message (_ ("Start of column"))
	script_matrixUp.__doc__ = _ ("Moves the matrix down one cell and then speaks and brailles it.")

	# For the input gestures:
	__gestures = {
		"kb:control+M": "toggleMaths",
		"kb:NVDA+UpArrow": "reportCurrentLine",
		"kb:control+D": "toggleDollars_nemeth",
		"kb:control+shift+D": "toggleDollars_speech",
		"kb:control+shift+M":"inputMatrix",
		"kb:control+shift+L": "matrixRight",
		"kb:control+shift+J": "matrixLeft",
		"kb:control+shift+K": "matrixDown",
		"kb:control+shift+I": "matrixUp",
	}
Beispiel #31
0
class mzFile(mzAPImzFile):
    def __init__(self, file_name, *args, **kwargs):
        self.file_type = 'raw'
        self.data_file = file_name

        try:
            self.source = CreateObject(
                "{10729396-43ee-49e5-aa07-85f02292ac70}")
        except WindowsError as err:
            print "RawReader.dll not found in registry."
            raise err
        self.source.OpenRawFile(file_name)

        self._filters = None
        self._scaninfo = None

        # A bunch of functions are pure C#.
        self.scan_range = self.source.scan_range
        self.time_range = self.source.time_range
        self.time_for_scan = self.source.time_from_scan
        self.scan_for_time = self.source.scan_from_time
        self.scanForTime = self.source.scan_from_time
        self.timeForScan = self.source.time_from_scan
        self.scan_time_from_scan_name = self.source.time_from_scan

    def scan(self, scan_number, centroid=False):
        if isinstance(scan_number, float):  # Taken as a scan time.
            scan_number = self.source.scan_from_time(scan_number)
        if centroid:
            return [x[:2] for x in self.source.centroid_scan(scan_number)]
        else:
            return list(self.source.profile_scan(scan_number))

    def lscan(self, scan_number):
        scan = self.source.centroid_scan(scan_number)
        if len(scan[0]) < 4:
            raise IOError, "Full lscan data not available for scan %s" % scan_number
        return [x[:4] for x in scan]

    def rscan(self, scan):
        return list(self.source.centroid_scan(scan))

    def average_scan(self, startscan, stopscan, filter):
        return list(self.source.average_scan(startscan, stopscan, filter))

    def filters(self):
        if not self._filters:
            filterlist = zip(self.source.GetAllFilterInfoTimes(),
                             self.source.GetAllFilterInfo())
            self._filters = [(time, string) for time, string in filterlist
                             if time and string]

        return self._filters

    def extra_info(self, scan):
        info = {}
        for key, val in self.source.get_extra_scan_info(scan):
            key = key.strip(':')
            try:
                info[key] = float(val)
            except ValueError:
                info[key] = val
        return info

    def scanInjectionTime(self, scan):
        keys, vals = zip(*self.source.get_extra_scan_info(scan))
        try:
            return float(vals[keys.index('Ion Injection Time (ms):')])
        except ValueError:
            return float(vals[keys.index('Ion Injection Time (ms):')].replace(
                ',', ''))

    def scanPrecursor(self, scan):
        keys, vals = zip(*self.source.get_extra_scan_info(scan))
        return (float(vals[keys.index('Monoisotopic M/Z:')]),
                float(vals[keys.index('Charge State:')]))

    def scan_info(self,
                  start_time=0,
                  stop_time=None,
                  start_mz=0,
                  stop_mz=100000):
        if not self._scaninfo:
            self._scaninfo = []

            for scan in range(*self.scan_range()):
                info = self.source.GetFilterInfoForScan(scan)
                time = self.source.time_from_scan(scan)
                self._scaninfo.append(
                    (time, float(info[1]), scan,
                     info[0].upper() if info[0].upper() != 'MS' else 'MS1',
                     'p' if info[2] == 'Profile' else 'c'))

        if start_time:
            start_scan = self.scanForTime(start_time)
        else:
            start_scan = self.scan_range()[0]
        if stop_time:
            stop_scan = self.scanForTime(stop_time)
        else:
            stop_scan = self.scan_range()[1]
        return [
            x for x in self._scaninfo
            if start_scan <= x[2] <= stop_scan and start_mz <= x[1] <= stop_mz
        ]

    def headers(self):
        return self.scan_info()

    def xic(self,
            start_time=-1,
            stop_time=-1,
            start_mz=-1,
            stop_mz=-1,
            filter=None):
        if start_time == -1 and stop_time == -1 and start_mz == -1 and stop_mz == -1 and filter == None:
            return self.tic()
        if not filter:
            filter = 'Full ms '
        if start_time != -1:
            start_time = self.scanForTime(start_time)
        if stop_time != -1:
            stop_time = self.scanForTime(stop_time)
        return list(
            self.source.get_xic(start_time, stop_time, start_mz, stop_mz,
                                filter))

    def tic(self):
        return list(self.source.get_tic())

    def close(self):
        pass  # Check for memory leaks!

    def centroid(self, scan, *foo, **bar):
        print "mzFile.centroid is deprecated, use mzFile.scan(..., centroid = True) instead."
        return self.scan(scan, centroid=True)


#if __name__ == '__main__':
#import os
#import glob
#import subprocess
#os.chdir(r'C:\Users\Max\Documents\Visual Studio 2017\Projects\ConsoleApp3\ConsoleApp3\bin\Debug')

#netDir = sorted(glob.glob('c:/Windows/Microsoft.NET/Framework%s/v[34]*/RegAsm.exe' % '64'))[-1]
#dllpath = r'C:\Users\Max\Documents\Visual Studio 2017\Projects\ConsoleApp3\ConsoleApp3\bin\Debug\ConsoleApp3.dll'
#ret = subprocess.call([netDir, dllpath, "/tlb", "/codebase"])
def process(PA):
	global ActiveWindow, Shapes, Word, TRs_all, xl, Visio
	global RESULTS
	try:

		# ouvrir le fichier excel et faire les initialisations de coutume
		xl = CreateObject("Excel.application")
		xl.Visible = False
		xl.DisplayAlerts = False
		wb = xl.Workbooks.Open(PA)
		wb.Sheets("synoptique-bilan µmodules").Select()

		# dans la sheet visée, détecter tout les objets OLE (qui seront 
		# normalement tous des déssins visio)
		OLEObjects = wb.Sheets("synoptique-bilan µmodules").OLEObjects()

		# pour chaque déssin ...
		for OLEObject in OLEObjects:
			# l'ouvrir dans Visio
			OLEObject.Verb(2)
			# prendre la main sur la fenêtre visio ouverte
			Visio = GetActiveObject("Visio.Application")
			# Visio.Visible = False
			Visio.DisplayAlerts = False
			ActiveWindow =  Visio.ActiveWindow
			Page = ActiveWindow.Page
			Shapes = Page.Shapes

			msg = "Voulez confirmer le nombre de PBs après chaque sélection?\n" \
						+ "(si c'est plan assez complexe mieux vaut répondre par oui)"
			yn = ynbox(msg)

			# allons-y!
			# On extrait d'abord les infos d'entête
			for shape in Shapes:
				text = shape.Text
				if text.startswith('NRO'):
					bloc_NRO = text
				elif text.startswith('PT'):
					try:
						blocs_PT.append(shape)
					except:
						blocs_PT = [shape]
				elif text.startswith('PA'):
					PA_posx = get_XY(shape)[0]
			if get_XY(blocs_PT[0])[0] > get_XY(blocs_PT[1])[0]:
				FI_bloc = blocs_PT[0]
				PA_bloc = blocs_PT[1]
			else:
				PA_bloc = blocs_PT[1]
				FI_bloc = blocs_PT[0]
			PA_PT = PA_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			PMZ_PT = FI_bloc.Text.rsplit('\n')[0].replace('PT: ', '')
			CH = PA_bloc.Text.rsplit('\n')[2].replace('CH: ', '')
			NRO = extract('NRO/PMZ/PA', bloc_NRO, 'NRO')
			ADRESSE1 = ' '.join(PA_bloc.Text.rsplit('\n')[3:5])\
									.replace('Adresse: ', '')
			ADRESSE2 = ADRESSE1.rsplit('-')[0]

			TRs = {}
			empty_TRs = []
			# là ça va barder!
			for shape in Shapes:
				if shape.Text.startswith('TR'):
					if get_XY(shape)[0] > PA_posx:
						TR_TXT = str(shape.Text.encode()).replace("b'", '').replace("'", '')
						TR = TR_TXT.rsplit('FO')[0] \
							.replace('\\n', ' ') + 'FO'
						if not re.match(r'TR\s+\d{2}\s+\d{4}\s+\d+FO', TR):
							empty_TRs.append(shape.ID)
							continue
						if TR not in TRs:
							TRs[TR] = {
								'LONG': 0,
								'SHAPES': [shape.ID],
								'CH/IMB/AP': [],
								'PTs': [],
								'maxPT': 0
								}
						else:
							TRs[TR]['SHAPES'].append(shape.ID)
						try:
							TR_LONG = int(TR_TXT.rsplit('\\xe2\\x80\\x93 ')[1] \
															.replace('m', ''))
						except:
							TR_LONG = 0
						TRs[TR]['LONG'] = TRs[TR]['LONG'] + TR_LONG
			
			title1 = 'Sélectionnez les bloc'
			title2 = 'Confirmez la sélection'
			for TR in TRs:
				while True:
					SelectShapes(TRs[TR]['SHAPES'])
					if ccbox(TR, title1):
						CH_OR_IMB_OR_AP_all = []
						PTs = []
						msg = "Pour " + TR + "\nVous avez sélectionné:\n"
						selected_PBs = 0
						yn_yes = True
						for selected in ActiveWindow.Selection:
							try:
								TEXT = str(selected.Text)
								if not TEXT.startswith('PB'):
									continue
								selected_PBs = selected_PBs + 1
								PT = TEXT.rsplit('\n')[2]
								ADR = TEXT.rsplit('\n')[3]
								CH_OR_IMB_OR_AP = TEXT.rsplit('\n')[4]
								if (not CH_OR_IMB_OR_AP.startswith('AP ')
										and not CH_OR_IMB_OR_AP.startswith('Ch.')
										and not CH_OR_IMB_OR_AP.startswith('IMB')):
									SelectShapes([selected.ID])
									msgbox("T'as surement encore fais une connerie dans tes"
												+ "déssins, regarde ce bloc dans la ligne PT!\n"
												+ "Je devrais trouver Ch.XXXX ou AP XXXX"
												+ "ou IMB/XXXX/XXX mais j'ai trouvé\n"
												+ CH_OR_IMB_OR_AP + "\n"
												+ "Quand t'auras détécté l'erreur click sur OK")
									cont = boolbox("Dois-je continuer ou fermer?",
																"Que faire?",
																['Continuer?', 'Fermer?'])
									if not cont:
										exit(0)
									else:
										pass
								else:
									msg = msg + "- " + CH_OR_IMB_OR_AP + "\n"
									CH_OR_IMB_OR_AP_all.append([ADR, CH_OR_IMB_OR_AP])
									PTs.append(int(PT.replace('PT', '')))
							except:
								SelectShapes([selected.ID])
								msgbox("T'as surement encore fais une connerie dans tes"
									+ "déssins, regarde ce bloc dans la ligne PT!\n"
									+ "Quand t'auras détécté l'erreur click sur OK")
								cont = boolbox("Dois-je continuer ou fermer?",
																"Que faire?",
																['Continuer?', 'Fermer?'])
								if not cont:
									exit(0)
								else:
									msg = msg + "(RIEN!)"
									CH_OR_IMB_OR_AP_all = []
									PTs = []
									yn_yes = False
						if not selected_PBs:
							cont = boolbox("Tu n'as rien sélectionné! Tu confirmes"
															+ " que ce n'est pas une connerie?",
															"Sélection vide!",
															['Oui vas-y', 'Comme d\'hab! Une connerie'])
							if cont:
								break
							else:
								continue
						if yn and yn_yes:
							msg = msg + "(" + str(selected_PBs) + " sélectionnés)"
							conf = boolbox(msg, title2, ['Confirmer?', 'Refaire?'])
							if conf:
								TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
								TRs[TR]['PTs'] = PTs
								break
							else:
								pass
						else:
							TRs[TR]['CH/IMB/AP'] = CH_OR_IMB_OR_AP_all
							TRs[TR]['PTs'] = PTs
							break
					else:
						exit(0)
				if len(TRs[TR]['PTs']):
					TRs[TR]['maxPT'] = 'DE_PT%06d' % max(TRs[TR]['PTs']) + '.doc'
				else:
					TRs[TR]['maxPT'] = 'je_ne_suis_pas_cense_exister.doc'
			if TRs == {}:
				msgbox("il n'y pas de TR valide sur ce déssin")
			TRs_all.append(TRs)
			Visio.Visible = False

		RESULTS[PA] = {
			'TRs_all': 	TRs_all,
			'NRO':			NRO,
			'PMZ_PT':		PMZ_PT,
			'PA_PT':		PA_PT,
			'CH':				CH,
			'ADRESSE1':	ADRESSE1,
			'ADRESSE2':	ADRESSE2,
			'DATE':			DATE
		}
		xl.Quit()
		return

	except:
		print(format_exc())
		codebox("t'as encore fais une connerie! Fais moi un screen de malheur!",
						"Erreur",
						format_exc())
		going()
def ForceComparison():
    if True:
        # create new scenario
        uiApp = CreateObject('STK12.Application')
        uiApp.Visible = True
        uiApp.UserControl = True
    
        root = uiApp.Personality2
        root.NewScenario("PerturbingForceComparison")
    else:
        # connect to running scenario
        uiApp = GetActiveObject('STK12.Application')
        uiApp.UserControl = True
        uiApp.Visible = True
        root = uiApp.Personality2
    
    ####################
    ##### SCENARIO #####
    ####################
    sc = root.CurrentScenario
    iagSc = sc.QueryInterface(STKObjects.IAgScenario)
    iagSc.AnalysisInterval.SetStartAndStopTimes("1 Jan 2020 00:00:00.00", "2 Jan 2020 00:00:00.00")
    root.Rewind
    
    
    #############################
    ##### CREATE SATELLITES #####
    #############################
    sats = np.array(["LEO_300km", "LEO_400km", "LEO_600km", "LEO_800km", "GPS", "GEO"])
    sma  = np.array([6678, 6778, 6978, 7178, 26600, 42165])
    inc  = np.array([98.0, 98.0, 98.0, 98.0, 55.0, 0.0])
    
    for thisSat in sats:
        print("Creating */Satellite/" + thisSat)
    
        oSat = sc.Children.New(STKObjects.eSatellite, thisSat)
        sat = oSat.QueryInterface(STKObjects.IAgSatellite)
        
        sat.SetPropagatorType(0) # ePropagatorHPOP
        prop = sat.Propagator.QueryInterface(STKObjects.IAgVePropagatorHPOP)
        prop.Step = 60
        prop.InitialState.Representation.AssignClassical(11, sma[np.where(sats == thisSat)[0]], 0.0, inc[np.where(sats == thisSat)[0]], 0.0, 0.0, 0.0)
    
        forceModel = prop.ForceModel
        forceModel.CentralBodyGravity.File = 'C:\Program Files\AGI\STK 12\STKData\CentralBodies\Earth\WGS84_EGM96.grv'
        forceModel.CentralBodyGravity.MaxDegree = 21
        forceModel.CentralBodyGravity.MaxOrder = 21
        forceModel.Drag.Use=1
        forceModel.Drag.DragModel.Cd=0.01
        forceModel.Drag.DragModel.AreaMassRatio=0.01
        forceModel.SolarRadiationPressure.Use=1
    
        prop.Propagate()
    
    
    
    
    ######################################
    ##### CREATE FORCE MODEL VECTORS #####
    ######################################
    # can't create ForceModel vectors with the OM so connect all the way
    vectors = []
    
    #######################
    ### GRAVITY VECTORS ###
    #######################
    # Point Mass
    GravityVector(root, "PointMass", 0, 0)
    vectors.append("PointMass")
    
    # J2
    GravityVector(root, "J2", 2, 0)
    vectors.append("J2")
    
    # J4
    GravityVector(root, "J4", 4, 0)
    vectors.append("J4")
    
    # J2/2
    GravityVector(root, "J2-2", 2, 2)
    vectors.append("J2-2")
    
    # J4/4
    GravityVector(root, "J4-4", 4, 4)
    vectors.append("J4-4")
    
    # J8/8
    GravityVector(root, "J8-8", 8, 8)
    vectors.append("J8-8")
    
    # J12/12
    GravityVector(root, "J12-12", 12, 12)
    vectors.append("J12-12")
    
    # J24/24
    GravityVector(root, "J24-24", 24, 24)
    vectors.append("J24-24")
    
    # J70/70
    GravityVector(root, "J70-70", 70, 70)
    vectors.append("J70-70")    
    
    
    ######################
    ### CENTRAL BODIES ###
    ######################
    # Sun
    thisVector = "SunForce"
    print("Creating vector: " + thisVector)
    vectors.append(thisVector)
    root.ExecuteCommand("VectorTool * Satellite Create VectorTemplate SunForce \"Force Model\" Scale 1.0 CentralBody Earth")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Force UseCBGravity Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Drag Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Force SRP Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Force ThirdBodyGravity Sun On FromCB")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SunForce \"Force Model\" Force ThirdBodyGravity Moon Off")
    
    # Moon
    thisVector = "MoonForce"
    print("Creating vector: " + thisVector)
    vectors.append(thisVector)
    root.ExecuteCommand("VectorTool * Satellite Create VectorTemplate MoonForce \"Force Model\" Scale 1.0 CentralBody Earth")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Force UseCBGravity Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Drag Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Force SRP Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Force ThirdBodyGravity Sun Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate MoonForce \"Force Model\" Force ThirdBodyGravity Moon On FromCB")
    
    # Mars
    CentralBodyForce(root, "Mars")
    vectors.append("MarsForce")
    
    # Jupiter
    CentralBodyForce(root, "Jupiter")
    vectors.append("JupiterForce")
    
    # Venus
    CentralBodyForce(root, "Venus")
    vectors.append("VenusForce")
    
    # drag
    thisVector = "Drag"
    print("Creating vector: " + thisVector + " using 1000 kg and 20 m^2 area")
    vectors.append(thisVector)
    root.ExecuteCommand("VectorTool * Satellite Create VectorTemplate Drag \"Force Model\" Scale 1.0 CentralBody Earth")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Force UseCBGravity Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Drag On 2.2 0.02 \"Jacchia 1970\" Manual 150 150 3.0")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Force SRP Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Force ThirdBodyGravity Sun Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate Drag \"Force Model\" Force ThirdBodyGravity Moon Off")
    
    
    # srp
    thisVector = "SRP"
    print("Creating vector: " + thisVector + " using 1000 kg and 20 m^2 area")
    vectors.append(thisVector)
    root.ExecuteCommand("VectorTool * Satellite Create VectorTemplate SRP \"Force Model\" Scale 1.0 CentralBody Earth")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Force UseCBGravity Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Drag Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Force SRP On")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Force ThirdBodyGravity Sun Off")
    root.ExecuteCommand("VectorTool * Satellite Modify VectorTemplate SRP \"Force Model\" Force ThirdBodyGravity Moon Off")
    
    
    ####################
    ##### ANALYSIS #####
    ####################
    for thisSat in sats:
        print("Analyzing */Satellite/" + thisSat)
        
        oSat = root.GetObjectFromPath("*/Satellite/" + thisSat)

        # loop through vectors and vector differences of interest
        m = GetAverageMagnitudeNewton(root, oSat, "PointMass")
        m = GetAverageMagnitudeNewton(root, oSat, "J2")
        m = GetAverageMagnitudeNewton(root, oSat, "J2-2")
        m = GetAverageMagnitudeNewton(root, oSat, "J4")
        m = GetAverageMagnitudeNewton(root, oSat, "J4-4")
        m = GetAverageMagnitudeNewton(root, oSat, "J8-8")
        m = GetAverageMagnitudeNewton(root, oSat, "J12-12")
        m = GetAverageMagnitudeNewton(root, oSat, "J24-24")
        m = GetAverageMagnitudeNewton(root, oSat, "J70-70")
        
        m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J2")
        m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J2-2")
        m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J4")
        m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J4-4")
        m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J8-8")
        m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J12-12")
        m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J24-24")
        m = GetAverageDifferenceNewton(root, oSat, "PointMass", "J70-70")
        
        m = GetAverageDifferenceNewton(root, oSat, "J2-2", "J2")
        m = GetAverageDifferenceNewton(root, oSat, "J2", "J4")
        m = GetAverageDifferenceNewton(root, oSat, "J4-4", "J2-2")
        m = GetAverageDifferenceNewton(root, oSat, "J8-8", "J4-4")
        m = GetAverageDifferenceNewton(root, oSat, "J12-12", "J8-8")
        m = GetAverageDifferenceNewton(root, oSat, "J24-24", "J12-12")
        m = GetAverageDifferenceNewton(root, oSat, "J70-70", "J24-24")
        
        m = GetAverageMagnitudeNewton(root, oSat, "SunForce")
        m = GetAverageMagnitudeNewton(root, oSat, "MoonForce")
        m = GetAverageMagnitudeNewton(root, oSat, "MarsForce")
        m = GetAverageMagnitudeNewton(root, oSat, "JupiterForce")
        m = GetAverageMagnitudeNewton(root, oSat, "VenusForce")
        
        m = GetAverageMagnitudeNewton(root, oSat, "Drag")
        m = GetAverageMagnitudeNewton(root, oSat, "SRP")
    
    
    
    
    
    ####################
    ##### CLEAN-UP #####
    ####################
    # delete vectors and satellites
    if False:
        for thisVector in vectors:
            root.ExecuteCommand("VectorTool * Satellite Delete VectorTemplate " + thisVector)
            
        for thisSat in sats:
            oThisSat = root.GetObjectFromPath("*/Satellite/" + thisSat)
            oThisSat.Unload()
Beispiel #34
0
def main():
    """ This is the main script to convert a ArcMap-Project"""
    export_name = arcpy.GetParameterAsText(0)

    if not export_name:
        export_name = "C:\\temp\\test.qgs"

    if export_name.endswith(".qgs") or export_name.endswith(".qgz"):
        export_name_short = export_name[:-4]
    else:
        export_name_short = export_name

    qgs_file_name = u"{}.qgs".format(export_name_short)
    qgs_file = codecs.open(qgs_file_name, "w", encoding="utf-8")

    logging = Logger.get_logger(export_name_short)

    xml_document = Document()

    arcpy.AddMessage("Scanning Project and collecting Layer-Information")

    # take Infos from opened ArcMap-Project -> to access the arcObjects
    arc_app = CreateObject(ArcGisModules.module_framework.AppROT,
                           interface=ArcGisModules.module_framework.IAppROT)
    arc_doc = change_interface(
        arc_app.Item(0).Document, ArcGisModules.module_map_ui.IMxDocument)
    arc_doc_info = change_interface(arc_doc,
                                    ArcGisModules.module_carto.IDocumentInfo2)

    header = create_header(xml_document, arc_doc_info)

    if not arc_doc.ActiveView.IsMapActivated:
        arc_doc.ActiveView = arc_doc.FocusMap

    project_path = ""
    try:
        project_path = os.path.dirname(arc_doc_info.Folder)
    except TypeError:
        print "There is no ArcMap-Project open - Will Crash!"
    arcpy.env.workspace = project_path
    arcpy.env.overwriteOutput = True

    # this is the arcpy connection to the document
    mxd_path = os.path.join(arc_doc_info.Path)
    mxd = arcpy.mapping.MapDocument(mxd_path)

    print 'Start Writing'

    for counter, dataframe in enumerate(arcpy.mapping.ListDataFrames(mxd)):
        if counter == 0:
            print 'Creating MapSpatialReferenceSystem.'
            MapSpatialReferenceSystem.create_map_srs_element(
                xml_document, header, dataframe)

        arc_dataframe = arc_doc.Maps.Item[counter]
        layer_list = arcpy.mapping.ListLayers(dataframe)

        arcpy.AddMessage("{} Layers are in the Dataframe".format(
            str(len(layer_list))))

        ProjectLayers.create_project_layers_element(xml_document, header,
                                                    layer_list, arc_dataframe)
        broken_layer_list = brokenLayers.BrokenLayers.broken_layer_list
        for broken_layer in broken_layer_list:
            if broken_layer in layer_list:
                layer_list.remove(broken_layer)
        MapLegend.create_map_legend_element(xml_document, header, layer_list,
                                            dataframe)
        LayerTree.create_layertree(xml_document, header, layer_list, dataframe)
        MapProperties.create_map_properties_element(xml_document, header)

    if len(arcpy.mapping.ListDataFrames(mxd)) > 1:
        VisibilityPresets.initialize_visibility(xml_document, header, mxd)

    arcpy.AddMessage("Creating Layout")
    logging.info("Creating Layout")
    layout = Layout(xml_document, header, arc_doc, mxd).create_layout()

    arcpy.AddMessage("Creating Metadata")
    Metadata.create_metadata(xml_document, header, arc_app)

    try:
        xml_document.writexml(qgs_file,
                              indent="  ",
                              addindent="  ",
                              newl="\n",
                              encoding="UTF-8")
        arcpy.AddMessage("Project saved!")
        arcpy.AddMessage('QGIS-File written')
    finally:
        qgs_file.close()

    if export_name.endswith(".qgz"):
        qgd_file_name = u"{}.qgd".format(export_name_short)
        qgd_file = open(qgd_file_name, "w")
        qgd_file.close()

        with ZipFile(u"{}.qgz".format(export_name_short), "w") as newzip:
            newzip.write(qgs_file_name, os.path.basename(qgs_file.name))
            newzip.write(qgd_file_name, os.path.basename(qgd_file.name))

        arcpy.AddMessage(' and zipped.')
        try:
            os.remove(qgs_file_name)
            os.remove(qgd_file_name)
        except OSError as e:
            print("Error: %s - %s." % (e.filename, e.strerror))
import os
import glob
import CommonMark
import sys

if not os.path.exists("images"):
    os.mkdir("images")
else:
    import shutil
    shutil.rmtree("images")
    os.mkdir("images")

image_directory = pathlib.Path("images")
temp_directory = pathlib.Path(tempfile.mkdtemp())

word = CreateObject("Word.Application")
word.Visible = False
from comtypes.gen import Word as constants

imagemagick = os.path.join(os.environ["MAGICK_HOME"], "convert.exe")

# [(file name, word image, html image)]
results = []


if __name__ == "__main__":
    if len(sys.argv) != 1:
        file_names = [pathlib.Path(p) for p in sys.argv[1:]]
    else:
        file_names = list(pathlib.Path("docs").iterdir())
Beispiel #36
0
class mzFile(mzAPImzFile):
    def __init__(self, file_name, *args, **kwargs):
        self.file_type = 'raw'
        self.data_file = file_name
        
        try:
            self.source = CreateObject("{10729396-43ee-49e5-aa07-85f02292ac70}")
        except WindowsError as err:
            print "RawReader.dll not found in registry."
            raise err
        except COMError:
            # As far as I know, this should only happen if you're trying to 
            # run this in Python 3.
            self.source = CreateObject("{10729396-43ee-49e5-aa07-85f02292ac70}",
                                       dynamic = True)
        self.source.OpenRawFile(file_name)
        
        self._filters = None
        self._scaninfo = None
        
        # A bunch of functions are pure C#.
        self.scan_range = self.source.scan_range
        self.time_range = self.source.time_range
        self.time_for_scan = self.source.time_from_scan
        self.scan_for_time = self.source.scan_from_time
        self.scanForTime = self.source.scan_from_time
        self.timeForScan = self.source.time_from_scan
        self.scan_time_from_scan_name = self.source.time_from_scan
        
        
    
    def scan(self, scan_number, centroid = False):
        if isinstance(scan_number, float): # Taken as a scan time.
            scan_number = self.source.scan_from_time(scan_number)
        if centroid:
            return [x[:2] for x in self.source.centroid_scan(scan_number)]
        else:
            return list(self.source.profile_scan(scan_number))
    
    def lscan(self, scan_number):
        scan = self.source.centroid_scan(scan_number)
        if len(scan[0]) < 4:
            raise IOError, "Full lscan data not available for scan %s" % scan_number
        return [x[:4] for x in scan]
    
    def rscan(self, scan):
        return list(self.source.centroid_scan(scan))
    
    def average_scan(self, startscan, stopscan, filter):
        return list(self.source.average_scan(startscan, stopscan, filter))
    
    def filters(self):
        if not self._filters:
            filterlist = zip(self.source.GetAllFilterInfoTimes(),
                             self.source.GetAllFilterInfo())
            self._filters = [(time, string) for time, string in filterlist
                             if time and string]
            
        return self._filters
    
    def extra_info(self, scan):
        info = {}
        for key, val in self.source.get_extra_scan_info(scan):
            key = key.strip(':')
            try:
                info[key] = float(val)
            except ValueError:
                info[key] = val
        return info
    
    def scanInjectionTime(self, scan):
        keys, vals = zip(*self.source.get_extra_scan_info(scan))
        try:
            return float(vals[keys.index('Ion Injection Time (ms):')])
        except ValueError:
            return float(vals[keys.index('Ion Injection Time (ms):')].replace(',', ''))
    
    def scanPrecursor(self, scan):
        keys, vals = zip(*self.source.get_extra_scan_info(scan))
        return (float(vals[keys.index('Monoisotopic M/Z:')]),
                float(vals[keys.index('Charge State:')]))
        
    
    def scan_info(self, start_time=0, stop_time=None, start_mz=0, stop_mz=100000):
        if not self._scaninfo:
            self._scaninfo = []
            
            for scan in range(*self.scan_range()):
                info = self.source.GetFilterInfoForScan(scan)
                time = self.source.time_from_scan(scan)
                self._scaninfo.append((time, float(info[1]), scan,
                                       info[0].upper() if info[0].upper() != 'MS' else 'MS1',
                                       'p' if info[2] == 'Profile' else 'c'))
                
        if start_time:
            start_scan = self.scanForTime(start_time)
        else:
            start_scan = self.scan_range()[0]
        if stop_time:
            stop_scan = self.scanForTime(stop_time)
        else:
            stop_scan = self.scan_range()[1]        
        return [x for x in self._scaninfo if 
                start_scan <= x[2] <= stop_scan and
                start_mz <= x[1] <= stop_mz]
    
    def headers(self):
        return self.scan_info()
               
    def xic(self, start_time = -1, stop_time = -1, start_mz = -1, stop_mz = -1, filter=None):
        if start_time == -1 and stop_time == -1 and start_mz == -1 and stop_mz == -1 and filter==None:
            return self.tic()
        if not filter:
            filter = 'Full ms '
        if start_time != -1:
            start_time = self.scanForTime(start_time)
        if stop_time != -1:
            stop_time = self.scanForTime(stop_time)
        return list(self.source.get_xic(start_time, stop_time, start_mz, stop_mz, filter))
    
    def tic(self):
        return list(self.source.get_tic())
    
    def close(self):
        pass # Check for memory leaks!
    

    
    def centroid(self, scan, *foo, **bar):
        print "mzFile.centroid is deprecated, use mzFile.scan(..., centroid = True) instead."
        return self.scan(scan, centroid = True)
    

                
import pyttsx
from comtypes.client import CreateObject
from comtypes.gen import SpeechLib

stream = CreateObject("SAPI.SpFileStream")

engine = pyttsx.init()
engine.setProperty('rate', 70)

outfile = "prompt.wav"
stream.Open(outfile, SpeechLib.SSFMCreateForWrite)
engine.AudioOutputStream = stream

voices = engine.getProperty('voices')
for voice in voices:
    print "Using voice:", repr(voice)
    engine.setProperty('voice', voice.id)
    engine.say("Hi there, how's you ?")
    engine.say("A B C D E F G H I J K L M")
    engine.say("N O P Q R S T U V W X Y Z")
    engine.say("0 1 2 3 4 5 6 7 8 9")
    engine.say("Sunday Monday Tuesday Wednesday Thursday Friday Saturday")
    engine.say("Violet Indigo Blue Green Yellow Orange Red")
    engine.say("Apple Banana Cherry Date Guava")
#engine.runAndWait()

stream.close()
from subprocess import call
from os.path import dirname
import abtronics
from time import sleep
from glob import glob
from ntpath import basename

shell = Dispatch("Shell.Application")
ADDUC_FOLDER = shell.BrowseForFolder(0, "Séléctionnez le dossier qui contient les fiches d'addoctibilité et ka fiche PA", 1)
ADDUC_FOLDER = ADDUC_FOLDER.Self.Path
XLS = glob(ADDUC_FOLDER + sep + "*.xls")
ADDUCS = [xls for xls in XLS if not basename(xls).startswith('PA')]
PA = [xls for xls in XLS if basename(xls).startswith('PA')][0]
print('nombre de fiches addc', len(ADDUCS))

xl = CreateObject("Excel.application")
xl.Visible = False
xl.DisplayAlerts = False
pa_wb = xl.Workbooks.Open(PA)
#adduc_sheet = pa_wb.Sheets.Add(After=pa_wb.Sheets(pa_wb.Sheets.Count))
adduc_sheet = pa_wb.Sheets.Add(After=pa_wb.Sheets(7))
adduc_sheet.Name = "Adductibilité des sites"

start_row = 1

def merge(adduc):
	global xl
	global pa_wb
	global start_row
	adduc_wb = xl.Workbooks.Open(adduc)
	for cell in adduc_wb.Sheets(1).Range('C8:C1000'):
 def __init__(self, rr_x=1000, rr_y=1000):
     self.rr = CreateObject("RoboRealm.API.1")
     self.rr_x = rr_x
     self.rr_y = rr_y
Beispiel #40
0
import unittest
from ctypes import POINTER
from comtypes.automation import IDispatch
from comtypes.client import CreateObject
from comtypes import GUID

##from test import test_support
##from comtypes.unittests import support

try:
    GUID.from_progid("MSScriptControl.ScriptControl")
    CreateObject("MSScriptControl.ScriptControl")
except WindowsError:
    # doesn't exist on Windows CE or in 64-bit.
    pass
else:

    class Test(unittest.TestCase):
        def test_jscript(self):
            engine = CreateObject("MSScriptControl.ScriptControl")
            engine.Language = "JScript"
            # strange.
            #
            # engine.Eval returns a VARIANT containing a dispatch pointer.
            #
            # The dispatch pointer exposes this typeinfo (the number of
            # dispproperties varies, depending on the length of the list we pass
            # to Eval):
            #
            #class JScriptTypeInfo(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDispatch):
            #    'JScript Type Info'
Beispiel #41
0
from InstrumentConfig import InstrumentQuantity
from numpy import log10, array
import numpy as np
#import visa
from comtypes.client import CreateObject#, GetModule
#from pythoncom import CoInitialize
from comtypes import CoInitialize


#Ensure module is created before importing
#Back up code to create module:
#GetModule("AgNA.dll")
try:
    import comtypes.gen.AgilentNALib as AgilentNALib
except ImportError:
    VNA=CreateObject('AgilentNA.AgilentNA')
    VNA.Release()
    import comtypes.gen.AgilentNALib as AgilentNALib


def cached_property(default_func):
    """a cached property decorator. only resets when set to None"""
    def get_value(self):
        if get_value.value is None:
            get_value.value=default_func(self)
        return get_value.value
    get_value.value=None

    def set_value(self, value):
        get_value.value=value
        
Beispiel #42
0
    opts, args = getopt.getopt(sys.argv[1:], "n:f:",
                               ["number of groups", "file"])
except getopt.GetoptError as err:
    print(err)
    print("\tUse -n to set number of generating groups\n"
          "\tUse -f to set path to destination file")
    sys.exit(2)

n = 5
f = "data/groups.xlsx"

for o, a in opts:
    if o == "-n":
        n = int(a)
    elif o == "-f":
        f = a

project_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
file = os.path.join(project_dir, f)

xl = CreateObject("Excel.Application")
try:
    xl.Visible = 0
    xl.DisplayAlerts = False
    wb = xl.Workbooks.Add()
    for i in range(n):
        xl.Range[f"A{i + 1}"].Value[()] = random_string("group", 10)
    wb.SaveAs(file, ConflictResolution=xlLocalSessionChanges)
finally:
    xl.Quit()
Beispiel #43
0
        COMMETHOD([], HRESULT, 'SetOverlayIcon', (['in'], c_int, 'hwnd'),
                  (['in'], POINTER(IUnknown), 'hIcon'),
                  (['in'], c_wchar_p, 'pszDescription')),
        COMMETHOD([], HRESULT, 'SetThumbnailTooltip', (['in'], c_int, 'hwnd'),
                  (['in'], c_wchar_p, 'pszTip')),
        COMMETHOD([], HRESULT, 'SetThumbnailClip', (['in'], c_int, 'hwnd'),
                  (['in'], POINTER(tagRECT), 'prcClip')),
    ]


class TaskbarList(CoClass):
    _com_interfaces_ = [ITaskbarList3]
    _reg_clsid_ = COMGUID('{56FDF344-FD6D-11D0-958A-006097C9A090}')


_taskbar = CreateObject(TaskbarList)
_taskbar.HrInit()


def _get_wsa_error():
    err = WSAGetLastError()
    try:
        return socket.errorTab[err]
    except KeyError:
        return os.strerror(err)


def dup(s):
    '''Duplicate a SOCKET.'''
    info = WSAPROTOCOL_INFO()
    if WSADuplicateSocket(s, os.getpid(), byref(info)):
Beispiel #44
0
class Device(object):
    def __init__(self, devnum=0, show_video_window=False):
        self.devnum = devnum
        self.show_video_window = show_video_window
        self.initialize()

    def initialize(self):
        self.filter_graph = CreateObject(FilterGraph)
        self.control = self.filter_graph.QueryInterface(IMediaControl)
        self.graph_builder = CreateObject(CaptureGraphBuilder2)
        self.graph_builder.SetFiltergraph(self.filter_graph)
        dev_enum = CreateObject(DeviceEnumerator)
        class_enum = dev_enum.CreateClassEnumerator(
            CLSID_VideoInputDeviceCategory, 0)
        #del dev_enum

        for iCount in xrange(self.devnum):
            try:
                (moniker, fetched) = class_enum.RemoteNext(1)
            except ValueError:
                raise RuntimeError("Device not found")

        # del class_enum

        null_context = POINTER(IBindCtx)()
        null_moniker = POINTER(IMoniker)()
        self.source = moniker.RemoteBindToObject(null_context, null_moniker,
                                                 IBaseFilter._iid_)

        self.filter_graph.AddFilter(self.source, "VideoCapture")

        self.grabber = CreateObject(SampleGrabber)
        self.filter_graph.AddFilter(self.grabber, "Grabber")

        mt = tag_AMMediaType()
        mt.majortype = MEDIATYPE_Video
        mt.subtype = MEDIASUBTYPE_RGB24
        mt.formattype = FORMAT_VideoInfo

        self.grabber.SetMediaType(mt)

        self.graph_builder.RenderStream(
            PIN_CATEGORY_CAPTURE,
            MEDIATYPE_Video,
            self.source,
            self.grabber,
            None,
        )

        window = self.filter_graph.QueryInterface(IVideoWindow)
        window.AutoShow = [OA_FALSE, OA_TRUE][self.show_video_window]

        self.grabber.SetBufferSamples(True)
        self.grabber.SetOneShot(False)

    def teardown(self):
        if hasattr(self, 'control'):
            self.control.Stop()
            self.control.Release()
            del self.control
        if hasattr(self, 'grabber'):
            self.grabber.Release()
            del self.grabber
        if hasattr(self, 'graph_builder'):
            self.graph_builder.Release()
            del self.graph_builder
        if hasattr(self, 'filter_graph'):
            self.filter_graph.Release()
            del self.filter_graph

    def display_capture_filter_properties(self):
        self.control.Stop()
        self._do_property_pages(self.source)

    @staticmethod
    def _do_property_pages(subject):
        spec_pages = subject.QueryInterface(ISpecifyPropertyPages)
        cauuid = spec_pages.GetPages()
        if cauuid.element_count > 0:
            # self.teardown()
            # self.initialize()
            OleCreatePropertyFrame(windll.user32.GetTopWindow(None), 0, 0,
                                   None, 1, byref(cast(subject, LPUNKNOWN)),
                                   cauuid.element_count, cauuid.elements, 0, 0,
                                   None)
            windll.ole32.CoTaskMemFree(cauuid.elements)
            # self.teardown()
            # self.initialize()

    def display_capture_pin_properties(self):
        self.control.Stop()
        self._do_property_pages(self._get_stream_config())

    def _get_graph_builder_interface(self, interface):
        args = [
            PIN_CATEGORY_CAPTURE,
            MEDIATYPE_Interleaved,
            self.source,
            interface._iid_,
        ]
        try:
            result = self.graph_builder.RemoteFindInterface(*args)
        except COMError:
            args[1] = MEDIATYPE_Video
            result = self.graph_builder.RemoteFindInterface(*args)
        return cast(result, POINTER(interface)).value

    def _get_stream_config(self):
        return self._get_graph_builder_interface(IAMStreamConfig)

    def _get_video_control(self):
        return self._get_graph_builder_interface(IAMVideoControl)

    def _get_ppin(self):
        try:
            return self.graph_builder.FindPin(self.source, PINDIR_OUTPUT,
                                              PIN_CATEGORY_CAPTURE,
                                              MEDIATYPE_Interleaved, False, 0)
        except COMError:
            return self.graph_builder.FindPin(self.source, PINDIR_OUTPUT,
                                              PIN_CATEGORY_CAPTURE,
                                              MEDIATYPE_Video, False, 0)

    def get_capabilities(self):
        video_control = self._get_video_control()
        ppin = self._get_ppin()
        return video_control.GetCaps(ppin)

    def _get_mode(self):
        video_control = self._get_video_control()
        ppin = self._get_ppin()
        return video_control.GetMode(ppin)

    # http://msdn.microsoft.com/en-us/library/dd407321(VS.85).aspx
    def set_mode(self, mode, value):
        video_control = self._get_video_control()
        ppin = self._get_ppin()
        mode_val = video_control.GetMode(ppin)
        vc_flags = VideoControlFlags.from_number(mode_val)
        vc_flags[mode] = bool(value)
        video_control.SetMode(ppin, vc_flags.number)
        new_mode_val = video_control.Getmode(ppin)
        if new_mode_val == mode_val:
            log.warning("Mode value appears unchanged on attempt to set %s",
                        mode)

    def set_resolution(self, width, height):
        self.control.Stop()
        stream_config = self._get_stream_config()
        p_media_type = stream_config.GetFormat()
        media_type = p_media_type.contents
        if media_type.formattype != FORMAT_VideoInfo:
            raise VidCapError("Cannot query capture format")
        p_video_info_header = cast(media_type.pbFormat,
                                   POINTER(VIDEOINFOHEADER))
        hdr = p_video_info_header.contents.bmi_header
        hdr.width, hdr.height = width, height
        stream_config.SetFormat(media_type)
        DeleteMediaType(media_type)
        #stream_config.Release()
        #self.teardown()
        #self.initialize()

    def get_buffer(self):
        media_type = tag_AMMediaType()
        self.grabber.GetConnectedMediaType(media_type)

        p_video_info_header = cast(media_type.pbFormat,
                                   POINTER(VIDEOINFOHEADER))

        # windll.ole32.CoTaskMemFree(media_type.pbFormat) ?

        hdr = p_video_info_header.contents.bmi_header
        size = hdr.image_size
        width = hdr.width
        height = hdr.height
        assert size % 4 == 0
        buffer = create_string_buffer(size)
        long_p_buffer = cast(buffer, POINTER(c_long))
        size = c_long(size)

        self.control.Run()

        try:
            while (True):
                # call the function directly, as the in/out symantics of
                # argtypes isn't working here.
                try:
                    GetCurrentBuffer = self.grabber._ISampleGrabber__com_GetCurrentBuffer
                    GetCurrentBuffer(byref(size), long_p_buffer)
                except COMError as e:
                    if e.args[0] == VFW_E_WRONG_STATE:
                        time.sleep(.100)
                    else:
                        raise
                else:
                    break
        except COMError as e:

            error_map = dict(
                E_INVALIDARG="Samples are not being buffered",
                E_POINTER="NULL pointer argument",
                VFW_E_NOT_CONNECTED="The filter is not connected",
                VFW_E_WRONG_STATE="The filter did not buffer a sample yet",
            )
            code = e[0]
            unknown_error = 'Unknown Error ({0:x})'.format(code)
            msg = "Getting the sample grabber's current buffer failed ({0}).".format(
                error_map.get(code, unknown_error))
            raise VidCapError(msg)

        return bytes(buffer[:size.value]), (width, height)

    def get_image(self):
        """Returns a PIL Image instance.

		textpos:
			The position of the timestamp can be specified by a string
			containing a combination of two words specifying the vertical
			and horizontal position of the timestamp.  Abbreviations
			are allowed.
			Vertical positions: top or bottom
			Horizontal positions: left, center, right

			defaults to 'bottom-left'
		"""
        buffer, dimensions = self.get_buffer()
        # todo, what is 'BGR', 0, -1 ?
        img = PIL.Image.frombytes('RGB', dimensions, buffer, 'raw', 'BGR', 0,
                                  -1)
        return img

    def getImage(self):
        return self.get_image()

    @staticmethod
    def _get_shadow_draw_locations(origin, shadow_style):
        x, y = origin
        outline_locs = ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1))
        shadow_draw_locations = dict(
            simple=(),
            shadow=((x + 1, y), (x, y + 1), (x + 1, y + 1)),
            outline=outline_locs,
        )
        shadow_draw_locations['thick-outline'] = (outline_locs +
                                                  ((x - 1, y - 1),
                                                   (x + 1, y - 1),
                                                   (x - 1, y + 1),
                                                   (x + 1, y + 1)))
        locs = shadow_draw_locations.get(shadow_style)
        if locs is None:
            raise ValueError("Unknown shadow style {0}".format(shadow_style))
        return locs

    def save_snapshot(self, filename, *args, **kwargs):
        """
		Saves a snapshot to a file.

		The filetype is inferred from the filename extension. Everything that
		PIL can handle can be specified (foo.jpg, foo.gif, foo.bmp, ...).

		filename: String containing the name of the resulting file.

		Any additional arguments are passed to the save() method of the image
		class.
		For example you can specify the compression level of a JPEG image using
		'quality=95'.
		"""
        self.get_image().save(filename, **kwargs)
Beispiel #45
0
import pyttsx3 as pyttsx  #使用pyttsx实现
engine = pyttsx.init()  #初始化
engine.say('大家好')  #文字转化语音
engine.runAndWait()  #运行
#***********************************
from win32com.client import Dispatch  #导入Dispatch对象
sperker = Dispatch('SAPI.SpVoice')  #生成对象
str = open("1.txt", encoding="utf-8").read()  #打开文本
sperker.Speak(str)  #朗读
sperker.Speak('我是赵桐')
del sperker  #释放对象
#***********************************
from comtypes.client import CreateObject
from comtypes.gen import SpeechLib
engine = CreateObject("SAPI.SpVoice")
stream = CreateObject('SAPI.SpFileStream')  #输出流
stream.open('1.wav', SpeechLib.SSFMCreateForWrite)
engine.AudioOutputStream = stream  #接通管道
f = open('1.txt', 'r', encoding='utf-8')  #读取文本内容
engine.speak(f.read())  #输出到1.wav
f.close()  #关闭文件
stream.close()  #输出流关闭
Beispiel #46
0
def init(portName):
    # pickup global instances of port, ser and sapi variables
    global port, ser, sapivoice, sapistream, connected, directory

    _loadEyeShapes()
    _loadMotorDefs()

    silenceFile = os.path.join(directory, 'Silence1.wav')

    # get the sapi objects ready on Windows
    if platform.system() == "Windows":
        sapivoice = CreateObject("SAPI.SpVoice")
        sapistream = CreateObject("SAPI.SpFileStream")
        winsound.PlaySound(silenceFile, winsound.SND_FILENAME)

    # get the audio system warmed up on Mac
    if platform.system() == "Darwin":
        playsound(silenceFile)

    # get the audio system warmed up on linux
    if platform.system() == "Linux":
        os.system('aplay ' + silenceFile)

    # Search for the Picoh serial port
    ports = list(serial.tools.list_ports.comports())
    for p in ports:

        # If port has Picoh connected save the location
        if portName in p[1]:
            port = p[0]
            print("Picoh found on port:" + port)
            connected = True
        elif portName in p[0]:
            port = p[0]
            print("Picoh found on port:" + port)
            connected = True

    # If not found then try the first port
    if port == "":
        for p in ports:
            port = p[0]
            print("Picoh not found")
            connected = False
            break

    if port == "":
        print("Picoh port " + portName + " not found")
        return False

    # Open the serial port
    if connected:
        ser = serial.Serial(port, 19200)
        ser.timeout = None
        ser.write_timeout = None

    # Set read timeout and write timeouts to blocking

    # Make an initial call to Festival without playing the sound to check it's all okay
    text = "Hi"

    # Create a bash command with the desired text. The command writes two files, a .wav with the speech audio and a
    # .txt file containing the phonemes and the times.

    if synthesizer.lower() != "festival":
        _generateSpeechFile(text)
        

    _loadSpeechDatabase()

    return True
Beispiel #47
0
import os

# Requires pip3 install comtypes
# Tested with comtypes-1-17 
# https://pypi.org/project/comtypes/
import comtypes

print("Beginning test of Microsoft Speech API")

# Using the Microsoft Speech API (SpVoice) 
# https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms723602(v%3Dvs.85)
from comtypes.client import CreateObject
engine = CreateObject("SAPI.SpVoice")
engine.speak("Hello World")



# using pyttsx3 - Offline text to speech for python3
# https://pythonprogramminglanguage.com/text-to-speech/
# https://pyttsx3.readthedocs.io/en/latest/
# https://github.com/nateshmbhat/pyttsx3
# 
# ****  error says that engine isn't found...?
# import pyttsx
# engine = pyttsx.init()
# engine.say("I will speak this text")
# engine.runAndWait()



Beispiel #48
0
class SKQuote(SKThread):
    notifystocklist = QtCore.pyqtSignal(int, list)
    notifyquote = QtCore.pyqtSignal(int, object)

    def __init__(self, parent=None):
        super(__class__, self).__init__(parent)
        #Create COM Object
        self.skquote = CreateObject(self.module.SKQuoteLib,
                                    interface=self.module.ISKQuoteLib)
        #create COM Event
        self.skquoteevents = SKQuoteLibEvents()
        #To regist COM Event to COM Object
        self.quoteConn = GetEvents(self.skquote, self.skquoteevents)

        #This timer is for quote to request the time server for avoid server disconnect this link
        self.keeptimer = QtCore.QTimer()
        self.keeptimer.setInterval(15000)  #15 sec
        self.keeptimer.setSingleShot(False)
        self.keeptimer.timeout.connect(self.on_timer_timeout_cb)

        #Events
        self.skquoteevents.onconnection.connect(self.on_onconnection_cb)
        self.skquoteevents.onnotifyservertime.connect(
            self.on_onnotifyservertime_cb)
        self.skquoteevents.onnotifystocklist.connect(
            self.on_onnotifystocklist_cb)
        self.skquoteevents.onnotifyquote.connect(self.on_onnotifyquote_cb)

    def enterMonitor(self):
        ret = self.skquote.SKQuoteLib_EnterMonitor()
        if ret == 0:
            self.message.emit('[SKQuote] Enter Monitor success')
            self.keeptimer.start()
            return True

        self.message.emit('[SKQuote: %d] %s' % (ret, SKCode[ret][1]))
        return False

    def leaveMonitor(self):
        ret = self.skquote.SKQuoteLib_LeaveMonitor()
        if ret == 0:
            self.message.emit('[SKQuote] Leave Monitor success')
            self.keeptimer.stop()
            return True

        self.message.emit('[SKQuote: %d] %s' % (ret, SKCode[ret][1]))
        return False

    def requestStockList(self, index):
        ret = self.skquote.SKQuoteLib_RequestStockList(index)
        if ret == 0:
            self.message.emit('[SKQuote] Request Stock success')
            return True

        self.message.emit('[SKQuote: %d] %s' % (ret, SKCode[ret][1]))
        return False

    def requestStocks(self, bstrStockNo):
        page, ret = self.skquote.SKQuoteLib_RequestStocks(-1, bstrStockNo)
        return ret

    #
    # Events
    #
    def on_onconnection_cb(self, nKind, nCode):
        if nKind == 3003 and nCode == 0:
            self.message.emit('[SKQuote] Connect success')
        elif nCode is not 0:
            self.message.emit('[SKQuote %d] %s' % (nCode, SKCode[nCode][0]))

    def on_onnotifyservertime_cb(self, sHour, sMinute, sSecond, nTotal):
        self.message.emit('[SKQuote] server time: %2d:%2d:%2d %d' %
                          (sHour, sMinute, sSecond, nTotal))

    def on_onnotifystocklist_cb(self, sMarketNo, bstrStockData):
        sp = []
        for s in bstrStockData.split(';'):
            if len(s) is 0:
                continue
            sp.append(s.split(','))
        self.notifystocklist.emit(sMarketNo, sp)

    def on_timer_timeout_cb(self):
        self.skquote.SKQuoteLib_RequestServerTime()

    def on_onnotifyquote_cb(self, sMarketNo, sIndex):
        pSKStock = self.module.SKSTOCK()
        pSKStock, ret = self.skquote.SKQuoteLib_GetStockByIndex(
            sMarketNo, sIndex, pSKStock)
        #pSKStock, ret = self.skquote.SKQuoteLib_GetStockByNo(sMarketNo, pSKStock)
        self.notifyquote.emit(ret, pSKStock)
Beispiel #49
0
# coding: utf-8

from comtypes.client import CreateObject
from comtypes.gen import SpeechLib

engine = CreateObject("SAPI.SpVoice")
stream = CreateObject("SAPI.SpFileStream")

outfile = "test.wav"
stream.Open(outfile, SpeechLib.SSFMCreateForWrite)
engine.AudioOutputStream = stream

print engine.GetVoices().Count
engine.Voice=engine.GetVoices().Item(1)
engine.Rate = 2

engine.speak(u'La température extérieure est de 4,7°Centigrades.')
engine.speak(u"Bonsoir Nicolas... Est-ce que ta journée de travail s'est bien passée?")
engine.speak(u"La factrice est passée, ce matin. Et on a sonné deux fois à la porte, à 17h34 et 18h27, en ton absence.")

stream.Close()
Beispiel #50
0
class Driver(InstrumentWorker):
    """ This class implements the Agilent 5230 PNA driver"""

    @cached_property
    def cData(self):
        return {} #self.acquire_data()
    
    @cached_property
    def t0(self):
        return self.StartFrequency.receive()
    
    @cached_property
    def dt(self):
        return (self.StopFrequency.receive()-self.StartFrequency.receive())/(self.Points.receive()-1)  

    @cached_property
    def S_enabled(self):
        return {name[:3] : self.getValue(name) for name in self.S_enabled_names}

    @cached_property
    def S_enabled_names(self):
        return tuple('{0} - Enabled'.format(name) for name in self.measDict)
        
        
    #@property
    #def eSweepType(self):
    #    return self.getValue('Sweep type')
        
    #@property
    #def fStartFrequency(self):
    #    startFreq = self.getValue("Start frequency")
    #    if self.eSweepType == 'Log':
    #        return log10(startFreq)
    #    return startFreq

    #@property
    #def fStopFrequency(self):
    #    stopFreq=self.getValue("Stop frequency")
    #    if self.eSweepType == 'Log':
    #        return log10(stopFreq) 
    #    return stopFreq

    #@property
    #def bWaitTrace(self):
    #    return self.getValue('Wait for new trace')

    #@property    
    #def bAverage(self):
        #return self.ch1.Averaging
    #    return self.getValue('Average')
                    
    def writeVNA(self, input_str):
        self.log("WriteString: {0}".format(input_str))
        self.VNA.System2.WriteString(input_str)
        
    def readVNA(self):
        value=self.VNA.System2.ReadString()
        self.log("ReadString: {0}".format(value))
        return value

    def askVNA(self, input_str):
        self.writeVNA(input_str)
        return self.readVNA()

    def acquire_data(self):
        self.ch1.ClearAverage()
        if self.Averaging.value:
            numTriggers=self.AveragingFactor.value
        else:
            numTriggers=1
        self.log(numTriggers)
        for n in range(numTriggers):
            #if self.needs_abort:
            #    break
            self.log(n)
            self.log(self.ch1.TriggerSweep(1000))
            self.log(self.VNA.System2.WaitForOperationComplete(10000))
        for key in self.measDict:
            self.log((key, self.S_enabled[key]))
            if self.S_enabled[key]:
                data=array(self.measDict[key].FetchComplex())
                self.cData[key]=data[0]+1.0j*data[1]
                if 0:
                    self.measDict[key].FetchX()
                    self.measDict[key].Trace.AutoScale()
        #self.needs_abort=False
        
    def VNAabort(self):
        self.VNA.Channels.Abort()
        self.VNA.Status.Clear()
        self.writeVNA("CALC:PAR:DEL:ALL")
        self.ch1.TriggerMode=TriggerModeDict['Hold']
        #self.needs_abort=True
                
    def performOpen(self, options={}):
        """Perform the operation of opening the instrument connection. Initializes a measurement param dictionary
        and calls the generic VISA_Driver open
        Calls an IVI-COM driver. importing of library is delayed"""
        
        CoInitialize()
        self.VNA=CreateObject('AgilentNA.AgilentNA')
        self.log("VNA object created")
        self.VNA.Initialize( "TCPIP::129.16.115.134::5025::SOCKET", False, False, "")
        self.log("VNA Initialized")
        
        self.ch1=self.VNA.Channels["Channel1"]
        self.VNAabort()
        #self.needs_abort=False
        self.measDict=dict(S11=self.ch1.Measurements["Measurement1"],
                           S21=self.ch1.Measurements["Measurement2"],
                           S12=self.ch1.Measurements["Measurement3"],
                           S22=self.ch1.Measurements["Measurement4"])
        #sAll=self.askVNA("CALC:PAR:CAT:EXT?")
        #t=sAll[1:-1].split(",")
        #self.log({t[i]:t[i+1] for i in range(0, len(t), 2)})  
        #
        #self.ch1.TriggerMode=TriggerModeDict['Hold']                       
        #self.prop_dict={}
        self.Averaging=Prop(self.ch1, 'Averaging')
        self.IFBandwidth=Prop(self.ch1, 'IFBandwidth')
        self.Points=Prop(self.ch1, "Points", coercer=int)
        self.AveragingFactor=Prop(self.ch1, "AveragingFactor", coercer=int)
        self.StopFrequency=Prop(self.ch1.StimulusRange, "Stop")
        self.StartFrequency=Prop(self.ch1.StimulusRange, "Start")
        self.Span=Prop(self.ch1.StimulusRange, "Span")
        self.CenterFrequency=Prop(self.ch1.StimulusRange, "Center")
        self.OutputPower=Prop(self.ch1.SourcePower, "Level", 1)
        #self.OutputPower2=Prop(self.ch1.SourcePower, "Level", 2)
        self.prop_dict=get_prop_dict(self)
        for key in self.prop_dict:
            getattr(self, key).value=self.getValue(key)

        #self.prop_mapping=get_mapping(prop_dict)
                    
        #self.log(self.prop_dict)
        #VNA.Channels["Channel1"].SweepTimeAuto
        #VNA.Channels["Channel1"].SweepType
        #VNA.Channels["Channel1"].SweepMode

        #VNA.Channels["Channel1"].SweepTime    
#    
#        meas.Create(1,1)
#        meas.Format=0

#        
#        VNA.Channels["Channel1"].TriggerMode
    def performClose(self, bError=False, options={}):
        self.VNAabort()
        self.VNA.Close( )
        self.log("VNA Closed")
        self.VNA.Release()
        self.log("VNA object released")
        
    def performSetValue(self, quant, value, sweepRate=0.0, options={}):
        """Perform the Set Value instrument operation. This function should
        return the actual value set by the instrument. Runs standard VISA set except
        for enabling S parameters and wait for new trace"""
        attr=getattr(self, quant.name, None)
        if attr is not None:
            return attr.send(value)
        elif quant.name == "Output enabled":
            if value:
                self.writeVNA(":OUTP 1")
            else:
                self.writeVNA(":OUTP 0")
        
        elif quant.name in self.S_enabled_names:
            key=quant.name[:3]
            if value:
                ReceiverPort=int(key[1])
                SourcePort=int(key[2])
                self.log((ReceiverPort, SourcePort))
                self.measDict[key].Create(ReceiverPort, SourcePort)
                self.measDict[key].Format=0
            else:
                if self.S_enabled[key]:
                    self.measDict[key].Delete()
            self.S_enabled[key]=value
        elif quant.name == "Abort":
            self.abort()
                # old-type handling of traces
                #if param in self.dMeasParam:
                    # clear old measurements for this parameter
                #    for name in self.dMeasParam[param]:
                #        self.writeVNA("CALC:PAR:DEL '{0}'".format(name))
                # create new measurement, if enabled is true
                #if value:
                #    newName = 'LabC_{0}'.format(param)
                #    self.writeVNA("CALC:PAR:EXT '{0}','{1}'".format(newName, param))
                #    iTrace = 1 + ['S11', 'S21', 'S12', 'S22'].index(param)
                #    self.writeVNA("DISP:WIND:TRAC{0}:FEED '{1}'".format(iTrace, newName))
                #    self.dMeasParam[param] = [newName]
    #        self.hw_write("DISP:WINDow1:TRACe:DELete")
    #        self.hw_write("CALCulate1:PARameter:DEFine 'MyMag', {}".format(self.measurement_type))
    #        self.hw_write("DISPlay:WINDow1:TRACe1:FEED 'MyMag'")
    #        self.hw_write("CALCulate1:PARameter:SELect 'MyMag'")
    #        self.hw_write("CALCulate1:FORMat MLOG")
    #        self.hw_write("CALCulate1:PARameter:DEFine 'MyPhase', {}".format(self.measurement_type))
    #        self.hw_write("DISPlay:WINDow1:TRACe2:FEED 'MyPhase'")
    #        self.hw_write("CALCulate1:PARameter:SELect 'MyPhase'")
    #        self.hw_write("CALCulate1:FORMat PHASe")
            #elif quant.name in ("Wait for new trace",):
            #    self.log(options)
            #elif quant.name not in ('Wait for new trace',):
                # run standard VISA case
            #    value = VISA_Driver.performSetValue(self, quant, value, sweepRate, options)
        return value


    def performGetValue(self, quant, options={}):
        """Perform the Get Value instrument operation"""
        self.log(options)
        self.log(self.isFirstCall(options))

        attr=getattr(self, quant.name, None)
        if attr is not None:
            return attr.receive()
        elif quant.name == "Output enabled":
            return bool(int(self.askVNA(":OUTP?")))
        elif quant.name in self.S_enabled_names:            
            key=quant.name[:3]#('S11 - Enabled', 'S21 - Enabled', 'S12 - Enabled', 'S22 - Enabled'):
            return self.S_enabled[key]
            #return self.getValue(quant.name)                  
                # update list of channels in use
                #self.getActiveMeasurements()
                # get selected parameter
                #param = quant.name[:3]
                #value = param in self.dMeasParam
        elif quant.name in self.measDict: #('S11', 'S21', 'S12', 'S22'):
            if self.isFirstCall(options):
                #resets cData on first call
                self.cData=None
            if quant.name not in self.cData:
                #resets cData if parameter not in data
                self.acquire_data()
            data=self.cData.get(quant.name, [])
            #if data==[]:
            #    return InstrumentQuantity.getTraceDict()
            #if quant.name in self.cData:
            self.log(InstrumentQuantity.getTraceDict.__doc__)
            return InstrumentQuantity.getTraceDict(data, t0=self.t0, dt=self.dt)
            #else:
                    # not enabled, return empty array
                #    value = InstrumentQuantity.getTraceDict([])
                #return self.cData[quant.name]
                    #if options.get("call_no", 0)==0:
                    #self.dMeasParam={}
                    # check if channel is on
                    #if quant.name not in self.dMeasParam:
                    # get active measurements again, in case they changed
                #    self.getActiveMeasurements()
                #if quant.name in self.dMeasParam:
                #    if self.getModel() in ('E5071C',):
                        # new trace handling, use trace numbers
                #        self.writeVNA("CALC:PAR%d:SEL" % self.dMeasParam[quant.name])
                #    else:
                        # old parameter handing, select parameter (use last in list)
                #        sName = self.dMeasParam[quant.name][-1]
                #        self.writeVNA("CALC:PAR:SEL '%s'" % sName)
                    # if not in continous mode, trig from computer
                #    bWaitTrace = self.getValue('Wait for new trace')
                #    bAverage = self.getValue('Average')
                    # wait for trace, either in averaging or normal mode
                #    if bWaitTrace:
                #        if bAverage:
                            # set channels 1-4 to set event when average complete (bit 1 start)
                #            self.writeVNA(':SENS:AVER:CLE;:STAT:OPER:AVER1:ENAB 30;:ABOR;:SENS:AVER:CLE;')
                #        else:
                #            self.writeVNA(':ABOR;:INIT:CONT OFF;:INIT:IMM;')
                #            self.writeVNA('*OPC')
                        # wait some time before first check
                #        self.thread().msleep(30)
                #        bDone = False
                #        while (not bDone) and (not self.isStopped()):
                            # check if done
                #            if bAverage:
                #                sAverage = self.askVNA('STAT:OPER:AVER1:COND?')
                #                bDone = int(sAverage)>0
                #            else:
                #                stb = int(self.askVNA('*ESR?'))
                #                bDone = (stb & 1) > 0
                #            if not bDone:
                #                self.thread().msleep(100)
                        # if stopped, don't get data
                #        if self.isStopped():
                #            self.writeVNA('*CLS;:INIT:CONT ON;')
                #            return []
                    # get data as float32, convert to numpy array
                #    if self.getModel() in ('E5071C',):
                #        # new trace handling, use trace numbers
                #        self.writeVNA(':FORM:DATA REAL32;:CALC:SEL:DATA:SDAT?')#, bCheckError=False)
                #    else:
                        # old parameter handing
               #         self.writeVNA(':FORM REAL,32;CALC:DATA? SDATA')#, bCheckError=False)
               #     sData = self.readVNA()#ignore_termination=True)
               #     self.log(sData)
               #     if bWaitTrace and not bAverage:
               #         self.writeVNA(':INIT:CONT ON;')
                    # strip header to find # of points
               #     i0 = sData.find('#')
               #     nDig = int(sData[i0+1])
               #     nByte = int(sData[i0+2:i0+2+nDig])
               #     nData = nByte/4
               #     nPts = nData/2
                    # get data to numpy array
               #     vData = np.frombuffer(sData[(i0+2+nDig):(i0+2+nDig+nByte)],
               #                           dtype='>f', count=nData)
                    # data is in I0,Q0,I1,Q1,I2,Q2,.. format, convert to complex
#                    mC = vData.reshape((nPts,2))
#                    vComplex = mC[:,0] + 1j*mC[:,1]
#                    # get start/stop frequencies
#                    startFreq = self.fStartFrequency #self.readValueFromOther('Start frequency')
#                    stopFreq = self.fStopFrereadValueFromOther('Stop frequency')
#                    sweepType = self.readValueFromOther('Sweep type')
#                    # if log scale, take log of start/stop frequencies
#                    if sweepType == 'Log':
#                        startFreq = np.log10(startFreq)
#                        stopFreq = np.log10(stopFreq)
#                    # create a trace dict
#                    value = InstrumentQuantity.getTraceDict(vComplex, t0=startFreq,
#                                                   dt=(stopFreq-startFreq)/(nPts-1))
#                else:
#                    # not enabled, return empty array
#                    value = InstrumentQuantity.getTraceDict([])
            #elif quant.name in ('Wait for new trace',):
                # do nothing, return local value
            #    value = quant.getValue()
            #else:
                # for all other cases, call VISA driver
            #    value = VISA_Driver.performGetValue(self, quant, options)
        return value
Beispiel #51
0
 def create_object(self):
     return CreateObject("TestComServerLib.TestComServer",
                         clsctx=comtypes.CLSCTX_LOCAL_SERVER)
Beispiel #52
0
    #sound = AudioSegment.from_mp3(file)
    #sound.export(wav_file, format="wav")

    file = "./" + file
    sound = AudioSegment.from_mp3(file)
    sound.export(wav_file, format="wav")

    #mixer.init()
    mixer.music.load(wav_file)
    mixer.music.play()

#windows system play and convert wav file
if (operatingSystem == 'win32'):
    from comtypes.client import CreateObject

    engine = CreateObject("SAPI.SpVoice")
    stream = CreateObject("SAPI.SpFileStream")

    from comtypes.gen import SpeechLib

    stream.Open(wav_file, SpeechLib.SSFMCreateForWrite)  # ERRORS NEAR HERE
    engine.AudioOutputStream = stream  # MAYBE HERE :(
    engine.speak(quote)
    stream.Close()

    import win32com.client as wincl
    speak = wincl.Dispatch("SAPI.SpVoice")
    speak.Speak(quote)

#print ("Playing: " + wav_file)
#This went to quickyl and slowed down the CPU
Beispiel #53
0
    keplerian_i.Orientation.AscNode.QueryInterface(
        STKObjects.IAgOrientationAscNodeRAAN
    ).Value = ascnode  # 升交点赤经:赤道平面春分点向右与升交点夹角

    # 定义卫星在轨道中的位置
    keplerian_i.Location.QueryInterface(
        STKObjects.IAgClassicalLocationMeanAnomaly
    ).Value = location  #平近点角:卫星从近地点开始按平均轨道角速度运动转过的角度

    propagator_i.InitialState.Representation.Assign(keplerian)
    # 启动卫星
    propagator_i.Propagate()
    return satellite


app = CreateObject("STK11.Application")
# app.Visible= True
# app.UserControl= True

root = app.Personality2
root.NewScenario("get_orbit")
sc = root.CurrentScenario
sc2 = sc.QueryInterface(STKObjects.IAgScenario)
sc2.StartTime = '10 Jan 2020 04:00:00.000'
sc2.StopTime = '20 Jan 2020 04:00:00.000'

df = pd.DataFrame()
for i in range(10):
    ranum = np.random.rand()
    meanmotion = 7 * ranum + 7
    eccentricity = ranum
#生成一百以内带退位减法 带进位加法

from comtypes.client import CreateObject,Constants
import random


app = CreateObject("Excel.Application")
excel_constants = Constants(app)

template_file = "g:/口算作业模板.xlsx"
out_dir = "g:\\"
out_name = out_dir+"口算"

max_number = 100
ratio_sub = 0.6 #减法题的比例
ratio_carry = 0.8 # 进退位比例
total_page = 40 # 总页数
seciton_per_page = 2 #每页的小节数
row_per_section = 10 #每页的行数
col_per_section = 3 #每页的列数
row_starts=[2, 16]

total_add_with_carry = 0 #带进位加法题目数
total_add_with_no_carry=0 #不带进位加法题目数
total_sub_decomposition = 0 #带退位减法题目数
total_sub_no_decomposition=0 #不带退位减法题目数

workbook = app.Workbooks.open(template_file)
# print(workbook.ActiveSheet.Cells(1,1).Value())

random.seed()
Beispiel #55
0
 def create_com_object():
     if not DLL_IS_LOADED:
         raise WindowsError("Could not locate Agilent DLLs")
     reader = CreateObject(
         'Agilent.MassSpectrometry.DataAnalysis.MassSpecDataReader')
     return reader
Beispiel #56
0
from comtypes.client import CreateObject
import os

project_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

#creat10 rows and save in excel

xl = CreateObject("Excel.Application")
xl.Visible = 1
wb = xl.Workbooks.Add()
for i in range(10):
    #диапазон ячеек     xl.Range["A1", "C1"].Value[()] =
    xl.Range["A%s" % (i + 1)].Value[()] = "group %s" % i
wb.SaveAs(os.path.join(project_dir, "groups.xlsx"))
xl.Quit()
Beispiel #57
0
@get('/alive')
def do_alive():
    return "OK"


@get('/TTS')
def do_TTS():
    uni_text = request.query.text
    print uni_text
    filename = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")+".wav"
    print "=>", filename
    stream.Open(filename, SpeechLib.SSFMCreateForWrite)
    engine.AudioOutputStream = stream
    engine.speak(uni_text)
    stream.Close()
    return "http://bc-annex.local/wav/"+filename


@route('/wav/<filename>')
def callback(filename):
    return static_file(filename, root='')


engine = CreateObject("SAPI.SpVoice")
stream = CreateObject("SAPI.SpFileStream")
engine.Voice=engine.GetVoices().Item(0)
engine.Rate = 2
os.chdir("C:\\Users\\nio\Desktop\\bc_TTS\\wav")
run(host='bc-annex.local', port=80)