Example #1
0
def game(dictDeck):
    while 1:
        ts = get_terminal_size()
        ossys("cls" if system() == "Windows" else "clear")
        for q, a in dictDeck.items():
            askQuestion(q, ts)
            tellAnswer(a, ts)
Example #2
0
def instalar_dependencias():
    """Tenta instalar a biblioteca matplotlib no sistema atual.

	Raises:
		ImportError: Se houver falha durante ou após instalar o matplotlib.
	"""

    # Tente importar matplotlib, se falhar, tente instalar
    try:
        from matplotlib import pyplot

    except ImportError:

        print("--> Instalando matplotlib, aguarde...")
        modulo = "matplotlib"
        codigo_instalacao = 0

        # Se for Windows, dê o comando, instale e limpe a tela
        if (platsys().upper() == "WINDOWS"):
            print("--> SO: WINDOWS")
            codigo_instalacao = ossys("pip install --user --quiet %s" % modulo)

        # Senão, é MAC ou Linux
        else:
            print("--> SO: LINUX")
            ossys("sudo apt install python3-tk 2>&1 >/dev/null")
            codigo_instalacao = ossys("pip3 install --user --quiet %s" %
                                      modulo)

        if codigo_instalacao != 0:
            raise ModuleNotFoundError(
                "Não foi possível instalar o módulo '%s'" % modulo)
Example #3
0
def tellAnswer(a, ts):
    ts = console()
    avar = "Answer:"
    print(tc.BLUE + tc.BOLD + tc.UNDERLINE + "{}".format(avar.center(ts)) +
          tc.ENDC)
    if '<n>' in a:
        tempList = [i for i in a.split()]
        #if ['<n>' in i for i in a] == [True]:
        #tempList = [ x for i in a for x in i.split() ]
        for i in tempList:
            if i == '<n>':
                continue
            else:
                print(tc.BLUE + "\t\t\t\t- {}".format(i) + tc.ENDC)

    else:
        print(tc.BLUE + "{}".format(a.center(ts)) + tc.ENDC)
    print('\n')
    variable = input(tc.RED + tc.ITALIC + 'Press Enter to get next question.\nPress'\
        ' q + Enter to exit:\n' + tc.ENDC)
    if variable in ('q', 'Q'):
        sys.exit()
    else:
        pass
    ossys("cls" if system() == "Windows" else "clear")
    return
Example #4
0
def main():

    VERSION = "1.1.0";

    config = GetConfig();

    mpdc = MPDClient();
    mpdc.timeout = int(config["General"]["MPDtimeout"]);
    mpdc.idletimeout = int(config["General"]["MPDtimeout_idle"]);
    try:
        mpdc.connect(config["General"]["MPDip"], port=int(config["General"]["MPDport"]));
    except ConnectionRefusedError:
        print(f"{TermColors.ERROR}ERROR!!! Either mpd isn't running or you have a mistake in the config. Fix ASAP! Exiting!{TermColors.END}");
        exit(-1);

    RPC = Presence(710956455867580427);
    RPC.connect();

    if (psys() == "Windows"):
        ossys("cls");
    else:
        ossys("clear");

    print(f"{TermColors.WORKS}MPDDRP v.{VERSION} - https://github.com/AKurushimi/mpddrp{TermColors.END}");

    try:
        while True:

            statusout = mpdc.status();
            csout = mpdc.currentsong();

            if (statusout["state"] != "stop"):
                title = csout["title"];
                artist = csout["artist"];
                album = csout["album"];
                timevar = statusout["time"].split(":");
                timenow = str(timedelta(seconds=int(timevar[0])));
                timeall = str(timedelta(seconds=int(timevar[1])));

            if (statusout["state"] == "pause"):
                RPC.update(details=title + " | " + album, state="Paused | " + artist, large_image="mpdlogo", small_image="pause", small_text="Paused");
            elif (statusout["state"] == "stop"):
                RPC.update(details="Stopped | MPD", state="   ", large_image="mpdlogo", small_image="stop", small_text="Stopped");
            elif (statusout["state"] == "play"):
                RPC.update(details=title + " | " + album, state=timenow + "/" + timeall + " | " + artist, large_image="mpdlogo", small_image="play", small_text="Playing");
                sleep(1);

    except (RuntimeError):
        pass;
    except (KeyboardInterrupt, SystemExit):
        RPC.clear();
        RPC.close();
        exit(0);
Example #5
0
def GetConfig():

    platform = psys()
    username = getuser()

    if (platform == "Windows"):
        config_dir = f"C:\\Users\\{username}\\AppData\\Roaming\\mpddrp\\"
    else:
        config_dir = f"/home/{username}/.config/mpddrp/"

    default_config = {
        "General": {
            "MPDip": "localhost",
            "MPDport": 6600,
            "MPDtimeout": 10,
            "MPDtimeout_idle": 0
        }
    }

    if (path.exists(config_dir + "config.json")):
        configfile = open(config_dir + "config.json", "r")
        config = loads(configfile.read())
        configfile.close()

        for default_setting in default_config["General"]:
            for setting in config["General"]:
                if (config["General"][setting] == ""):
                    print(
                        f"{TermColors.ERROR}ERROR!!! {setting} doesn't have a value assigned! Fix ASAP! Exiting!{TermColors.END}"
                    )
                    exit(-1)
                try:
                    if (config["General"][default_setting]):
                        continue
                except KeyError:
                    print(
                        f"{TermColors.ERROR}ERROR!!! Please add {default_setting} in your config file! Fix ASAP! Exiting!{TermColors.END}"
                    )
                    exit(-1)
    else:
        ossys(f"mkdir -p {config_dir}")
        configfile = open(config_dir + "config.json", "w")
        configfile.write(dumps(default_config, indent=4, sort_keys=True))
        configfile.close()
        config = default_config

    return config
