def getEvents(self, start_calendar_date, end_calendar_date):
		events = []
		self.eventId_calendarId = {}
		self.date_to_events = {}
		
		s = utils.formatDateTime_get_iso(start_calendar_date) + 'Z'
		e = utils.formatDateTime_get_iso(end_calendar_date) + 'Z'
		print str(s) + " --- " + str(e)
		tmp_events=[]
		# Loop over all calendars
		for cal in self.calendars:
			# Check if calendar is enabled
			if self.is_selected(cal['summary']):
				eventsResult = self.service.events().list(calendarId=cal['id'], timeMin=s, timeMax=e, maxResults=100, singleEvents=True, orderBy='startTime').execute()
				tmp_events = eventsResult.get('items', [])
				
				# Save mapping
				for event in tmp_events:
					# Map event id to calendar id
					self.eventId_calendarId[event['id']] = cal['id']
					if not utils.formatDate(event, 'start') in self.date_to_events:
						self.date_to_events[utils.formatDate(event, 'start')] = []
					self.date_to_events[utils.formatDate(event, 'start')].append(event)
				
				events.extend(tmp_events)
		return events
Example #2
0
def addProposicao(sigla,status=None,desc=None,candidatura=None,proposicaoSQL=None,data=None,autor=None,tipo=None,originalid=None,cursor=None):    
    
    row = getProposicao(sigla,cursor=cursor)   
    desc=utils.applyCoding(desc,depara) 
    desc=desc.replace("'" ,'"' )
    autor=autor.replace("'" ,'"' )
    if autor is not None and len(autor)>490:
        autor=autor[:490]
    data=utils.formatDate(data,'%d/%m/%Y %H:%M:%S','%Y-%m-%d')
    if isinstance(candidatura, tuple):
        candidatura=int(candidatura[0]) 
    if candidatura is None:
        candidatura=0
    if row is None:
        cursor.execute("INSERT INTO `proposicao` (`status`,  `sigla`, `desc`,candidatura,autor,data,tipo,originalid) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",[status,sigla,desc,str(candidatura),autor,data,tipo,originalid])
        print "Inserido Proposicao "            
    else:
        query = "update proposicao set `desc` = '"+desc+"',`status` = '"+status +        "',`autor` = '"+autor+"',`data` = '"+data+"',`tipo` = '"+tipo+"',`candidatura` = '"+ \
        str(candidatura)+"',originalid='"+originalid+"' where sigla = '"+sigla+ "';"
        print "Atualizando Proposicao "+sigla
        print query
        cursor.execute(query )
        proposicaoSQL=proposicaoSQL+query
        
    #return getProposicao(sigla)
    return proposicaoSQL
def RedditAppendData(subResults, start_date):
    lastdate = start_date
    for post in subResults:
        for company, ticker in companies_ticker.items():
            if utils.findWholeWord(company)(post.title):
                queryDate = utils.formatDateUtf(post.created_utc)
                DateFormated = utils.formatDate(queryDate)
                if int(post.created_utc) < lastdate:
                    lastdate = post.created_utc
                temp = stock.getHistoricalPrices(ticker, DateFormated,
                                                 DateFormated)
                if temp != 0:
                    stockdata = temp[0]
                    with open('tempreddit.json', 'a') as outfile:
                        jsonData = DataReddit(post.id, post.ups, post.downs,
                                              post.title, ticker, queryDate,
                                              stockdata["Open"],
                                              stockdata["Close"],
                                              stockdata["High"],
                                              stockdata["Low"])
                        json.dump(jsonData,
                                  outfile,
                                  default=utils.jdefault,
                                  sort_keys=True,
                                  indent=4,
                                  ensure_ascii=False)
                        print(
                            json.dumps(jsonData,
                                       default=utils.jdefault,
                                       sort_keys=True,
                                       indent=4,
                                       ensure_ascii=False))
    return lastdate
Example #4
0
def generate_psd_rows(start_datetime, end_datetime):
    st = formatDate(start_datetime, SENSOR_DATE_TIME_FORMAT)
    et = formatDate(end_datetime, SENSOR_DATE_TIME_FORMAT)
    rows = get_sensor_data_in_time_range(st, et)
    daqwise_data = {}
    for daq_id, val in rows:
        if daq_id not in daqwise_data:
            daqwise_data[daq_id] = {'ts': []}
        daqwise_data[daq_id]['ts'].append(val)

    psd_rows = []
    for daq_id in daqwise_data:
        freqs, power = power_spectrum(daqwise_data[daq_id]['ts'])
        average_power = integrate.simps(power)
        freqs = ",".join(map(lambda x: str(x), freqs))
        spectrum_val = ",".join(map(lambda x: str(x), power))
        psd_rows.append((daq_id, st, average_power, freqs, spectrum_val))
    return psd_rows
Example #5
0
def addPolitico(nome,nascimento=None,desc_pt=None,partido=None,id_original=None,cursor=None):    
    row = getPolitico(nome,id_original,cursor=cursor)    
    nascimento = utils.formatDate(nascimento)
    if row is None:
        cursor.execute("insert into politico (nome,nascimento,desc_pt,partido,id_original) values (%s,%s,%s,%s,%s)",[nome,nascimento,desc_pt,partido,id_original])
        print "Inserido politico "           
    else:
        cursor.execute("update politico set id_original = "+id_original+",desc_pt='"+desc_pt+"',nome='"+nome+"' , nascimento='"+nascimento+"' where id = "+str(row[0])+ ";")
        print "Atualizado politico"
        #nascimento=STR_TO_DATE('"+nascimento+"', '%d/%m/%Y')
    return getPolitico(nome,id_original,cursor=cursor) 
Example #6
0
def formatRecord(recordIn, questions):
	''' scores a dated saved enneagram record '''
	''' formats a <tr> to display counters '''
	counters = {}
	for q in questions:
		if q["K"] in recordIn.keys():
			ch = int(recordIn[q["K"]]) - 1			# this is the statement chosen
			ev = q["S"][ch]["E"]					# enneagram value of that statement
			if ev in counters.keys():			# questions[0]["S"][0]["E"]
				counters[ev] += 1
			else:
				counters[ev] = 1
	fString = '<tr style="font-size: 1.2em"><td class="textL">' + utils.formatDate(u["date"]) + '</td>'
	for c in sorted(counters.items(), key=lambda ect: ect[1]):
		fString += '<td class="textL"><b>' + c[0] + '</b>: ' + utils.formatNumber(c[1], 3) + '</td>'
	return fString + '</tr>'
def QueryProfile(api, QUERY_PROFILE, limit):
    """Query a profile with provided profile id, returning tweets to a limit of pages"""
    try:
        user = api.user_timeline(QUERY_PROFILE)
        for tweet in limit_handler(
                tweepy.Cursor(api.user_timeline,
                              id=QUERY_PROFILE).pages(limit)):
            for company, ticker in companies_ticker.items():
                if utils.findWholeWord(company)(tweet[0].text):
                    queryDate = str(tweet[0].created_at)
                    DateFormated = utils.formatDate(queryDate)
                    temp = stock.getHistoricalPrices(ticker, DateFormated,
                                                     DateFormated)
                    if temp != 0:
                        stockdata = temp[0]
                        with open('temptweet.json', 'a') as outfile:
                            jsonData = DataTwitter(
                                tweet[0].id_str, tweet[0].favorite_count,
                                tweet[0].retweet_count, tweet[0].text, ticker,
                                queryDate, stockdata["Open"],
                                stockdata["Close"], stockdata["High"],
                                stockdata["Low"])
                            json.dump(jsonData,
                                      outfile,
                                      default=utils.jdefault,
                                      sort_keys=True,
                                      indent=4,
                                      ensure_ascii=False)
                            print(
                                json.dumps(jsonData,
                                           default=utils.jdefault,
                                           sort_keys=True,
                                           indent=4,
                                           ensure_ascii=False))
        utils.JSONify('temptweet.json', 'tweets.json')
    except KeyboardInterrupt:
        print('\nProfile Query Interupted')
        utils.JSONify('temptweet.json', 'tweets.json')