Example #6
0
def instalar_dependencias():
    """Tenta instalar as ferramentas no sistema atual.

	Args:
		nomes: Nomes das bibliotecas a serem instaladas

	Raises:
		ImportError: Se houver falha durante ou após instalar
	"""

    # Tente importar cada ferramenta, se falhar, tente instalar
    try:

        import cv2

    except ImportError:

        print("Instalando dependências, aguarde...")

        # ossys("sudo apt-get install python3-tk")
        # ossys("sudo apt-get install python3-opencv")

        for lib in ["opencv-python"]:

            print(f">>> Tentando instalar '{lib}'")

        # Se for Windows
        if (platsys().upper() == "WINDOWS"):
            ossys(f"pip install --user {lib}")

        # Senão, é MAC ou Linux
        else:
            ossys(f"pip3 install --user {lib}")

        # Se for Windows
        if (platsys().upper() == "WINDOWS"):
            ossys("cls")

        # Senão, é MAC ou Linux
        else:
            ossys("clear")

            print("--> Dependências instaladas com êxito!")

            # Se após tentar instalar, o erro ainda persistir, avise e saia
    finally:

        try:
            import cv2

        except:
            raise ImportError(
                "Falha ao instalar dependências necessárias. Bye.")
Example #7
0
def save_reference_data(casefile_name, stack_list):
    ref_stack_list = []
    for stack in stack_list:
        rstack = {'layers' : []}
        for lay in stack.layers:
            rlay = {}
            rlay['R12']  = lay.R12
            rlay['T12']  = lay.T12
            rlay['R21']  = lay.R21
            rlay['T21']  = lay.T21
            rlay['k_z']  = lay.k_z
            if isinstance(rlay, Simmo):
                rlay['sol1'] = lay.sol1
            rstack['layers'].append(rlay)
        rstack['R_net'] = stack.R_net
        rstack['T_net'] = stack.T_net
        ref_stack_list.append(rstack)
    np.savez_compressed("ref/%s.npz" % casefile_name, 
        stack_list = ref_stack_list)

    cp_cmd = 'cp *.txt ref/%s/' % casefile_name
    ossys(cp_cmd)

    assert False, "Reference results saved successfully, \
linesstrength = 3
font = 18
ax1 = fig.add_subplot(1,1,1)
ax1.plot(sub_ns,eta, 'k-o', linewidth=linesstrength)
ax1.set_xlabel('Substrate refractive index',fontsize=font)
ax1.set_ylabel(r'$\eta$ (%)',fontsize=font)
plt.savefig('eta_substrates')

# Animate spectra as a function of substrates.
from os import system as ossys
delay = 30 # delay between images in gif in hundredths of a second
names = 'Total_Spectra_stack'
gif_cmd = 'convert -delay %(d)i +dither -layers Optimize -colors 16 \
%(n)s*.pdf %(n)s.gif'% {
'd' : delay, 'n' : names}
ossys(gif_cmd)
opt_cmd = 'gifsicle -O2 %(n)s.gif -o %(n)s-opt.gif'% {'n' : names}
ossys(opt_cmd)
rm_cmd = 'rm %(n)s.gif'% {'n' : names}
ossys(rm_cmd)



# Calculate and record the (real) time taken for simulation
elapsed = (time.time() - start)
hms     = str(datetime.timedelta(seconds=elapsed))
hms_string = 'Total time for simulation was \n \
    %(hms)s (%(elapsed)12.3f seconds)'% {
            'hms'       : hms,
            'elapsed'   : elapsed, }
ax1 = fig.add_subplot(1, 1, 1)
ax1.plot(sub_ns, eta, 'k-o', linewidth=linesstrength)
ax1.set_xlabel('Substrate refractive index', fontsize=font)
ax1.set_ylabel(r'$\eta$ (%)', fontsize=font)
plt.savefig('eta_substrates')

# Animate spectra as a function of substrates.
from os import system as ossys
delay = 30  # delay between images in gif in hundredths of a second
names = 'Total_Spectra_stack'
gif_cmd = 'convert -delay %(d)i +dither -layers Optimize -colors 16 \
%(n)s*.pdf %(n)s.gif' % {
    'd': delay,
    'n': names
}
ossys(gif_cmd)
opt_cmd = 'gifsicle -O2 %(n)s.gif -o %(n)s-opt.gif' % {'n': names}
ossys(opt_cmd)
rm_cmd = 'rm %(n)s.gif' % {'n': names}
ossys(rm_cmd)

# Calculate and record the (real) time taken for simulation
elapsed = (time.time() - start)
hms = str(datetime.timedelta(seconds=elapsed))
hms_string = 'Total time for simulation was \n \
    %(hms)s (%(elapsed)12.3f seconds)' % {
    'hms': hms,
    'elapsed': elapsed,
}

python_log = open("python_log.log", "w")
Example #10
0
from platform import system as platsys
from util import instalar_dependencias

instalar_dependencias()

# Tente importar as bibliotecas mais especifícas
try:
    from matplotlib import animation, pyplot
    from matplotlib.patches import Wedge, Circle
    from Ponto import PontoPolar

except ModuleNotFoundError:

    # Se as bibliotecas estiverem instaladas, rechame o programa e limpe a tela
    if platsys().upper() == "WINDOWS":
        ossys("python main.py")

    else:
        ossys("python3 main.py")

    exit(0)

# Inicializa a estrutura do quadro onde os objetos serão desenhados
glob_fig = pyplot.figure()
glob_ax = glob_fig.add_subplot(111, polar=True)
glob_ax.grid(linewidth=0.75)

# Abertura do setor que realiza varredura
glob_abert_min = 45

# Número de graus que o ângulo de abertura se incrementará no sentido anti-horário