Example #8
0
def runVotacaoProposicao(cursor=None):         
    csv_reader = utils.openCSV('data/VotacoesProposicoes.csv')
    #"update proposicao set favor=null, contra=null , abstencao=null where id>0"
    print "runVotacaoProposicao:"
    for line in csv_reader:
        if line[1]:      
             
            codProposicao    = line[0]
            nomeProposicao  = line[1]  
            dataVotacao    = line[2]
            dataVotacao=utils.formatDate(dataVotacao,'%d/%m/%Y','%Y-%m-%d')
            
            nomeProposicao= proposicao.propostaVinculada(nomeProposicao)
            print "Proposicao:"+nomeProposicao
            id = proposicao.getProposicao(sigla=nomeProposicao,cursor=cursor)
            if not id:
                id = proposicao.getProposicaoByOriginal(id=codProposicao,cursor=cursor)
            
            if not id:
                continue
            id=id[0]
            print "Proposicao Encontrada:"+str(id)
            cursor.execute("UPDATE proposicao SET datavotacao=%s where id = %s",[dataVotacao,id])
Example #9
0
def runProposicaoAcao(cursor=None,anoFilter=None,semanaFilter=None):         
    csv_reader = utils.openCSV('data/TramitacaoOrgaoProposicao.csv')
    proposicaoSQL=""
    siglaAtual=None
    for line in csv_reader:
        if line[1]:      
            
            ProposicaoAcao_tipo    = line[0]
            ProposicaoAcao_numero   = line[1]
            ProposicaoAcao_ano    = line[2]
            ProposicaoAcao_situacao    = line[3]
            ProposicaoAcao_ementa    = line[4]
            ProposicaoAcao_idProposicao = line[5]   
            ProposicaoAcao_data    = line[6]
            ProposicaoAcao_codOrgao = line[7]   
            ProposicaoAcao_orgao    = line[8]
            ProposicaoAcao_descricao = line[9]   
            
            ProposicaoAcao_Sigla= ProposicaoAcao_tipo + " " + ProposicaoAcao_numero + "/"+ ProposicaoAcao_ano 
            ProposicaoAcao_data=utils.formatDate(ProposicaoAcao_data)
            
            
            id = getProposicao(sigla=ProposicaoAcao_Sigla,cursor=cursor)
            if not id:
                id = getProposicaoByOriginal(id=ProposicaoAcao_idProposicao,cursor=cursor)
            
            if not id:
                print "Proposicao Nao Encontrada:"+ProposicaoAcao_Sigla
                continue
            
            #ProposicaoAcao_situacao
            
            orgaoId = orgao.addOrgao(sigla=ProposicaoAcao_orgao,original_cf=ProposicaoAcao_codOrgao,desc=ProposicaoAcao_orgao,cursor=cursor) 
            
            proposicaoSQL=addProposicaoAcao(nome=ProposicaoAcao_ementa,data=ProposicaoAcao_data,siglaProposicao=ProposicaoAcao_Sigla,
                                            status=ProposicaoAcao_situacao,orgao=orgaoId,cursor=cursor)
Example #10
0
            else:
                gDict[id] = [((g["T"], g["N"]))]
        if authA[0] == '1':
            for u in sorted(gDict):
                print(
                    '''<br><a class="textL" style="color: blue; font-size: 1.2em;" href="javascript:'" '''
                )
                print(''' onClick=javascript:toggleDiv("div{}")>{} ({})</a>'''.
                      format(u, u, len(gDict[u])))
                print('''<div id="div{}" style="display:none;";>'''.format(u))
                print(
                    '''<table border=0><tr><th>Date</th><th>Puzzle Number</th>'''
                )
                for g in gDict[u]:
                    print('''<tr><td>{}</td><td class="textR">{}</td></tr>'''.
                          format(utils.formatDate(g[0][0:8]), g[1]))
                print('''</table>''')
                print('''</div>''')
        else:
            print(
                '''<table border=0><tr><th>Date</th><th>Puzzle Number</th>''')
            for g in gDict[gid]:
                print(
                    '''<tr><td>{}</td><td class="textR">{}</td></tr>'''.format(
                        utils.formatDate(g[0][0:8]), g[1]))
            print('''</table>''')
    else:
        print('''
Welcome to ToMarGames Friends and Family!<br><br>It looks like you've landed on a page you don't have permission to access.
				''')
print('</body></html>')
Example #11
0
def main():
    import sys, os
    from pprint import pprint

    # Early check for forked process.
    if appinfo.args.forkExecProc:
        # Only import utils now for this case.
        # Otherwise, I want "--pyshell" to be without utils loaded.
        import utils
        utils.ExecingProcess.checkExec()

    # Early check for "--pyshell".
    # This is a simple debug shell where we don't load anything.
    if appinfo.args.pyshell:
        better_exchook.simple_debug_shell({}, {})
        raise SystemExit

    # Early check for "--pyexec".
    # This is a simple Python execution where we don't load anything.
    if appinfo.args.pyexec:
        sourcecode = appinfo.args.pyexec[0]
        exec(compile(sourcecode, "<pyexec>", "exec"))
        raise SystemExit

    import utils
    import time

    print "MusicPlayer", appinfo.version, "from", appinfo.buildTime, "git-ref", appinfo.gitRef[:
                                                                                               10], "on", appinfo.platform, "(%s)" % sys.platform
    print "startup on", utils.formatDate(time.time())

    utils.setCurThreadName("Python main")

    try:
        # Hack: Make the `__main__` module also accessible as `main`.
        mainmod = sys.modules["__main__"]
        sys.modules.setdefault("main", mainmod)
        del mainmod
    except Exception:
        sys.excepthook(*sys.exc_info())
        # doesn't matter, continue

    # Import PyObjC here. This is because the first import of PyObjC *must* be
    # in the main thread. Otherwise, the NSAutoreleasePool created automatically
    # by PyObjC on the first import would be released at exit by the main thread
    # which would crash (because it was created in a different thread).
    # http://pyobjc.sourceforge.net/documentation/pyobjc-core/intro.html
    objc, AppKit = None, None
    try:
        import objc
    except Exception:
        if sys.platform == "darwin":
            print "Error while importing objc"
            sys.excepthook(*sys.exc_info())
        # Otherwise it doesn't matter.
    try:
        # Seems that the `objc` module is not enough. Without `AppKit`,
        # I still get a lot of
        #   __NSAutoreleaseNoPool(): ... autoreleased with no pool in place - just leaking
        # errors.
        if objc:
            import AppKit
    except Exception:
        # Print error in any case, also ImportError, because we would expect that this works.
        print "Error while importing AppKit"
        sys.excepthook(*sys.exc_info())

    # Import core module here. This is mostly as an early error check.
    try:
        import musicplayer
    except Exception:
        print "Error while importing core module! This is fatal."
        sys.excepthook(*sys.exc_info())
        print "Environment:"
        pprint(os.environ)
        raise

    # Import gui module here. Again, mostly as an early error check.
    # If there is no gui, the module should still load and provide
    # dummy functions where appropriate.
    import gui

    # Default quit handling.
    # Note that this is executed after `threading._shutdown`, i.e. after
    # all non-daemon threads have finished.
    import atexit
    atexit.register(gui.handleApplicationQuit)

    # Import some core modules. They propagate themselves to other
    # subsystems, like GUI.
    # XXX: Maybe move all this to `State` module?
    import State
    import Preferences
    import Search
    import SongEdit

    # This will overtake the main loop and raise SystemExit at its end,
    # or never return.
    # It also just might do nothing.
    gui.main()
    # If we continue here, we can setup our own main loop.

    # We have no GUI. Continue with some simple console control handling.
    import stdinconsole

    handleApplicationInit()

    # Note on quit behavior: Simply iterating state.updates
    # and waiting for its end does not work because we would
    # not interrupt on signals, e.g. KeyboardInterrupt.
    # It is also not possible (in general) to catch
    # signals from other threads, thus we have to do it here.
    # time.sleep() is a good way to wait for signals.
    # However, we use stdinconsole.readNextInput() because
    # there is simply no way to have os.read() in another thread
    # and to be able to interrupt that from here (the main thread).
    # In other threads: thread.interrupt_main() does not work
    # for time.sleep() (or at least it will not interrupt the sleep).
    # os.kill(0, signal.SIGINT) works, though.
    # To interrupt/stop all threads:
    # signal.set_wakeup_fd(sys.stdin.fileno()) also does not really
    # work to interrupt the stdin thread, probably because stdin is
    # not non-blocking.
    # Every thread must only wait on a OnRequestQueue which registers
    # itself in its thread. We cancelAll() here already the main queue
    # (state.updates) and in Module.stop(), we also cancel any custom
    # queue.

    while True:
        try:
            stdinconsole.readNextInput()  # wait for KeyboardInterrupt
        except BaseException, e:
            State.state.updates.put((e, (), {}))
            State.state.updates.cancelAll()
            break
Example #12
0
def main():
	import sys, os
	from pprint import pprint

	# Early check for forked process.
	if appinfo.args.forkExecProc:
		# Only import utils now for this case.
		# Otherwise, I want "--pyshell" to be without utils loaded.
		import utils
		utils.ExecingProcess.checkExec()

	# Early check for "--pyshell".
	# This is a simple debug shell where we don't load anything.
	if appinfo.args.pyshell:
		better_exchook.simple_debug_shell({}, {})
		raise SystemExit

	# Early check for "--pyexec".
	# This is a simple Python execution where we don't load anything.
	if appinfo.args.pyexec:
		sourcecode = appinfo.args.pyexec[0]
		exec(compile(sourcecode, "<pyexec>", "exec"))
		raise SystemExit

	import utils
	import time

	print "MusicPlayer", appinfo.version, "from", appinfo.buildTime, "git-ref", appinfo.gitRef[:10], "on", appinfo.platform, "(%s)" % sys.platform
	print "startup on", utils.formatDate(time.time())

	utils.setCurThreadName("Python main")

	try:
		# Hack: Make the `__main__` module also accessible as `main`.
		mainmod = sys.modules["__main__"]
		sys.modules.setdefault("main", mainmod)
		del mainmod
	except Exception:
		sys.excepthook(*sys.exc_info())
		# doesn't matter, continue

	# Import PyObjC here. This is because the first import of PyObjC *must* be
	# in the main thread. Otherwise, the NSAutoreleasePool created automatically
	# by PyObjC on the first import would be released at exit by the main thread
	# which would crash (because it was created in a different thread).
	# http://pyobjc.sourceforge.net/documentation/pyobjc-core/intro.html
	objc, AppKit = None, None
	try:
		import objc
	except Exception:
		if sys.platform == "darwin":
			print "Error while importing objc"
			sys.excepthook(*sys.exc_info())
		# Otherwise it doesn't matter.
	try:
		# Seems that the `objc` module is not enough. Without `AppKit`,
		# I still get a lot of
		#   __NSAutoreleaseNoPool(): ... autoreleased with no pool in place - just leaking
		# errors.
		if objc:
			import AppKit
	except Exception:
		# Print error in any case, also ImportError, because we would expect that this works.
		print "Error while importing AppKit"
		sys.excepthook(*sys.exc_info())

	# Import core module here. This is mostly as an early error check.
	try:
		import musicplayer
	except Exception:
		print "Error while importing core module! This is fatal."
		sys.excepthook(*sys.exc_info())
		print "Environment:"
		pprint(os.environ)
		raise

	# Import gui module here. Again, mostly as an early error check.
	# If there is no gui, the module should still load and provide
	# dummy functions where appropriate.
	import gui

	# Default quit handling.
	# Note that this is executed after `threading._shutdown`, i.e. after
	# all non-daemon threads have finished.
	import atexit
	atexit.register(gui.handleApplicationQuit)

	# Import some core modules. They propagate themselves to other
	# subsystems, like GUI.
	# XXX: Maybe move all this to `State` module?
	import State
	import Preferences
	import Search
	import SongEdit

	# This will overtake the main loop and raise SystemExit at its end,
	# or never return.
	# It also just might do nothing.
	gui.main()
	# If we continue here, we can setup our own main loop.

	# We have no GUI. Continue with some simple console control handling.
	import stdinconsole

	handleApplicationInit()

	# Note on quit behavior: Simply iterating state.updates
	# and waiting for its end does not work because we would
	# not interrupt on signals, e.g. KeyboardInterrupt.
	# It is also not possible (in general) to catch
	# signals from other threads, thus we have to do it here.
	# time.sleep() is a good way to wait for signals.
	# However, we use stdinconsole.readNextInput() because
	# there is simply no way to have os.read() in another thread
	# and to be able to interrupt that from here (the main thread).
	# In other threads: thread.interrupt_main() does not work
	# for time.sleep() (or at least it will not interrupt the sleep).
	# os.kill(0, signal.SIGINT) works, though.
	# To interrupt/stop all threads:
	# signal.set_wakeup_fd(sys.stdin.fileno()) also does not really
	# work to interrupt the stdin thread, probably because stdin is
	# not non-blocking.
	# Every thread must only wait on a OnRequestQueue which registers
	# itself in its thread. We cancelAll() here already the main queue
	# (state.updates) and in Module.stop(), we also cancel any custom
	# queue.

	while True:
		try: stdinconsole.readNextInput() # wait for KeyboardInterrupt
		except BaseException, e:
			State.state.updates.put((e, (), {}))
			State.state.updates.cancelAll()
			break
Example #13
0
def calculaDigitoVerificador(dados):
    #aqui monto a chave de 43 digitos.
    #próximo passo, calcular o digito verificador.
    # O dígito verificador da chave de acesso da NF-e é baseado em um cálculo do módulo 11. O
    # módulo 11 de um número é calculado multiplicando-se cada algarismo pela sequência de
    # multiplicadores 2,3,4,5,6,7,8,9,2,3, ..., posicionados da direita para a esquerda.

    #A somatória dos resultados das ponderações dos algarismos é dividida por 11 e o DV (dígito
    #verificador) será a diferença entre o divisor (11) e o resto da divisão:
    #DV = 11 - (resto da divisão)
    codigoUf = dados.get("codigoUf")
    emissao = dados.get("dataEmissao")
    emissaoTemp = emissao
    cnpj = dados.get("cnpj")
    modelo = dados.get("modelo")
    serie = dados.get("serie")
    numeroNfInicio = dados.get("numeroNfInicio")
    numeroNfFinal = dados.get("numeroNfFinal")
    tipoEmissao = dados.get("tipoEmissao")
    codigoNumerico = dados.get("codigoNumerico")

    qtDias = utils.quantidadeDias(emissao, datetime.today())
    chaveAcessoArray = []
    for numeroNf in range(int(numeroNfInicio), int(numeroNfFinal) + 1):

        emissao = emissaoTemp
        for dia in range(0, qtDias):
            dataEmissao = utils.addDay(emissao)
            emissao = utils.formatDate(dataEmissao)

            chave43 = codigoUf + emissao[0:5].replace(
                '/', '') + cnpj + modelo + serie + utils.prencheNumeroNf(
                    str(numeroNf)) + tipoEmissao + codigoNumerico

            chaveAcesso = chave43

            indice = 2
            chave43 = chave43[::-1]
            soma = 0
            for i in range(len(chave43)):
                valorChaveAcessoSeparado = chave43[i:i + 1]
                mult = int(valorChaveAcessoSeparado) * indice
                soma += mult

                indice += 1
                if (indice > 9):
                    indice = 2

            #próximo passo: Dividindo a somatória das ponderações por 11 teremos
            resto = soma % 11
            #Quando o resto da divisão for 0 (zero) ou 1 (um), o DV deverá ser igual a 0 (zero).
            dv = 11 - resto

            if ((resto <= 0 or resto == 1) or dv >= 10):
                dv = 0

            chaveAcesso = chaveAcesso + str(dv)
            chaveAcessoArray.append(chaveAcesso)
            # print(chaveAcesso)

    return chaveAcessoArray
Example #14
0
					<table><tr valign="top"><td style="background-color: #dddd88; "><table>
					<tr><td colspan="2" class="textL" style="color: #darkblue; background-color: #dddd88; font-size: 1.5em;"><a href="https://www.enneagraminstitute.com/how-the-enneagram-system-works/">Enneagram Types</a></td></tr>
					''')
                    for t in sorted(eData.types):
                        print('''
						<tr><td class="textC" style="color: #dddd88; background-color: darkblue; font-size: 1.3em;">%s</td>
							<td class="textL"><a href="%s">The %s</a></td></tr>
						''' % (t, "https://www.enneagraminstitute.com/type-" + t,
                        eData.types[t]))
                    print('''
					</table></td>
<td><h4 style="margin: 0px; color: beige; background-color: purple; text-align: left">Past results for %s</h4>
					<table>
					''' % name)
                counters = eData.scoreRecord(u)
                fString = '<tr style="font-size: 1.2em"><td class="textL">' + utils.formatDate(
                    u["date"]) + '</td>'
                for c in sorted(counters.items(),
                                key=lambda ect: ect[1],
                                reverse=True):
                    fString += '<td class="textL"><b>' + c[
                        0] + '</b>: ' + utils.formatNumber(c[1], 3) + '</td>'
                fString += '</tr>'
                print(fString)
    else:
        saverecord = {}
    print('</table></td></tr></table>')
    print('''
	<script>
	function validateForm()
	{
	''')
Example #15
0
 def formatDate(self, datestr):
     dateobj = self.parseDate(datestr)
     return utils.formatDate(dateobj)
Example #16
0
	print(authS[1])
	if authS[0] == '1':
		with open("games.json") as gData:
			games = json.load(gData)
		gDict = {}
		for g in games:
			id = g["I"]
			if (id in gDict):
				gDict[id].append((g["T"], g["M"]))
			else:
				gDict[id] = [((g["T"], g["M"]))]
		if authA[0] == '1':
			for u in sorted(gDict):
				print('''<br><a class="textL" style="color: blue; font-size: 1.2em;" href="javascript:'" ''')
				print(''' onClick=javascript:toggleDiv("div{}")>{} ({})</a>'''.format(u, u, len(gDict[u])))
				print('''<div id="div{}" style="display:none;";>'''.format(u))
				print('''<table border=0><tr><th>Date</th><th>Moves</th>''')
				for g in gDict[u]:
					print('''<tr><td>{}</td><td class="textR">{}</td></tr>'''.format(utils.formatDate(g[0][0:8]), g[1]))
				print('''</table>''')
				print('''</div>''')
		else:
			print('''<table border=0><tr><th>Date</th><th>Moves</th>''')
			for g in gDict[gid]:
				print('''<tr><td>{}</td><td class="textR">{}</td></tr>'''.format(utils.formatDate(g[0][0:8]), g[1]))
			print('''</table>''')
	else:
		print('''
Welcome to ToMarGames Friends and Family!<br><br>It looks like you've landed on a page you don't have permission to access.
				''')
print('</body></html>')
Example #17
0
	import faulthandler
	faulthandler.enable(all_threads=True)
except ImportError:
	print "note: faulthandler module not available"

# Do this early to do some option parsing and maybe special handling.
import appinfo

# This might do some init which might be important to be done in the main thread.
import utils

utils.ExecingProcess.checkExec()

import sys, time
print "MusicPlayer", appinfo.version, "from", appinfo.buildTime, "on", appinfo.platform, "(%s)" % sys.platform
print "startup on", utils.formatDate(time.time())

from State import state, modules

if __name__ == '__main__':	

	import stdinconsole
	import gui

	try:
		# This will overtake the main loop and raise SystemExit at its end.
		gui.main()
	except SystemExit:
		raise
	
	for m in modules: m.start()
Example #18
0
def main():

	import utils
	utils.ExecingProcess.checkExec()


	import sys, time
	print "MusicPlayer", appinfo.version, "from", appinfo.buildTime, "git-ref", appinfo.gitRef[:10], "on", appinfo.platform, "(%s)" % sys.platform
	print "startup on", utils.formatDate(time.time())

	utils.setCurThreadName("Python main")

	try:
		# Hack: Make the `__main__` module also accessible as `main`.
		mainmod = sys.modules["__main__"]
		sys.modules.setdefault("main", mainmod)
		del mainmod
	except Exception:
		sys.excepthook(*sys.exc_info())
		# doesn't matter, continue

	# Import PyObjC here. This is because the first import of PyObjC *must* be
	# in the main thread. Otherwise, the NSAutoreleasePool created automatically
	# by PyObjC on the first import would be released at exit by the main thread
	# which would crash (because it was created in a different thread).
	# http://pyobjc.sourceforge.net/documentation/pyobjc-core/intro.html
	objc, AppKit = None, None
	try:
		import objc
	except Exception:
		if sys.platform == "darwin":
			print "Error while importing objc"
			sys.excepthook(*sys.exc_info())
		# Otherwise it doesn't matter.
	try:
		# Seems that the `objc` module is not enough. Without `AppKit`,
		# I still get a lot of
		#   __NSAutoreleaseNoPool(): ... autoreleased with no pool in place - just leaking
		# errors.
		if objc:
			import AppKit
	except Exception:
		# Print error in any case, also ImportError, because we would expect that this works.
		print "Error while importing AppKit"
		sys.excepthook(*sys.exc_info())


	from State import state, modules
	import stdinconsole
	import gui

	try:
		# This will overtake the main loop and raise SystemExit at its end.
		gui.main()
	except SystemExit:
		raise
	
	for m in modules: m.start()

	successStartup = True

	# Note on quit behavior: Simply iterating state.updates
	# and waiting for its end does not work because we would
	# not interrupt on signals, e.g. KeyboardInterrupt.
	# It is also not possible (in general) to catch
	# signals from other threads, thus we have to do it here.
	# time.sleep() is a good way to wait for signals.
	# However, we use stdinconsole.readNextInput() because
	# there is simply no way to have os.read() in another thread
	# and to be able to interrupt that from here (the main thread).
	# In other threads: thread.interrupt_main() does not work
	# for time.sleep() (or at least it will not interrupt the sleep).
	# os.kill(0, signal.SIGINT) works, though.
	# To interrupt/stop all threads:
	# signal.set_wakeup_fd(sys.stdin.fileno()) also does not really
	# work to interrupt the stdin thread, probably because stdin is
	# not non-blocking.
	# Every thread must only wait on a OnRequestQueue which registers
	# itself in its thread. We cancelAll() here already the main queue
	# (state.updates) and in Module.stop(), we also cancel any custom
	# queue.

	while True:
		try: stdinconsole.readNextInput() # wait for KeyboardInterrupt
		except BaseException, e:
			state.updates.put((e, (), {}))
			state.updates.cancelAll()
			break